From 31a29402e38cbfb06a063a1ed51f709b98a37b76 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 17:52:19 +0000 Subject: [PATCH] Add an owner-only gate for private notes. Public pages stay cached and unchanged. A Pages Function verifies a Cloudflare Access token before it shows the private entry or reads a separate deployment. This repository keeps an empty catalog and does not contain the owner identity. Co-authored-by: Shumin --- .github/workflows/ci.yml | 3 + .gitignore | 7 + README.md | 2 +- astro.config.mjs | 4 +- deploy/private-notes/README.md | 23 ++ deploy/private-notes/build-catalog.mjs | 53 +++ deploy/private-notes/build-catalog.test.mjs | 33 ++ deploy/private-notes/catalog.json | 3 + deploy/private-notes/notes/README.md | 5 + deploy/private-notes/src/worker.test.ts | 107 ++++++ deploy/private-notes/src/worker.ts | 58 +++ deploy/private-notes/wrangler.toml.example | 8 + docs/cloudflare-pages.md | 2 + docs/private-notes.md | 110 ++++++ functions/_middleware.ts | 17 + functions/lib/access.test.ts | 150 ++++++++ functions/lib/access.ts | 342 +++++++++++++++++ functions/lib/catalog.ts | 62 +++ functions/lib/chrome.built.test.ts | 22 ++ functions/lib/chrome.ts | 41 ++ functions/lib/gate.test.ts | 247 ++++++++++++ functions/lib/gate.ts | 399 ++++++++++++++++++++ functions/lib/html.ts | 132 +++++++ functions/lib/jwt-fixture.ts | 61 +++ functions/lib/markdown.test.ts | 24 ++ functions/lib/markdown.ts | 114 ++++++ functions/lib/origin.test.ts | 31 ++ functions/lib/origin.ts | 59 +++ package.json | 1 + public/_headers | 11 + scripts/check-public-boundary.mjs | 130 +++++++ src/components/Header.astro | 17 + src/layouts/BaseLayout.astro | 2 +- src/pages/auth/login.astro | 31 ++ src/pages/auth/logout.astro | 31 ++ src/pages/robots.txt.ts | 3 +- 36 files changed, 2341 insertions(+), 4 deletions(-) create mode 100644 deploy/private-notes/README.md create mode 100644 deploy/private-notes/build-catalog.mjs create mode 100644 deploy/private-notes/build-catalog.test.mjs create mode 100644 deploy/private-notes/catalog.json create mode 100644 deploy/private-notes/notes/README.md create mode 100644 deploy/private-notes/src/worker.test.ts create mode 100644 deploy/private-notes/src/worker.ts create mode 100644 deploy/private-notes/wrangler.toml.example create mode 100644 docs/private-notes.md create mode 100644 functions/_middleware.ts create mode 100644 functions/lib/access.test.ts create mode 100644 functions/lib/access.ts create mode 100644 functions/lib/catalog.ts create mode 100644 functions/lib/chrome.built.test.ts create mode 100644 functions/lib/chrome.ts create mode 100644 functions/lib/gate.test.ts create mode 100644 functions/lib/gate.ts create mode 100644 functions/lib/html.ts create mode 100644 functions/lib/jwt-fixture.ts create mode 100644 functions/lib/markdown.test.ts create mode 100644 functions/lib/markdown.ts create mode 100644 functions/lib/origin.test.ts create mode 100644 functions/lib/origin.ts create mode 100644 scripts/check-public-boundary.mjs create mode 100644 src/pages/auth/login.astro create mode 100644 src/pages/auth/logout.astro diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fa6ae7..fccb550 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,4 +15,7 @@ jobs: node-version: 22 cache: npm - run: npm ci + - run: npm test - run: npm run build + - run: node scripts/check-public-boundary.mjs --dist + - run: node --experimental-strip-types --test functions/lib/chrome.built.test.ts diff --git a/.gitignore b/.gitignore index fef4ead..4f7d115 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,13 @@ pnpm-debug.log* # environment variables .env .env.production +.dev.vars +.dev.vars.* + +# A local checkout of private notes at the repo root. Never part of this public site. +/private-notes/ +deploy/private-notes/notes/* +!deploy/private-notes/notes/README.md # macOS-specific files .DS_Store diff --git a/README.md b/README.md index f594430..bb1b797 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ What changed for that skill: ## Deploy -Cloudflare Pages, static output. See [docs/cloudflare-pages.md](docs/cloudflare-pages.md). Node 22, build `npm run build`, publish `dist`. +Cloudflare Pages, static output, plus a Pages Function that gates private notes. See [docs/cloudflare-pages.md](docs/cloudflare-pages.md) and [docs/private-notes.md](docs/private-notes.md). Node 22, build `npm run build`, publish `dist`. Private notes are not part of this build. ## Theme diff --git a/astro.config.mjs b/astro.config.mjs index 922ef55..fc9ef68 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -31,7 +31,9 @@ export default defineConfig({ integrations: [ mdx(), - sitemap(), + sitemap({ + filter: (page) => !page.includes('/auth/'), + }), ], // Tailwind CSS v4 is wired via its Vite plugin (the former @astrojs/tailwind diff --git a/deploy/private-notes/README.md b/deploy/private-notes/README.md new file mode 100644 index 0000000..1ec1100 --- /dev/null +++ b/deploy/private-notes/README.md @@ -0,0 +1,23 @@ +# Private notes worker + +This directory is the isolated notes API. It is not deployed with the public Pages project. The public project only learns the origin later, through `PRIVATE_NOTES_ORIGIN`. + +The catalog in this repository is empty. Fill it from a private repository’s build, not from the public site’s `npm run build`. + +## Later, in a private repository + +Copy these paths without rearranging them: + +- `functions/lib/access.ts` +- `functions/lib/catalog.ts` +- `deploy/private-notes/` + +Add `deploy/private-notes/notes/.md`, then run: + +```bash +node deploy/private-notes/build-catalog.mjs +``` + +Deploy that repository from its own Cloudflare project. Use `wrangler.toml.example` as the starting point. Set `ACCESS_TEAM_DOMAIN`, `ACCESS_AUD`, and `OWNER_EMAIL` there. They must match the public production environment. Do not commit them. + +See [docs/private-notes.md](../../docs/private-notes.md). diff --git a/deploy/private-notes/build-catalog.mjs b/deploy/private-notes/build-catalog.mjs new file mode 100644 index 0000000..666e1b5 --- /dev/null +++ b/deploy/private-notes/build-catalog.mjs @@ -0,0 +1,53 @@ +/** + * Turns markdown files in a private repository into catalog.json. + * The public site does not run this, and this repository has no notes to read. + */ + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const PLANTED = /^\d{4}-\d{2}-\d{2}$/; +const MAX_BODY = 100_000; +const MAX_TITLE = 200; + +export function buildCatalog(notesDir) { + /** @type {{ slug: string, title: string, planted: string, body: string }[]} */ + const notes = []; + if (!fs.existsSync(notesDir)) return { notes }; + for (const name of fs.readdirSync(notesDir)) { + if (!name.endsWith('.md') || name === 'README.md') continue; + const slug = name.slice(0, -'.md'.length); + if (!SLUG.test(slug)) continue; + const parsed = parseNote(fs.readFileSync(path.join(notesDir, name), 'utf8')); + if (!parsed) continue; + notes.push({ slug, ...parsed }); + } + notes.sort((a, b) => b.planted.localeCompare(a.planted) || a.slug.localeCompare(b.slug)); + return { notes }; +} + +function parseNote(raw) { + const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(raw); + if (!match) return null; + /** @type {Record} */ + const data = {}; + for (const line of match[1].split(/\r?\n/)) { + const split = line.indexOf(':'); + if (split === -1) continue; + data[line.slice(0, split).trim()] = line.slice(split + 1).trim(); + } + const title = (data.title ?? '').replace(/[\r\n]+/g, ' ').trim(); + const planted = data.planted ?? ''; + const body = match[2] ?? ''; + if (!title || title.length > MAX_TITLE || !PLANTED.test(planted) || body.length > MAX_BODY) return null; + return { title, planted, body }; +} + +const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; +if (isDirectRun) { + const root = path.dirname(fileURLToPath(import.meta.url)); + const catalog = buildCatalog(path.join(root, 'notes')); + fs.writeFileSync(path.join(root, 'catalog.json'), `${JSON.stringify(catalog, null, 2)}\n`); +} diff --git a/deploy/private-notes/build-catalog.test.mjs b/deploy/private-notes/build-catalog.test.mjs new file mode 100644 index 0000000..1ec8b3e --- /dev/null +++ b/deploy/private-notes/build-catalog.test.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, it } from 'node:test'; +import { buildCatalog } from './build-catalog.mjs'; + +describe('private catalog build', () => { + it('reads a temporary directory and ignores unsafe filenames', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'private-notes-')); + fs.writeFileSync(path.join(dir, 'README.md'), 'do not publish\n'); + fs.writeFileSync(path.join(dir, 'Hello World.md'), '---\ntitle: No\nplanted: 2026-01-01\n---\nnope\n'); + fs.writeFileSync( + path.join(dir, 'fixture-note.md'), + '---\ntitle: Fixture\nplanted: 2026-11-01\n---\n\n', + ); + const catalog = buildCatalog(dir); + assert.deepEqual(catalog.notes, [ + { + slug: 'fixture-note', + title: 'Fixture', + planted: '2026-11-01', + body: '\n', + }, + ]); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('sees no notes in this public repository', () => { + const notesDir = path.join(path.dirname(new URL(import.meta.url).pathname), 'notes'); + assert.deepEqual(buildCatalog(notesDir), { notes: [] }); + }); +}); diff --git a/deploy/private-notes/catalog.json b/deploy/private-notes/catalog.json new file mode 100644 index 0000000..8de43c7 --- /dev/null +++ b/deploy/private-notes/catalog.json @@ -0,0 +1,3 @@ +{ + "notes": [] +} diff --git a/deploy/private-notes/notes/README.md b/deploy/private-notes/notes/README.md new file mode 100644 index 0000000..b054df2 --- /dev/null +++ b/deploy/private-notes/notes/README.md @@ -0,0 +1,5 @@ +# Notes stay out of the public repository + +This directory is empty on purpose. Do not add notes here. + +The public site and its preview deployments build from the public repository. A note committed beside this file would be one `git add` away from that build. Put notes only in the private repository, then run `build-catalog.mjs` there before deploying the private worker. diff --git a/deploy/private-notes/src/worker.test.ts b/deploy/private-notes/src/worker.test.ts new file mode 100644 index 0000000..ae2c335 --- /dev/null +++ b/deploy/private-notes/src/worker.test.ts @@ -0,0 +1,107 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { before, beforeEach, describe, it } from 'node:test'; +import { clearJwksCache, type FetchLike } from '../../../functions/lib/access.ts'; +import { FIXTURE_NOTE_BODY, makeAccessSigner, ownerClaims, TEST_ENV, type AccessSigner } from '../../../functions/lib/jwt-fixture.ts'; +import { handlePrivateNotes } from './worker.ts'; + +const NOW = Date.parse('2026-11-22T00:00:00Z'); +const CATALOG = { + notes: [ + { + slug: 'fixture-note', + title: 'Fixture note', + planted: '2026-11-01', + body: FIXTURE_NOTE_BODY, + }, + ], +}; + +describe('private notes deployment', () => { + let signer: AccessSigner; + + before(async () => { + signer = await makeAccessSigner(); + }); + + beforeEach(() => clearJwksCache()); + + it('ships an empty catalog from this public repository', () => { + const catalog = JSON.parse(readFileSync(new URL('../catalog.json', import.meta.url), 'utf8')) as { notes: unknown[] }; + assert.deepEqual(catalog.notes, []); + }); + + it('returns notes only to the verified owner and never caches them', async () => { + const deps = { fetch: jwks(signer), now: () => NOW }; + const token = await signer.sign(ownerClaims(NOW)); + const owner = await call('/index.json', deps, token); + assert.equal(owner.status, 200); + const index = (await owner.json()) as { notes: Array<{ body?: string }> }; + assert.equal(index.notes[0]?.body, undefined); + assert.equal(owner.headers.get('cache-control'), 'private, no-store'); + assert.equal(owner.headers.get('cdn-cache-control'), 'no-store'); + + const note = await call('/notes/fixture-note.json', deps, token); + assert.match(await note.text(), new RegExp(FIXTURE_NOTE_BODY)); + + const anon = await call('/notes/fixture-note.json', deps); + assert.equal(anon.status, 404); + assert.equal((await anon.text()).includes(FIXTURE_NOTE_BODY), false); + + const other = await call('/notes/fixture-note.json', deps, await signer.sign(ownerClaims(NOW, 'reader@fixture.test'))); + assert.equal(other.status, 403); + assert.equal((await other.text()).includes(FIXTURE_NOTE_BODY), false); + + const expired = await call( + '/index.json', + deps, + await signer.sign({ ...ownerClaims(NOW), exp: Math.floor(NOW / 1000) - 600 }), + ); + assert.equal(expired.status, 404); + assert.equal((await expired.text()).includes(FIXTURE_NOTE_BODY), false); + + const spoof = await handlePrivateNotes( + new Request('https://private-notes.fixture.test/index.json', { + headers: { 'Cf-Access-Authenticated-User-Email': 'owner@fixture.test' }, + }), + TEST_ENV, + CATALOG, + deps, + ); + assert.equal(spoof.status, 404); + assert.equal((await spoof.text()).includes(FIXTURE_NOTE_BODY), false); + }); + + it('fails closed when Access is not configured', async () => { + const token = await signer.sign(ownerClaims(NOW)); + const response = await handlePrivateNotes( + new Request('https://private-notes.fixture.test/index.json', { + headers: { 'Cf-Access-Jwt-Assertion': token }, + }), + {}, + CATALOG, + { fetch: jwks(signer), now: () => NOW }, + ); + assert.equal(response.status, 404); + assert.equal((await response.text()).includes(FIXTURE_NOTE_BODY), false); + }); +}); + +function call(path: string, deps: { fetch: FetchLike; now: () => number }, token?: string): Promise { + return handlePrivateNotes( + new Request(`https://private-notes.fixture.test${path}`, { + headers: token ? { 'Cf-Access-Jwt-Assertion': token } : {}, + }), + TEST_ENV, + CATALOG, + deps, + ); +} + +function jwks(signer: AccessSigner): FetchLike { + return async () => + new Response(JSON.stringify(signer.jwks()), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} diff --git a/deploy/private-notes/src/worker.ts b/deploy/private-notes/src/worker.ts new file mode 100644 index 0000000..64f9a16 --- /dev/null +++ b/deploy/private-notes/src/worker.ts @@ -0,0 +1,58 @@ +/** + * Isolated notes API. It answers only after the same Access token check as + * the public gate. The committed catalog is empty; a private repository + * fills it at its own build, which the public site never runs. + */ + +import { identify, type AccessDeps, type GateEnv } from '../../../functions/lib/access.ts'; +import { parseCatalog, type PrivateNote } from '../../../functions/lib/catalog.ts'; +import catalogJson from '../catalog.json' with { type: 'json' }; + +const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +export function handlePrivateNotes( + request: Request, + env: GateEnv, + catalog: unknown, + deps: AccessDeps = {}, +): Promise { + return route(request, env, parseCatalog(catalog), deps); +} + +export default { + fetch(request: Request, env: GateEnv): Promise { + return handlePrivateNotes(request, env, catalogJson); + }, +}; + +async function route(request: Request, env: GateEnv, notes: readonly PrivateNote[], deps: AccessDeps): Promise { + if (request.method !== 'GET' && request.method !== 'HEAD') return json({ error: 'not_found' }, 405, request.method); + const identity = await identify(request, env, deps); + if (identity.status !== 'authenticated') return json({ error: 'not_found' }, 404, request.method); + if (!identity.owner) return json({ error: 'not_found' }, 403, request.method); + const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/'; + if (path === '/index.json') { + const index = notes + .map(({ slug, title, planted }) => ({ slug, title, planted })) + .sort((a, b) => b.planted.localeCompare(a.planted) || a.slug.localeCompare(b.slug)); + return json({ notes: index }, 200, request.method); + } + const slug = /^\/notes\/([a-z0-9]+(?:-[a-z0-9]+)*)\.json$/.exec(path)?.[1]; + if (!slug || !SLUG.test(slug)) return json({ error: 'not_found' }, 404, request.method); + const note = notes.find((item) => item.slug === slug); + if (!note) return json({ error: 'not_found' }, 404, request.method); + return json({ slug: note.slug, title: note.title, planted: note.planted, body: note.body }, 200, request.method); +} + +function json(body: unknown, status: number, method: string): Response { + const headers = new Headers({ + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'private, no-store', + 'cdn-cache-control': 'no-store', + 'cloudflare-cdn-cache-control': 'no-store', + 'x-content-type-options': 'nosniff', + 'x-robots-tag': 'noindex, nofollow', + 'referrer-policy': 'no-referrer', + }); + return new Response(method === 'HEAD' ? null : JSON.stringify(body), { status, headers }); +} diff --git a/deploy/private-notes/wrangler.toml.example b/deploy/private-notes/wrangler.toml.example new file mode 100644 index 0000000..3006c98 --- /dev/null +++ b/deploy/private-notes/wrangler.toml.example @@ -0,0 +1,8 @@ +# Copy to wrangler.toml in the private repository only. +# Do not add wrangler.toml to the public Pages project. +# Set ACCESS_TEAM_DOMAIN, ACCESS_AUD, and OWNER_EMAIL in that project's +# dashboard. Do not commit the values. + +name = "private-notes" +main = "src/worker.ts" +compatibility_date = "2025-04-01" diff --git a/docs/cloudflare-pages.md b/docs/cloudflare-pages.md index 551373f..4ab71d0 100644 --- a/docs/cloudflare-pages.md +++ b/docs/cloudflare-pages.md @@ -16,3 +16,5 @@ In the Pages project (funfun.zone): The old feed URL `/rss.xml` redirects to `/feed.xml` via `public/_redirects`. `public/appcast.xml` is the Claude Island Sparkle feed. Leave it in `public/` so `https://funfun.zone/appcast.xml` keeps working. + +Private notes are not part of this build. The gate and the separate deployment are described in [private-notes.md](private-notes.md). Do not point this Pages project at a private notes repository. diff --git a/docs/private-notes.md b/docs/private-notes.md new file mode 100644 index 0000000..30fb568 --- /dev/null +++ b/docs/private-notes.md @@ -0,0 +1,110 @@ +# Private notes + +The public garden stays public. Private notes are a separate deployment. This repository does not contain them, and it does not know the owner’s Google account. + +Nothing in this pull request turns live authentication on. Cloudflare Access, Google, and the private deployment still have to be configured by hand. Until those values exist, the gate fails closed: the private entry is absent, and `/private/` responds as a missing page. + +## Why Access on its own is not enough + +Cloudflare Access can sit in front of a path and demand a Google login. It does not rewrite the public HTML, and the cache key for a public page ignores cookies. The header is the same document for every visitor. The `CF_Authorization` cookie is HttpOnly, so the browser cannot safely decide what to draw. + +Hiding a link with client-side script would also flash, and anyone could spoof it. The entry is inserted by a Pages Function after it verifies the Access token. Anonymous HTML is returned untouched, so it can stay cached. A response that saw a token is `Cache-Control: private, no-store` and `CDN-Cache-Control: no-store`. + +Access is still the login. This site does not implement Google’s token exchange, does not store a refresh token, and does not set its own session cookie. + +## Two deployments + +| | Public site | Private notes | +| --- | --- | --- | +| Repository | this one, public | a private repository you create later | +| Cloudflare project | the existing Pages project | a new project, not created here | +| What it stores | garden, public notes, the gate | note markdown, generated at that project’s build | +| Who can read it | everyone | the signed-in owner, after the token check | + +The public Pages build must not check out the private repository. A submodule, a git dependency, or a build-step clone would copy notes into the public workspace and could publish them. `scripts/check-public-boundary.mjs` fails the build if a submodule or a filled catalog appears. The private repository’s name is not chosen and this change does not create it. + +`PRIVATE_NOTES_ORIGIN` is the https origin of the private deployment. It is not a secret and it is not authorization. The private worker verifies the same Access token again. The public function only fetches it after the token matches `OWNER_EMAIL`, and it does not put that origin in the HTML. + +`*.pages.dev`, including the public project’s default hostname and preview URLs, does not serve the entry or the notes unless `PRIVATE_NOTES_ALLOW_PREVIEW=true`. Leave that unset. + +## What you have to provide + +This repository has no owner email, team name, or Access audience. Do not copy them from a commit, a GitHub profile, or a guess. Set them in the Cloudflare dashboard. + +1. `ACCESS_TEAM_DOMAIN` — `https://.cloudflareaccess.com` +2. `ACCESS_AUD` — the Access application’s AUD tag +3. `OWNER_EMAIL` — the Google account you will sign in with +4. `PRIVATE_NOTES_ORIGIN` — `https://` with no path, after that host exists + +Google’s OAuth client id and client secret are entered only in Zero Trust → Integrations → Identity providers → Google. They are not Pages environment variables and they do not belong in this repository. + +## Checklist + +### Google + +1. In Google Cloud, create an OAuth client of type Web application. You need this because Access’s Google login uses your client. The site never sees it. +2. Authorized JavaScript origin: `https://.cloudflareaccess.com` +3. Authorized redirect URI: `https://.cloudflareaccess.com/cdn-cgi/access/callback` +4. Audience type External, unless you are using Google Workspace on purpose. +5. Copy the client id and client secret into the Zero Trust Google identity provider. Enable PKCE if you want it. Do not put the secret in git, in Pages, or in the browser. + +### Cloudflare Access + +1. Create one self-hosted application. Deny is the default. +2. Add a public hostname for `funfun.zone` with path `private`, and another for path `auth`. Leave the rest of the site unprotected. +3. If the dashboard lets this same application include the private deployment’s hostname, add that hostname with an empty path so the whole host is gated and both hosts share one AUD. A second application has a different AUD. The public function forwards the token it already verified, and that token will not satisfy a different AUD. If you cannot share the application, do not put a second Access policy in front of the private host; the worker still rejects requests without this application’s token. +4. Allow policy: Include, Selector Emails, Value the same address as `OWNER_EMAIL`. Identity provider: the Google provider from the previous section. A wider “any Google account” policy still does not show notes, because the function compares the token’s email claim with `OWNER_EMAIL`. +5. Session duration, in all three places Access lets you set it: one month. That is the longest Access will issue. + - Zero Trust → Access controls → Access settings → global session duration + - The application’s session duration + - The allow policy’s session duration +6. Optional: turn on instant authentication so Google is the only prompt. +7. Do not add a Bypass policy for `/private` or `/auth`. +8. Do not add a Cache Everything rule, and do not ignore cache-control headers. The owner’s HTML must not be stored for everyone else. + +When the application token expires, Access can renew it while the global session is still valid. When the global session ends, Google asks again. This code honors the token’s `exp`. It allows 60 seconds of clock skew and refuses a token whose remaining life is longer than 32 days. It does not extend a session. + +### Pages environment + +On the **production** environment of the public Pages project only: + +- `ACCESS_TEAM_DOMAIN` +- `ACCESS_AUD` +- `OWNER_EMAIL` +- `PRIVATE_NOTES_ORIGIN` + +Do not copy those onto preview deployments. Preview hostnames stay closed even if the variables leak there, unless you also set `PRIVATE_NOTES_ALLOW_PREVIEW=true`. + +There is no service token. A service token would let the public function read notes without your Google login, and a leaked token would skip the owner check. + +### Private repository and deployment + +Do this only when you want notes to exist. This pull request does not do it. + +1. Create a private git repository. Pick the name then. +2. Copy this layout into it, unchanged, so the imports still resolve: + - `functions/lib/access.ts` + - `functions/lib/catalog.ts` + - `deploy/private-notes/` +3. Put notes in `deploy/private-notes/notes/.md`. A slug is lowercase letters, digits, and single hyphens. Frontmatter needs `title` and `planted: YYYY-MM-DD`. The body is a small markdown subset: headings, lists, quotes, code, emphasis, and https or note links. Images are not loaded. +4. Run `node deploy/private-notes/build-catalog.mjs` in that repository. It writes `catalog.json`, which the worker bundles. Do not run that script in this public repository as part of `npm run build`. +5. Create a new Cloudflare Workers or Pages project connected to the private repository only. `deploy/private-notes/wrangler.toml.example` shows the shape. It has no account id and no secrets. +6. Set `ACCESS_TEAM_DOMAIN`, `ACCESS_AUD`, and `OWNER_EMAIL` on that project to the same values as production. Do not give the public Pages project a git credential for the private repository. +7. Deploy the private project. Its `*.pages.dev` hostname is safe to use as `PRIVATE_NOTES_ORIGIN` only because the worker returns 404 without a verified owner token. Add that hostname to the Access application as well when the dashboard allows one shared AUD. +8. Set `PRIVATE_NOTES_ORIGIN` on the public production environment. The nav entry appears after you sign in on `https://funfun.zone` and the token matches. + +Notes never go in `src/content/`, `public/`, or this catalog. Public notes, their URLs, the garden, and `/feed.xml` are unchanged. + +## Sign-in + +The header shows **Sign in**. It links to `/auth/login/`. After Access sets a valid owner token, the next HTML response includes **Private Notes** and **Sign out**. A different Google account gets **Sign out** and a 403 on `/private/`, with no note text. A missing, expired, or forged token is treated as logged out. `Cf-Access-Authenticated-User-Email` alone is ignored. + +Sign out sends the browser to `/cdn-cgi/access/logout` on the site, which clears the Access cookie. + +## Limits + +- Live auth does not work until the checklist is done. This change cannot prove a real Google login. +- The readable page is rendered on the public host, inside the existing shell, from JSON the private deployment returns. The browser does not call the private host and does not see its URL. +- Markdown is intentionally smaller than the garden’s pipeline. Wikilinks, math, and images are not part of it. +- A stolen Access token can be replayed until `exp`. The cookie is HttpOnly and Secure. There is no second, longer session in this site. +- `localhost` is allowed to open the gate so `wrangler pages dev` can be tried later. Production requests are not localhost. diff --git a/functions/_middleware.ts b/functions/_middleware.ts new file mode 100644 index 0000000..02db095 --- /dev/null +++ b/functions/_middleware.ts @@ -0,0 +1,17 @@ +/** + * Runs on every Pages request, including static files. Public responses are + * returned untouched unless the request actually presents an Access token. + */ + +import type { GateEnv } from './lib/access.ts'; +import { handleGate } from './lib/gate.ts'; + +interface MiddlewareContext { + request: Request; + env: GateEnv; + next: () => Promise; +} + +export function onRequest(context: MiddlewareContext): Promise { + return handleGate(context.request, context.env, () => context.next()); +} diff --git a/functions/lib/access.test.ts b/functions/lib/access.test.ts new file mode 100644 index 0000000..ab8442b --- /dev/null +++ b/functions/lib/access.test.ts @@ -0,0 +1,150 @@ +import assert from 'node:assert/strict'; +import { before, beforeEach, describe, it } from 'node:test'; +import { + accessLoginUrl, + accessLogoutUrl, + clearJwksCache, + identify, + readAccessConfig, + safeNextPath, + verifyAccessJwt, +} from './access.ts'; +import { makeAccessSigner, ownerClaims, TEST_ENV, type AccessSigner } from './jwt-fixture.ts'; + +const NOW = Date.parse('2026-11-22T00:00:00Z'); + +describe('Access token verification', () => { + let signer: AccessSigner; + + before(async () => { + signer = await makeAccessSigner(); + }); + + beforeEach(() => { + clearJwksCache(); + }); + + it('rejects placeholder configuration', () => { + assert.equal(readAccessConfig({}), null); + assert.equal(readAccessConfig({ ...TEST_ENV, OWNER_EMAIL: 'replace_with_owner_google_email' }), null); + assert.equal(readAccessConfig({ ...TEST_ENV, OWNER_EMAIL: 'person@example.com' }), null); + assert.equal(readAccessConfig({ ...TEST_ENV, ACCESS_TEAM_DOMAIN: 'https://your-team.cloudflareaccess.com' }), null); + assert.equal(readAccessConfig({ ...TEST_ENV, ACCESS_AUD: 'not-an-aud' }), null); + assert.ok(readAccessConfig(TEST_ENV)); + }); + + it('accepts an owner token and rejects the wrong Google account', async () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + const owner = await signer.sign(ownerClaims(NOW)); + const other = await signer.sign(ownerClaims(NOW, 'Other@fixture.test')); + const deps = { fetch: jwks(signer), now: () => NOW }; + assert.equal((await verifyAccessJwt(owner, config, deps))?.owner, true); + const verified = await verifyAccessJwt(other, config, deps); + assert.equal(verified?.owner, false); + assert.equal(verified?.email, 'other@fixture.test'); + }); + + it('fails closed for expiry, lifetime, audience, issuer, and bad signatures', async () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + const deps = { fetch: jwks(signer), now: () => NOW }; + const expired = await signer.sign({ ...ownerClaims(NOW), exp: Math.floor(NOW / 1000) - 120 }); + const tooLong = await signer.sign({ ...ownerClaims(NOW), exp: Math.floor(NOW / 1000) + 40 * 24 * 60 * 60 }); + const early = await signer.sign({ ...ownerClaims(NOW), nbf: Math.floor(NOW / 1000) + 120 }); + const wrongAud = await signer.sign({ ...ownerClaims(NOW), aud: 'b'.repeat(64) }); + const wrongIss = await signer.sign({ ...ownerClaims(NOW), iss: 'https://evil.cloudflareaccess.com' }); + const otherKey = await makeAccessSigner('test-key'); + const forged = await otherKey.sign(ownerClaims(NOW)); + for (const token of [expired, tooLong, early, wrongAud, wrongIss, forged]) { + assert.equal(await verifyAccessJwt(token, config, deps), null); + } + }); + + it('rejects none and HMAC algorithms before verification', async () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + const deps = { fetch: jwks(signer), now: () => NOW }; + const none = craft({ alg: 'none', kid: 'test-key' }, ownerClaims(NOW)); + const hmac = craft({ alg: 'HS256', kid: 'test-key' }, ownerClaims(NOW)); + const jku = await signer.sign(ownerClaims(NOW), { jku: 'https://evil.example/jwks' }); + assert.equal(await verifyAccessJwt(none, config, deps), null); + assert.equal(await verifyAccessJwt(hmac, config, deps), null); + assert.equal((await verifyAccessJwt(jku, config, deps))?.owner, true); + }); + + it('does not treat a service token or a failed JWKS fetch as the owner', async () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + const service = await signer.sign({ ...ownerClaims(NOW), email: undefined, common_name: 'ci' }); + assert.equal((await verifyAccessJwt(service, config, { fetch: jwks(signer), now: () => NOW }))?.owner, false); + clearJwksCache(); + const down = async () => new Response('no', { status: 500 }); + assert.equal(await verifyAccessJwt(await signer.sign(ownerClaims(NOW)), config, { fetch: down, now: () => NOW }), null); + }); + + it('refetches JWKS when the token key id is new', async () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + let calls = 0; + const fetch = async () => { + calls += 1; + const body = calls === 1 ? { keys: [] } : signer.jwks(); + if (calls === 1) return new Response(JSON.stringify({ keys: [{ kid: 'old', kty: 'RSA' }] }), { status: 200 }); + return new Response(JSON.stringify(body), { status: 200 }); + }; + const token = await signer.sign(ownerClaims(NOW)); + assert.equal((await verifyAccessJwt(token, config, { fetch, now: () => NOW }))?.owner, true); + assert.equal(calls, 2); + }); + + it('ignores an email header and still accepts a valid cookie beside a bad header', async () => { + const token = await signer.sign(ownerClaims(NOW)); + const deps = { fetch: jwks(signer), now: () => NOW }; + const spoof = new Request('https://funfun.zone/', { + headers: { 'Cf-Access-Authenticated-User-Email': 'owner@fixture.test' }, + }); + assert.deepEqual(await identify(spoof, TEST_ENV, deps), { status: 'anonymous' }); + + const both = new Request('https://funfun.zone/', { + headers: { + cookie: `theme=dark; CF_Authorization=${token}`, + 'Cf-Access-Jwt-Assertion': craft({ alg: 'none', kid: 'test-key' }, ownerClaims(NOW)), + }, + }); + const identity = await identify(both, TEST_ENV, deps); + assert.equal(identity.status, 'authenticated'); + if (identity.status === 'authenticated') assert.equal(identity.owner, true); + }); + + it('builds login and logout URLs without putting the owner email in them', () => { + const config = readAccessConfig(TEST_ENV); + assert.ok(config); + const login = accessLoginUrl(config.issuer, config.aud, 'https://funfun.zone/auth/login/', '/posts/'); + assert.equal( + login, + `https://fixture-team.cloudflareaccess.com/cdn-cgi/access/login/funfun.zone?kid=${'a'.repeat(64)}&redirect_url=%2Fposts%2F`, + ); + assert.doesNotMatch(login, /owner@fixture/); + const logout = accessLogoutUrl('https://funfun.zone/auth/logout/'); + assert.equal(logout, 'https://funfun.zone/cdn-cgi/access/logout?returnTo=https%3A%2F%2Ffunfun.zone%2F'); + const request = new Request('https://funfun.zone/auth/login/?next=https://evil.example/phish'); + assert.equal(safeNextPath(request), '/'); + const same = new Request('https://funfun.zone/auth/login/?next=/private/hello/'); + assert.equal(safeNextPath(same), '/private/hello/'); + }); +}); + +function jwks(signer: AccessSigner): typeof fetch { + return (async () => + new Response(JSON.stringify(signer.jwks()), { + status: 200, + headers: { 'content-type': 'application/json' }, + })) as typeof fetch; +} + +function craft(header: Record, claims: Record): string { + const encode = (value: unknown) => + btoa(JSON.stringify(value)).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); + return `${encode(header)}.${encode(claims)}.e30`; +} diff --git a/functions/lib/access.ts b/functions/lib/access.ts new file mode 100644 index 0000000..eee5842 --- /dev/null +++ b/functions/lib/access.ts @@ -0,0 +1,342 @@ +/** + * Verify a Cloudflare Access application token. + * The signature is checked against the team JWKS. Email headers, cookies' + * mere presence, and localStorage are not identity. + */ + +export interface GateEnv { + ACCESS_TEAM_DOMAIN?: string; + ACCESS_AUD?: string; + OWNER_EMAIL?: string; + PRIVATE_NOTES_ORIGIN?: string; + PRIVATE_NOTES_ALLOW_PREVIEW?: string; + ASSETS?: { fetch(input: Request | string): Promise }; +} + +export interface AccessConfig { + /** https://.cloudflareaccess.com */ + issuer: string; + jwksUrl: string; + aud: string; + ownerEmail: string; +} + +export type Identity = + | { status: 'anonymous' } + | { status: 'invalid' } + | { status: 'authenticated'; owner: boolean; token: string }; + +export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise; + +export interface AccessDeps { + fetch?: FetchLike; + now?: () => number; +} + +/** Access will not issue a longer application token than one month. */ +const MAX_SESSION_MS = 32 * 24 * 60 * 60 * 1000; +const CLOCK_SKEW_MS = 60_000; +const JWKS_TTL_MS = 60 * 60 * 1000; +const MAX_TOKEN_LENGTH = 12_000; +const MAX_JWKS_BYTES = 100_000; + +const BLOCKED_EMAIL_DOMAINS = new Set(['example.com', 'example.org', 'example.net', 'localhost', 'invalid']); +const BLOCKED_TEAM_LABELS = new Set([ + 'example', + 'your-team', + 'yourteam', + 'your_team', + 'changeme', + 'replace-me', + 'team', +]); + +interface JwtHeader { + alg?: string; + kid?: string; + typ?: string; + crit?: unknown; +} + +interface JwtClaims { + iss?: unknown; + aud?: unknown; + exp?: unknown; + nbf?: unknown; + email?: unknown; +} + +interface AccessJwk extends JsonWebKey { + kid?: string; + alg?: string; + use?: string; +} + +let jwksCache: { url: string; keys: Map; expires: number } | null = null; + +export function clearJwksCache(): void { + jwksCache = null; +} + +export function readAccessConfig(env: GateEnv): AccessConfig | null { + const aud = env.ACCESS_AUD?.trim().toLowerCase() ?? ''; + if (!/^[a-f0-9]{32,128}$/.test(aud)) return null; + const ownerEmail = normalizeEmail(env.OWNER_EMAIL ?? ''); + if (!isUsableOwnerEmail(ownerEmail)) return null; + const issuer = normalizeIssuer(env.ACCESS_TEAM_DOMAIN ?? ''); + if (!issuer) return null; + return { aud, ownerEmail, issuer, jwksUrl: `${issuer}/cdn-cgi/access/certs` }; +} + +export function normalizeIssuer(raw: string): string | null { + const trimmed = raw.trim().replace(/\/+$/, ''); + if (!trimmed) return null; + const withScheme = /^https:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`; + let url: URL; + try { + url = new URL(withScheme); + } catch { + return null; + } + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.port) { + return null; + } + if (url.pathname !== '/' && url.pathname !== '') return null; + const host = url.hostname.toLowerCase(); + const suffix = '.cloudflareaccess.com'; + if (!host.endsWith(suffix)) return null; + const label = host.slice(0, -suffix.length); + if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) return null; + if (BLOCKED_TEAM_LABELS.has(label)) return null; + return `https://${host}`; +} + +export function normalizeEmail(raw: string): string { + return raw.trim().normalize('NFKC').toLowerCase(); +} + +function isUsableOwnerEmail(email: string): boolean { + if (email.length < 6 || email.length > 320) return false; + if (email.includes('replace_with') || email.includes('changeme') || email.includes('your-email')) return false; + const at = email.indexOf('@'); + if (at <= 0 || at !== email.lastIndexOf('@')) return false; + const domain = email.slice(at + 1); + if (!domain.includes('.') || domain.startsWith('.') || domain.endsWith('.')) return false; + if (BLOCKED_EMAIL_DOMAINS.has(domain)) return false; + if (/[\s<>"'`]/.test(email)) return false; + return true; +} + +export async function identify(request: Request, env: GateEnv, deps: AccessDeps = {}): Promise { + const tokens = collectTokens(request); + const config = readAccessConfig(env); + if (!config) return tokens.length > 0 ? { status: 'invalid' } : { status: 'anonymous' }; + if (tokens.length === 0) return { status: 'anonymous' }; + + let nonOwner: string | null = null; + let sawInvalid = false; + for (const token of tokens) { + const verified = await verifyAccessJwt(token, config, deps); + if (!verified) { + sawInvalid = true; + continue; + } + if (verified.owner) return { status: 'authenticated', owner: true, token }; + if (verified.email) nonOwner = token; + else sawInvalid = true; + } + if (nonOwner) return { status: 'authenticated', owner: false, token: nonOwner }; + return sawInvalid ? { status: 'invalid' } : { status: 'anonymous' }; +} + +export function collectTokens(request: Request): string[] { + const found: string[] = []; + const header = request.headers.get('Cf-Access-Jwt-Assertion')?.trim(); + const cookie = readCookie(request, 'CF_Authorization'); + for (const token of [cookie, header]) { + if (!token || token.length > MAX_TOKEN_LENGTH || found.includes(token)) continue; + found.push(token); + } + return found; +} + +function readCookie(request: Request, name: string): string | null { + const raw = request.headers.get('cookie'); + if (!raw) return null; + for (const part of raw.split(';')) { + const eq = part.indexOf('='); + if (eq === -1) continue; + if (part.slice(0, eq).trim() !== name) continue; + const value = part.slice(eq + 1).trim(); + return value || null; + } + return null; +} + +interface VerifiedToken { + email: string | null; + owner: boolean; +} + +export async function verifyAccessJwt( + token: string, + config: AccessConfig, + deps: AccessDeps = {}, +): Promise { + try { + const parts = token.split('.'); + if (parts.length !== 3 || parts.some((part) => part.length === 0)) return null; + const header = decodeJson(parts[0]); + if (!header || header.alg !== 'RS256' || header.crit) return null; + if (header.typ && header.typ !== 'JWT') return null; + if (!header.kid) return null; + const key = await importVerificationKey(header.kid, config, deps); + if (!key) return null; + const data = new TextEncoder().encode(`${parts[0]}.${parts[1]}`); + const signature = base64UrlDecode(parts[2]); + const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, signature, data); + if (!ok) return null; + const claims = decodeJson(parts[1]); + if (!claims || claims.iss !== config.issuer) return null; + if (!audienceMatches(claims.aud, config.aud)) return null; + if (!lifetimeOk(claims, deps.now?.() ?? Date.now())) return null; + if (claims.email === undefined || claims.email === null) return { email: null, owner: false }; + if (typeof claims.email !== 'string') return null; + const email = normalizeEmail(claims.email); + if (!email.includes('@')) return null; + const owner = await emailsEqual(email, config.ownerEmail); + return { email, owner }; + } catch { + return null; + } +} + +function audienceMatches(aud: unknown, expected: string): boolean { + if (typeof aud === 'string') return aud === expected; + if (!Array.isArray(aud)) return false; + return aud.some((item) => item === expected); +} + +function lifetimeOk(claims: JwtClaims, now: number): boolean { + if (typeof claims.exp !== 'number' || !Number.isFinite(claims.exp)) return false; + if (claims.exp * 1000 + CLOCK_SKEW_MS < now) return false; + if (claims.exp * 1000 - now > MAX_SESSION_MS + CLOCK_SKEW_MS) return false; + if (claims.nbf !== undefined) { + if (typeof claims.nbf !== 'number' || !Number.isFinite(claims.nbf)) return false; + if (claims.nbf * 1000 - CLOCK_SKEW_MS > now) return false; + } + return true; +} + +async function importVerificationKey(kid: string, config: AccessConfig, deps: AccessDeps): Promise { + let keys = await loadKeys(config, deps, false); + if (!keys?.has(kid)) keys = await loadKeys(config, deps, true); + const jwk = keys?.get(kid); + if (!jwk || jwk.kty !== 'RSA') return null; + if (jwk.alg && jwk.alg !== 'RS256') return null; + if (jwk.use && jwk.use !== 'sig') return null; + if (jwk.d) return null; + const { kty, n, e } = jwk; + if (!n || !e) return null; + return crypto.subtle.importKey( + 'jwk', + { kty, n, e, alg: 'RS256', ext: true }, + { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, + false, + ['verify'], + ); +} + +async function loadKeys( + config: AccessConfig, + deps: AccessDeps, + force: boolean, +): Promise | null> { + const now = deps.now?.() ?? Date.now(); + if (!force && jwksCache && jwksCache.url === config.jwksUrl && jwksCache.expires > now) { + return jwksCache.keys; + } + if (!config.jwksUrl.startsWith(`${config.issuer}/cdn-cgi/access/certs`)) return null; + const fetchImpl = deps.fetch ?? globalThis.fetch; + const response = await fetchImpl(config.jwksUrl, { + redirect: 'manual', + headers: { accept: 'application/json' }, + signal: AbortSignal.timeout(5_000), + }); + if (response.status !== 200) return null; + const text = await response.text(); + if (text.length > MAX_JWKS_BYTES) return null; + const parsed = JSON.parse(text) as { keys?: AccessJwk[] }; + if (!parsed.keys?.length) return null; + const keys = new Map(); + for (const key of parsed.keys) { + if (key?.kid && key.kty === 'RSA' && !key.d) keys.set(key.kid, key); + } + if (keys.size === 0) return null; + jwksCache = { url: config.jwksUrl, keys, expires: now + JWKS_TTL_MS }; + return keys; +} + +async function emailsEqual(left: string, right: string): Promise { + const encoder = new TextEncoder(); + const [a, b] = await Promise.all([ + crypto.subtle.digest('SHA-256', encoder.encode(left)), + crypto.subtle.digest('SHA-256', encoder.encode(right)), + ]); + const x = new Uint8Array(a); + const y = new Uint8Array(b); + let diff = x.length ^ y.length; + const length = Math.max(x.length, y.length); + for (let i = 0; i < length; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0); + return diff === 0; +} + +function decodeJson(part: string): T | null { + try { + const value = JSON.parse(new TextDecoder().decode(base64UrlDecode(part))) as T; + if (!value || typeof value !== 'object') return null; + return value; + } catch { + return null; + } +} + +function base64UrlDecode(part: string): Uint8Array { + const padded = part.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (part.length % 4)) % 4); + const binary = atob(padded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +export function accessLoginUrl(issuer: string, aud: string, requestUrl: string, nextPath: string): string { + const host = new URL(requestUrl).host; + const url = new URL(`/cdn-cgi/access/login/${host}`, issuer); + url.searchParams.set('kid', aud); + url.searchParams.set('redirect_url', nextPath); + return url.href; +} + +export function accessLogoutUrl(requestUrl: string): string { + const origin = new URL(requestUrl).origin; + const url = new URL('/cdn-cgi/access/logout', origin); + url.searchParams.set('returnTo', `${origin}/`); + return url.href; +} + +/** Same-origin path only, so the login redirect cannot leave the site. */ +export function safeNextPath(request: Request): string { + const raw = new URL(request.url).searchParams.get('next') ?? '/'; + let target: URL; + try { + target = new URL(raw, request.url); + } catch { + return '/'; + } + if (target.origin !== new URL(request.url).origin) return '/'; + if (target.username || target.password) return '/'; + if (!target.pathname.startsWith('/') || target.pathname.startsWith('//') || target.pathname.includes('\\')) { + return '/'; + } + return `${target.pathname}${target.search}`; +} diff --git a/functions/lib/catalog.ts b/functions/lib/catalog.ts new file mode 100644 index 0000000..523a5fe --- /dev/null +++ b/functions/lib/catalog.ts @@ -0,0 +1,62 @@ +/** Shape shared by the private deployment and the public gate. Bodies stay out of the index. */ + +export interface PrivateNoteMeta { + slug: string; + title: string; + planted: string; +} + +export interface PrivateNote extends PrivateNoteMeta { + body: string; +} + +const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const PLANTED = /^\d{4}-\d{2}-\d{2}$/; +const MAX_NOTES = 500; +const MAX_TITLE = 200; +const MAX_BODY = 100_000; + +export function parseCatalog(input: unknown): PrivateNote[] { + if (!input || typeof input !== 'object') return []; + const notes = (input as { notes?: unknown }).notes; + if (!Array.isArray(notes)) return []; + const parsed: PrivateNote[] = []; + const seen = new Set(); + for (const item of notes) { + if (parsed.length >= MAX_NOTES) break; + const note = parseNote(item, true); + if (!note || seen.has(note.slug)) continue; + seen.add(note.slug); + parsed.push(note); + } + return parsed; +} + +export function parseNote(input: unknown, requireBody: boolean): PrivateNote | null { + if (!input || typeof input !== 'object') return null; + const record = input as Record; + if (typeof record.slug !== 'string' || !SLUG.test(record.slug)) return null; + if (typeof record.title !== 'string') return null; + const title = record.title.replace(/[\r\n]+/g, ' ').trim(); + if (!title || title.length > MAX_TITLE) return null; + if (typeof record.planted !== 'string' || !PLANTED.test(record.planted)) return null; + if (!requireBody) return { slug: record.slug, title, planted: record.planted, body: '' }; + if (typeof record.body !== 'string' || record.body.length > MAX_BODY) return null; + return { slug: record.slug, title, planted: record.planted, body: record.body }; +} + +export function parseIndex(input: unknown): PrivateNoteMeta[] { + if (!input || typeof input !== 'object') return []; + const notes = (input as { notes?: unknown }).notes; + if (!Array.isArray(notes)) return []; + const parsed: PrivateNoteMeta[] = []; + const seen = new Set(); + for (const item of notes) { + if (parsed.length >= MAX_NOTES) break; + const note = parseNote(item, false); + if (!note || seen.has(note.slug)) continue; + seen.add(note.slug); + parsed.push({ slug: note.slug, title: note.title, planted: note.planted }); + } + return parsed; +} diff --git a/functions/lib/chrome.built.test.ts b/functions/lib/chrome.built.test.ts new file mode 100644 index 0000000..d98c6c4 --- /dev/null +++ b/functions/lib/chrome.built.test.ts @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { readFileSync, existsSync } from 'node:fs'; +import { describe, it } from 'node:test'; +import { applyChrome } from './chrome.ts'; + +const built = 'dist/index.html'; + +describe('built header', () => { + it('keeps the private entry out of the static page and accepts an owner injection', () => { + if (!existsSync(built)) return; + const html = readFileSync(built, 'utf8'); + assert.equal(html.includes('href="/private/"'), false); + assert.equal(html.includes('Private Notes'), false); + assert.match(html, /data-auth="sign-in"/); + const owner = applyChrome(html, 'owner', '/'); + assert.equal((owner.match(/href="\/private\/"/g) ?? []).length, 2); + assert.match(owner, />Sign outSign out'; +export const MARKER_MOBILE = ''; +export const PRIVATE_HREF = '/private/'; + +export type ChromeMode = 'anonymous' | 'signed-in' | 'owner'; + +export function applyChrome(html: string, mode: ChromeMode, pathname: string): string { + if (mode === 'anonymous') return html; + let next = signOut(html); + if (mode === 'owner') { + const active = pathname === '/private' || pathname.startsWith('/private/'); + next = next.replace(MARKER_DESKTOP, ownerLink('desktop', active)); + next = next.replace(MARKER_MOBILE, ownerLink('mobile', active)); + } + return next; +} + +function signOut(html: string): string { + return html.replace(/]*\bdata-auth="sign-in"[^>]*>\s*Sign in\s*<\/a>/g, (anchor) => + anchor + .replace('href="/auth/login/"', 'href="/auth/logout/"') + .replace('data-auth="sign-in"', 'data-auth="sign-out"') + .replace(/>\s*Sign in\s*<\/a>/, '>Sign out'), + ); +} + +function ownerLink(kind: 'desktop' | 'mobile', active: boolean): string { + const desktop = active + ? 'font-sans text-sm font-medium text-primary-900 dark:text-primary-100' + : 'font-sans text-sm text-primary-600 transition-colors hover:text-primary-900 dark:text-primary-400 dark:hover:text-primary-100'; + const mobile = active + ? 'block rounded-lg px-3 py-2 text-sm font-medium text-primary-900 dark:text-primary-100' + : 'block rounded-lg px-3 py-2 text-sm font-medium text-primary-600 transition-colors hover:text-primary-900 dark:text-primary-400 dark:hover:text-primary-100'; + const current = active ? ' aria-current="page"' : ''; + return `Private Notes`; +} diff --git a/functions/lib/gate.test.ts b/functions/lib/gate.test.ts new file mode 100644 index 0000000..2cf8cfa --- /dev/null +++ b/functions/lib/gate.test.ts @@ -0,0 +1,247 @@ +import assert from 'node:assert/strict'; +import { before, beforeEach, describe, it } from 'node:test'; +import { clearJwksCache, type FetchLike, type GateEnv } from './access.ts'; +import { handleGate } from './gate.ts'; +import { FIXTURE_NOTE_BODY, makeAccessSigner, ownerClaims, TEST_ENV, type AccessSigner } from './jwt-fixture.ts'; + +const NOW = Date.parse('2026-11-22T00:00:00Z'); +const SHELL = `FunFun Zone | A blog + + + + +Sign in + +Sign in +

