Skip to content
Open
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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions deploy/private-notes/README.md
Original file line number Diff line number Diff line change
@@ -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/<slug>.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).
53 changes: 53 additions & 0 deletions deploy/private-notes/build-catalog.mjs
Original file line number Diff line number Diff line change
@@ -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<string, string>} */
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`);
}
33 changes: 33 additions & 0 deletions deploy/private-notes/build-catalog.test.mjs
Original file line number Diff line number Diff line change
@@ -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<script>alert(1)</script>\n',
);
const catalog = buildCatalog(dir);
assert.deepEqual(catalog.notes, [
{
slug: 'fixture-note',
title: 'Fixture',
planted: '2026-11-01',
body: '<script>alert(1)</script>\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: [] });
});
});
3 changes: 3 additions & 0 deletions deploy/private-notes/catalog.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"notes": []
}
5 changes: 5 additions & 0 deletions deploy/private-notes/notes/README.md
Original file line number Diff line number Diff line change
@@ -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.
107 changes: 107 additions & 0 deletions deploy/private-notes/src/worker.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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' },
});
}
58 changes: 58 additions & 0 deletions deploy/private-notes/src/worker.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
return route(request, env, parseCatalog(catalog), deps);
}

export default {
fetch(request: Request, env: GateEnv): Promise<Response> {
return handlePrivateNotes(request, env, catalogJson);
},
};

async function route(request: Request, env: GateEnv, notes: readonly PrivateNote[], deps: AccessDeps): Promise<Response> {
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 });
}
8 changes: 8 additions & 0 deletions deploy/private-notes/wrangler.toml.example
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 2 additions & 0 deletions docs/cloudflare-pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading
Loading