Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions functions/api/reader.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from '../../lib/server/guard.js';
import { CONTACT_EMAIL } from '../../lib/site-facts.mjs';
import { logResend } from '../../lib/server/resend.js';
import { ensureSubscriberShape, readerIdFromToken } from '../../lib/server/share.js';

const ACCESS_TTL_S = 60 * 60 * 24 * 400;
const CONSENT_TEXT = 'Also email me when new chapters and the print edition are ready.';
Expand Down Expand Up @@ -43,9 +44,13 @@ async function sendWelcome(env, email, link, nn) {
from: env.READER_FROM || env.CLAIM_NOTIFY_FROM || 'Knowware <onboarding@resend.dev>',
reply_to: CONTACT_EMAIL,
to: [email],
subject: 'Your Knowware chapters are unlocked',
subject: 'Chapter 1 is open. Share a voice to continue.',
text: [
'Every chapter of Knowware, including the capstone, is unlocked for you.',
`Chapter ${nn} of Knowware is open for you.`,
'',
'Each next chapter unlocks when you share one of its voices on',
'Instagram, LinkedIn, X or TikTok and paste the post back on the site.',
'That is how the book travels — one voice at a time.',
'',
`Continue Chapter ${nn}:`,
link,
Expand Down Expand Up @@ -131,6 +136,9 @@ async function handlePost({ request, env }) {
const token = newToken();
await env.CLAIMS.put(`reader:${await sha256(token)}`, JSON.stringify({ email, createdAt: now }), { expirationTtl: ACCESS_TTL_S });

// Chapter 1 is open at sign-up; 02–09 and x need a share receipt each.
// The readerId is a short hash of the token used in signatures and backlinks.
const readerId = await readerIdFromToken(token);
const subKey = `subscriber:${await sha256(email)}`;
const existing = JSON.parse((await env.CLAIMS.get(subKey)) || 'null');
const record = {
Expand All @@ -141,6 +149,8 @@ async function handlePost({ request, env }) {
updates: updates || existing?.updates || false,
consent: updates ? { text: CONSENT_TEXT, at: now } : existing?.consent || null,
country: request.cf?.country || '',
readerId: existing?.readerId || readerId,
unlocks: { ...(existing?.unlocks || {}), '01': true },
};
await env.CLAIMS.put(subKey, JSON.stringify(record));

Expand Down Expand Up @@ -191,6 +201,8 @@ async function handleGet({ request, env }) {
JSON.stringify({ email: record.email, createdAt: now, verifiedAt: record.verifiedAt, via: 'link' }),
{ expirationTtl: ACCESS_TTL_S },
);
// Back-fill readerId and unlocks on old subscriber records.
await ensureSubscriberShape(env, `subscriber:${await sha256(record.email)}`, deviceToken, now);
return redirect(next, accessCookies(deviceToken));
}

Expand Down
44 changes: 44 additions & 0 deletions functions/api/reader/claim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// POST /api/reader/claim — a reader pastes the URL of a post that quotes
// a voice from the chapter they are trying to unlock. The URL is the
// receipt; the chapter opens straight away. Verification of the post itself
// is lazy (see functions/cron/verify-receipts.js).

import { EMAIL_RE, TOKEN_RE, json, originAllowed, rateLimited, readCookie, readJson, sha256 } from '../../../lib/server/guard.js';
import { claimShare } from '../../../lib/server/share.js';

export async function onRequestPost({ request, env }) {
if (!originAllowed(request)) return json({ ok: false, error: 'Requests must come from the Knowware site.' }, 403);

const token = readCookie(request, 'kw_reader');
if (!TOKEN_RE.test(token)) return json({ ok: false, error: 'Sign up first.', code: 'auth' }, 401);

const parsed = await readJson(request, 4096);
if (parsed.response) return parsed.response;

if (await rateLimited(env, request, 'claim', 10, 3600)) {
return json({ ok: false, error: 'Too many claims from this connection. Try again in an hour.' }, 429, { 'Retry-After': '3600' });
}

const readerRaw = await env.CLAIMS.get(`reader:${await sha256(token)}`);
if (!readerRaw) return json({ ok: false, error: 'Your session expired. Sign in again.', code: 'auth' }, 401);
const reader = JSON.parse(readerRaw);
if (!reader.email || !EMAIL_RE.test(reader.email)) return json({ ok: false, error: 'Account missing an email.', code: 'auth' }, 401);
const subscriberKey = `subscriber:${await sha256(reader.email)}`;

const now = new Date().toISOString();
const result = await claimShare(env, {
readerToken: token,
subscriberKey,
chapter: parsed.data.chapter,
voice: parsed.data.voice,
url: parsed.data.url,
platform: parsed.data.platform,
now,
});

if (!result.ok) {
const status = result.code === 'auth' ? 401 : result.code === 'duplicate' || result.code === 'already' ? 409 : 400;
return json(result, status);
}
return json(result, 200);
}
23 changes: 23 additions & 0 deletions functions/api/reader/me.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// GET /api/reader/me — the current reader's unlocks, for the UI to decide
// whether to show the email form, the share pane, or the "continue" link.
// Returns an empty object with 200 for a signed-out visitor so the page
// doesn't flash the wrong state.

import { TOKEN_RE, json, readCookie, sha256 } from '../../../lib/server/guard.js';

export async function onRequestGet({ request, env }) {
const token = readCookie(request, 'kw_reader');
if (!TOKEN_RE.test(token)) return json({ signedIn: false, unlocks: {} }, 200);

const readerRaw = await env.CLAIMS.get(`reader:${await sha256(token)}`);
if (!readerRaw) return json({ signedIn: false, unlocks: {} }, 200);
const reader = JSON.parse(readerRaw);
if (!reader.email) return json({ signedIn: false, unlocks: {} }, 200);

const subRaw = await env.CLAIMS.get(`subscriber:${await sha256(reader.email)}`);
const sub = subRaw ? JSON.parse(subRaw) : null;
const unlocks = (sub && sub.unlocks) || { '01': true };
const readerId = (sub && sub.readerId) || (await sha256(token)).slice(0, 8);

return json({ signedIn: true, unlocks, readerId }, 200);
}
19 changes: 15 additions & 4 deletions functions/read/[slug]/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,31 @@
import chapters from '../../../lib/generated/full-chapters.js';
import pageHeaders from '../../../lib/generated/page-headers.js';
import { TOKEN_RE, readCookie, sha256 } from '../../../lib/server/guard.js';
import { ensureSubscriberShape, hasUnlock } from '../../../lib/server/share.js';

export async function onRequestGet({ request, env, params }) {
const slug = String(params.slug);
const html = /^(0[1-9]|x)$/.test(slug) ? chapters[slug] : undefined;
if (!html) return new Response('Not found', { status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });

const token = readCookie(request, 'kw_reader');
const ok = TOKEN_RE.test(token) && (await env.CLAIMS.get(`reader:${await sha256(token)}`));

if (!ok) {
const reject = () => {
const headers = new Headers({ Location: `/read/${slug}/#unlock`, 'Cache-Control': 'no-store' });
headers.append('Set-Cookie', 'kw_reader_ui=; Path=/; Max-Age=0; Secure; SameSite=Lax');
return new Response(null, { status: 302, headers });
}
};

if (!TOKEN_RE.test(token)) return reject();
const readerRaw = await env.CLAIMS.get(`reader:${await sha256(token)}`);
if (!readerRaw) return reject();
const reader = JSON.parse(readerRaw);
if (!reader.email) return reject();

// Per-chapter gate. Legacy subscribers (before this feature) have no
// `unlocks` field; ensureSubscriberShape back-fills unlocks['01'] = true,
// so they keep access to chapter 1 but must share to continue.
const sub = await ensureSubscriberShape(env, `subscriber:${await sha256(reader.email)}`, token, new Date().toISOString());
if (!hasUnlock(sub, slug)) return reject();

return new Response(html, {
headers: {
Expand Down
130 changes: 130 additions & 0 deletions lib/server/share.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Share-to-continue: per-chapter unlock via social post receipts.
// Logic lives here so Node tests can exercise it with a fake KV; the
// Cloudflare Functions in functions/api/reader/ just wire request/response
// to these helpers.

import { sha256 } from './guard.js';

export const CHAPTER_RE = /^(0[1-9]|x)$/;
export const CHAPTERS = ['01', '02', '03', '04', '05', '06', '07', '08', '09', 'x'];

// Each platform's URL pattern. The first capture group, when present, is a
// stable post id used for deduplication; otherwise we hash the full URL.
export const PLATFORMS = {
instagram: /^https?:\/\/(?:www\.)?instagram\.com\/(?:p|reel)\/([A-Za-z0-9_-]+)\/?(?:\?.*)?$/,
linkedin: /^https?:\/\/(?:www\.)?linkedin\.com\/(?:posts\/[^/?#]+|feed\/update\/urn:li:activity:\d+)\/?(?:\?.*)?$/,
x: /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\/[^/]+\/status\/(\d+)\/?(?:\?.*)?$/,
tiktok: /^https?:\/\/(?:www\.)?tiktok\.com\/@[^/]+\/video\/(\d+)\/?(?:\?.*)?$/,
};

export function detectPlatform(url) {
if (typeof url !== 'string' || url.length > 2048) return null;
for (const [name, re] of Object.entries(PLATFORMS)) {
if (re.test(url)) return name;
}
return null;
}

// Normalise so the same post typed two ways (with/without trailing slash,
// query string, http vs https) hashes to the same key.
export function canonicalUrl(url, platform) {
const re = PLATFORMS[platform];
if (!re) return url;
const m = url.match(re);
if (!m) return url;
if (platform === 'instagram') return `https://instagram.com/p/${m[1]}`;
if (platform === 'x') return `https://x.com/i/status/${m[1]}`;
if (platform === 'tiktok') return `https://tiktok.com/video/${m[1]}`;
// LinkedIn URL shapes vary; strip query string and trailing slash.
return url.replace(/[/?#].*$/, '').replace(/\/$/, '');
}

// The reader id is a short, deterministic hash of the reader's access token.
// It appears in signatures and backlinks so a shared post can be attributed
// to the sharer without exposing their token.
export async function readerIdFromToken(token) {
return (await sha256(token)).slice(0, 8);
}

export async function urlHash(canon) {
return (await sha256(canon)).slice(0, 24);
}

export function signatureFor(voiceId, readerId) {
return `#knowware-v${voiceId}-r/${readerId}`;
}

export function backlinkFor(voiceId, readerId, origin = 'https://knowware.systems') {
return `${origin}/v/${voiceId}?r=${readerId}`;
}

// Submit a share receipt for a chapter. Returns:
// { ok: true, next } — chapter unlocked
// { ok: false, error, code } — validation / duplicate / already-claimed
// env.CLAIMS is the KV binding; now is an ISO timestamp.
export async function claimShare(env, { readerToken, subscriberKey, chapter, voice, url, platform, now }) {
const ch = String(chapter || '').toLowerCase();
if (!CHAPTER_RE.test(ch)) return { ok: false, error: 'Unknown chapter.', code: 'chapter' };
if (ch === '01') return { ok: false, error: 'Chapter 1 opens with sign-up, no share needed.', code: 'chapter' };

const v = Number(voice);
if (!Number.isInteger(v) || v < 1 || v > 81) return { ok: false, error: 'Pick one of the suggested voices.', code: 'voice' };

const detected = detectPlatform(url);
if (!detected) return { ok: false, error: 'That URL does not look like an Instagram, LinkedIn, X or TikTok post.', code: 'url' };
if (platform && platform !== detected) return { ok: false, error: 'The URL does not match the platform selected.', code: 'platform' };

// Look up the subscriber record keyed by email hash. The caller passed the
// key because it already looked up the reader token.
const subRaw = await env.CLAIMS.get(subscriberKey);
if (!subRaw) return { ok: false, error: 'Sign up first.', code: 'auth' };
const sub = JSON.parse(subRaw);
const readerId = sub.readerId || (await readerIdFromToken(readerToken));

// One receipt per reader per chapter: refuse the second attempt.
const reserveKey = `reader-receipts:${readerId}:${ch}`;
if (await env.CLAIMS.get(reserveKey)) return { ok: false, error: 'This chapter is already unlocked for you.', code: 'already' };

const canon = canonicalUrl(url, detected);
const uh = await urlHash(canon);
const receiptKey = `receipt:${uh}`;

// Refuse the same URL across readers.
if (await env.CLAIMS.get(receiptKey)) return { ok: false, error: 'That post has already been used.', code: 'duplicate' };

const receipt = {
readerId, chapter: ch, voice: v, platform: detected, url: canon, postedAt: now,
status: 'pending',
};
await env.CLAIMS.put(receiptKey, JSON.stringify(receipt));
await env.CLAIMS.put(reserveKey, uh);

// Flip the unlock on the subscriber record.
sub.readerId = readerId;
sub.unlocks = { ...(sub.unlocks || {}), [ch]: true };
sub.updatedAt = now;
await env.CLAIMS.put(subscriberKey, JSON.stringify(sub));

return { ok: true, next: `/read/${ch}/full` };
}

// Does this reader have the given chapter unlocked?
// Chapter 1 is always open once they signed up (the welcome flow sets it).
export function hasUnlock(subscriber, chapter) {
if (!subscriber) return false;
const unlocks = subscriber.unlocks || {};
return unlocks[chapter] === true;
}

// Called by functions/api/reader.js on sign-up / link verification so the
// subscriber record always has readerId + unlocks[01] set.
export async function ensureSubscriberShape(env, subscriberKey, token, now) {
const raw = await env.CLAIMS.get(subscriberKey);
if (!raw) return null;
const sub = JSON.parse(raw);
let dirty = false;
if (!sub.readerId) { sub.readerId = await readerIdFromToken(token); dirty = true; }
if (!sub.unlocks || sub.unlocks['01'] !== true) { sub.unlocks = { ...(sub.unlocks || {}), '01': true }; dirty = true; }
if (dirty) { sub.updatedAt = now; await env.CLAIMS.put(subscriberKey, JSON.stringify(sub)); }
return sub;
}
Loading
Loading