Home

+`; + +const NOTE = { + slug: 'fixture-note', + title: 'Fixture note', + planted: '2026-11-01', + body: `Hello ${FIXTURE_NOTE_BODY}\n\n`, +}; + +describe('private notes gate', () => { + beforeEach(() => clearJwksCache()); + + it('serves the public page unchanged to anonymous visitors', async () => { + const { response } = await send('/', {}); + assert.equal(response.status, 200); + assert.equal(response.headers.get('cache-control'), 'public, max-age=3600'); + assert.equal(await response.text(), SHELL); + assert.equal(response.headers.get('cdn-cache-control'), null); + }); + + it('injects the owner entry only for a verified owner and refuses to cache it', async () => { + const token = await currentSigner.sign(ownerClaims(NOW)); + const owner = await send('/', { token }); + const html = await owner.response.text(); + assert.match(html, /href="\/private\/"/); + assert.match(html, /Private Notes/); + assert.match(html, />Sign out hit.url.includes('private-notes')), false); + + const shared = new Map(); + const remember = async (path: string, credential?: string) => { + const result = await send(path, credential ? { token: credential } : {}); + const body = await result.response.text(); + const cacheControl = `${result.response.headers.get('cache-control')} ${result.response.headers.get('cdn-cache-control')}`; + if (!/no-store|private/.test(cacheControl)) shared.set(path, body); + return body; + }; + const ownerBody = await remember('/', token); + assert.match(ownerBody, /Private Notes/); + assert.notEqual(shared.get('/')?.includes('Private Notes'), true); + const anonBody = await remember('/'); + assert.equal(anonBody.includes('Private Notes'), false); + assert.equal(shared.get('/'), SHELL); + }); + + it('hides the entry from a non-owner, an expired token, a spoofed header, and a pages.dev host', async () => { + const other = await currentSigner.sign(ownerClaims(NOW, 'reader@fixture.test')); + const expired = await currentSigner.sign({ ...ownerClaims(NOW), exp: Math.floor(NOW / 1000) - 600 }); + for (const token of [other, expired]) { + const page = await send('/', { token }); + const html = await page.response.text(); + assert.equal(html.includes('href="/private/"'), false, 'public page leaked the entry'); + assert.equal(page.hits.some((hit) => hit.url.includes('private-notes')), false); + } + + const spoof = await send('/', { headers: { 'Cf-Access-Authenticated-User-Email': 'owner@fixture.test' } }); + assert.equal(await spoof.response.text(), SHELL); + assert.equal(spoof.response.headers.get('cache-control'), 'public, max-age=3600'); + + const preview = await send('/', { token: await currentSigner.sign(ownerClaims(NOW)), host: 'https://funfun-zone.pages.dev' }); + assert.equal((await preview.response.text()).includes('href="/private/"'), false); + }); + + it('does not fetch private notes unless the caller is the verified owner on an allowed host', async () => { + const token = await currentSigner.sign(ownerClaims(NOW)); + const cases = [ + send('/private/', {}), + send('/private/', { token: await currentSigner.sign(ownerClaims(NOW, 'reader@fixture.test')) }), + send('/private/', { token, env: { OWNER_EMAIL: undefined, ACCESS_AUD: undefined } }), + send('/private/', { token, host: 'https://funfun-zone.pages.dev' }), + send('/private/', { headers: { 'Cf-Access-Authenticated-User-Email': 'owner@fixture.test' } }), + ]; + for (const pending of cases) { + const result = await pending; + const html = await result.response.text(); + assert.equal(html.includes(FIXTURE_NOTE_BODY), false); + assert.equal(result.hits.some((hit) => hit.url.includes('private-notes')), false); + } + + const owner = await send('/private/fixture-note/', { token }); + const html = await owner.response.text(); + assert.equal(owner.response.status, 200); + assert.match(html, new RegExp(FIXTURE_NOTE_BODY)); + assert.match(html, /<script>/); + assert.doesNotMatch(html, /\n\n[ok](https://example.com/a)\n\n[bad](javascript:alert(1))\n\n![pic](javascript:alert(2))\n\n[note](my-note)', + ); + assert.match(html, /Hello <script>alert\(1\)<\/script>/); + assert.doesNotMatch(html, /