diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f1d390..fd2bd3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,51 @@ +## 2026-11-15 14:22 + +| Check | Status | Details | +|-------|--------|---------| +| Lint | ✓ PASS | 0 errors | +| Build | ✓ PASS | 27 pages built, 5 pages indexed (Pagefind) | +| Unit Tests | ✓ PASS | 75 tests passed | +| E2E Tests | ✓ PASS | 96 tests passed | +| Lighthouse | ✓ PASS | 99.1% performance (avg) | + +### Lighthouse Performance (local build) + +| Page | Scores (3 runs) | +|------|-----------------| +| / (index) | 100%, 100%, 100% | +| /about | 89%, 99%, 99% | +| /posts | 100%, 100%, 100% | +| /archives (soft 404, not linked) | 100%, 100%, 100% | +| /404 | 100%, 100%, 100% | + +**Diagnostics:** None for the blog (one /about run at 89%, others 99%). Live site not measured (Turnstile gate). CMS checks: format clean, 173 unit, 2 integration, 2 e2e passed. `blog-cms` preview build log: "Found Functions directory at /functions. Uploading.", `uses_functions: true`. + +Changes: CMS proxy review fixes: also reject `%2E` and `%5C` in proxied paths, drop the `Link` header (GitHub page links use `/repositories//` and would 404), redirect Sveltia's "View on GitHub" links (`/gh/comdotlinux/blog/...`) to github.com; tests for query-string forwarding, `User-Agent` and API version on every upstream call, `update-branch`, `blog-other` and ref rules; README notes on Publish, the 24 h Access session and the live check order. + +## 2026-11-15 14:12 + +| Check | Status | Details | +|-------|--------|---------| +| Lint | ✓ PASS | 0 errors | +| Build | ✓ PASS | 27 pages built, 5 pages indexed (Pagefind) | +| Unit Tests | ✓ PASS | 75 tests passed | +| E2E Tests | ✓ PASS | 96 tests passed | +| Lighthouse | ✓ PASS | 99.6% performance (avg) | + +### Lighthouse Performance (local build) + +| Page | Scores (3 runs) | +|------|-----------------| +| / (index) | 97%, 100%, 100% | +| /about | 99%, 99%, 99% | +| /posts | 100%, 100%, 100% | +| /archives (soft 404, not linked) | 100%, 100%, 100% | +| /404 | 100%, 100%, 100% | + +**Diagnostics:** None for the blog. Live site not measured (Turnstile gate). CMS checks: format clean, 159 unit, 2 integration, 2 e2e passed; local `wrangler pages dev` compiles `cms/functions` (503 without settings, 401 without or with a forged Access JWT, 403 cross-site). + +Changes: CMS sign-in through Cloudflare Access only. New Pages Function `cms/functions/gh/[[path]].ts` verifies the Access JWT and proxies Sveltia's GitHub calls with a GitHub App installation token held server side (path, write and GraphQL mutation allow-lists, no DELETE or merges, commits only on `cms/` branches); static popup `cms/public/auth.html` completes Sveltia's handshake with a placeholder token; `config.yml` gets `base_url`, `auth_endpoint`, `api_root`, `auth_methods`. Needs the GitHub App and Production settings from `cms/README.md` before it works. + ## 2026-11-15 11:55 | Check | Status | Details | diff --git a/CLAUDE.md b/CLAUDE.md index 1acd51c..c45324d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -205,6 +205,10 @@ The production site is gated at the edge, as in the bio repo: no page is served - Trade-off the user accepted: search engines and link-preview bots cannot read post pages. - Local dev, `astro preview`, e2e and Lighthouse run without the gate (Functions only run on Cloudflare). Unit tests: `tests/functions/turnstile.test.ts`. +### CMS (`cms/`, Pages project `blog-cms`) + +Sveltia CMS at `cms.blog.kulkarni.cloud/admin/`, behind Cloudflare Access. Access is the only login: `cms/functions/gh/[[path]].ts` verifies the Access JWT and proxies Sveltia's GitHub calls with a GitHub App installation token held server side. Production settings `GITHUB_APP_ID`, `GITHUB_APP_INSTALLATION_ID`, `GITHUB_APP_PRIVATE_KEY` (secret), `OWNER_EMAIL` (secret) are typed by the owner; details in `cms/README.md` and `cms/AGENTS.md`. + ## Static Assets Images for blog posts are stored in `public/assets/` organized by date: diff --git a/cms/AGENTS.md b/cms/AGENTS.md index 8000d7e..bb08ccf 100644 --- a/cms/AGENTS.md +++ b/cms/AGENTS.md @@ -8,22 +8,26 @@ Owner-only post editor: Sveltia CMS as a static admin page, deployed by the Clou ## Key Files -| File | Description | -| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `public/admin/index.html` | Loads `@sveltia/cms` at an exact version from unpkg with `integrity` (sha384) and `crossorigin`; `noindex` | -| `public/admin/config.yml` | GitHub backend `comdotlinux/blog`, branch `main`, `publish_mode: editorial_workflow` (branch `cms/posts/` plus a PR per post); `output.omit_empty_optional_fields: true`; collection `posts` in `src/content/posts`, date-only `pubDatetime`/`modDatetime`, `draft` default false, raw Markdown body first | -| `package.json` | Scripts `serve`, `format:check`, `test:unit`, `test:integration`, `test:e2e`, `test:compat`; exact pins | -| `vitest.config.ts` | Unit tests in `test/unit/` | -| `playwright.config.ts` | Projects `integration` (HTTP only) and `e2e` (Chromium, 1 retry for the CDN); web server `python3 -m http.server` on `CMS_PORT` (default 8787) | -| `scripts/compat-check.sh` | Copies `test/fixtures/compat-post.md` and the golden new entry into `../src/content/posts/zz-cms-compat-*.md`, builds the blog, greps the HTML (table, `hello.ts` label, callout div, image, no `{%`), then moves the two files to `../.trash/` | -| `scripts/content-guard.sh` | Run by the `content-guard` CI job on post changes: no `{%` in posts, removed `file=` fence lines must be re-added, changed posts need `title`, `description`, `pubDatetime` and no empty-string values | -| `test/fixtures/` | Spike 1 fixture and the files Sveltia wrote in Spike 1 (`golden/`) | +| File | Description | +| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `public/admin/index.html` | Loads `@sveltia/cms` at an exact version from unpkg with `integrity` (sha384) and `crossorigin`; `noindex` | +| `public/admin/config.yml` | GitHub backend `comdotlinux/blog`, branch `main`, `base_url`/`auth_endpoint: auth` (sign-in popup `public/auth.html`), `api_root` `/gh/api/v3` (the proxy), `auth_methods: [oauth]` (hides the token field), `publish_mode: editorial_workflow` (branch `cms/posts/` plus a PR per post); `output.omit_empty_optional_fields: true`; collection `posts` in `src/content/posts`, date-only `pubDatetime`/`modDatetime`, `draft` default false, raw Markdown body first | +| `public/auth.html` | Static sign-in popup: answers Sveltia's `authorizing:github` handshake with the placeholder token `cf-access`, `postMessage` only to `location.origin`, `data-cfasync="false"`, `noindex` | +| `functions/gh/[[path]].ts` | Pages Function on `/gh/*`: verifies the Access JWT (RS256, `kid`, `aud`, `iss`, `exp`, `nbf`, `OWNER_EMAIL`), same-origin check, mints a GitHub App installation token, forwards an allow-list of paths, writes and GraphQL mutations to `api.github.com`; `/user` and repo `permissions` shims | +| `package.json` | Scripts `serve`, `format:check`, `test:unit`, `test:integration`, `test:e2e`, `test:compat`; exact pins | +| `vitest.config.ts` | Unit tests in `test/unit/` | +| `playwright.config.ts` | Projects `integration` (HTTP only) and `e2e` (Chromium, 1 retry for the CDN); web server `python3 -m http.server` on `CMS_PORT` (default 8787) | +| `scripts/compat-check.sh` | Copies `test/fixtures/compat-post.md` and the golden new entry into `../src/content/posts/zz-cms-compat-*.md`, builds the blog, greps the HTML (table, `hello.ts` label, callout div, image, no `{%`), then moves the two files to `../.trash/` | +| `scripts/content-guard.sh` | Run by the `content-guard` CI job on post changes: no `{%` in posts, removed `file=` fence lines must be re-added, changed posts need `title`, `description`, `pubDatetime` and no empty-string values | +| `test/fixtures/` | Spike 1 fixture and the files Sveltia wrote in Spike 1 (`golden/`) | ## For AI Agents - Keep `config.yml` field names a subset of the blog's `posts` schema keys (`src/content.config.ts`); `test/unit/config.test.ts` enforces it. - Never remove `omit_empty_optional_fields`: without it Sveltia writes `modDatetime: ''`, which fails the blog build. - Upgrading Sveltia means a new version and a new sha384 in `index.html` (see `README.md`), then all tests. -- Do not add a build step or runtime secrets. Pages runs with `SKIP_DEPENDENCY_INSTALL=1`. +- Do not add a build step. Pages runs with `SKIP_DEPENDENCY_INSTALL=1`, so `functions/` must not import npm packages (WebCrypto only). +- Runtime settings, Production only, typed by the owner (`README.md` "One-time setup"): secrets `GITHUB_APP_PRIVATE_KEY` (PKCS#8 PEM) and `OWNER_EMAIL`, text variables `GITHUB_APP_ID` and `GITHUB_APP_INSTALLATION_ID`. Never write their values anywhere; missing ones make the proxy answer 503. +- The `/gh/` proxy is the only path from the browser to GitHub. Never put a GitHub token in the browser, never log tokens, keys or JWTs (`console.error` takes fixed text and a status code only), keep `Cache-Control: no-store` on every response, errors included. The proxy sends no CORS headers: it serves the same origin only. New Sveltia calls go into the allow-lists in the proxy with a test. - Branch prefix is Sveltia's `cms/posts/`. Post PRs are merged or closed on GitHub, never with Sveltia's Publish or Discard (both delete branches). - `wrangler` installed anywhere under a checkout that has a stale `.wrangler/deploy/config.json` refuses `pages dev`; the tests here use `python3 -m http.server` instead. diff --git a/cms/README.md b/cms/README.md index 89aa6ca..d7679c7 100644 --- a/cms/README.md +++ b/cms/README.md @@ -1,13 +1,13 @@ # Blog CMS -An owner-only web editor for the blog's posts, built on [Sveltia CMS](https://sveltiacms.app/). It is a static admin page (`public/admin/`) served by the Cloudflare Pages project `blog-cms` at `https://cms.blog.kulkarni.cloud/admin/`, behind Cloudflare Access. There is no build step and no server code; Sveltia talks to GitHub from the browser with a fine-grained personal access token. +An owner-only web editor for the blog's posts, built on [Sveltia CMS](https://sveltiacms.app/). It is a static admin page (`public/admin/`) served by the Cloudflare Pages project `blog-cms` at `https://cms.blog.kulkarni.cloud/admin/`, behind Cloudflare Access. There is no build step. Cloudflare Access is the only login: one Pages Function, `functions/gh/[[path]].ts`, proxies Sveltia's GitHub calls with a GitHub App token that never leaves the server (see [How sign-in works](#how-sign-in-works)). ## Writing a post -1. Open `https://cms.blog.kulkarni.cloud/admin/`, pass Cloudflare Access, then "Sign In Using Access Token" with your PAT (Contents read and write, Metadata read, this repository only). -2. Create or edit a post under Posts and save. Sveltia commits it to its own branch `cms/posts/` and opens a pull request against `main`. Nothing reaches `main` until that pull request is merged. +1. Open `https://cms.blog.kulkarni.cloud/admin/`, pass Cloudflare Access, then click "Sign In with GitHub". A small window opens and closes by itself; there is no GitHub login and no token to paste. Allow popups for the host if the browser blocks it. +2. Create or edit a post under Posts and save. Sveltia commits it to its own branch `cms/posts/` and opens a pull request against `main`; commits and pull requests show the App bot (`[bot]`) as author. Nothing reaches `main` until that pull request is merged. 3. Check the blog's Cloudflare Pages preview for the branch (alias `cms-posts-.blog-7qk.pages.dev`) and the CI checks on the pull request. -4. **Merge or close the pull request on GitHub.** Never use Sveltia's **Publish** or **Discard**: Publish merges and then deletes the branch, Discard closes the pull request and deletes the unmerged branch. Log every merged or closed branch in `.trash/MOVED.md` (name, PR number, head SHA) as restorable from its PR. +4. **Merge or close the pull request on GitHub.** Never use Sveltia's **Publish** or **Discard** (the proxy refuses both with 403): Publish merges and then deletes the branch, Discard closes the pull request and deletes the unmerged branch. Log every merged or closed branch in `.trash/MOVED.md` (name, PR number, head SHA) as restorable from its PR. Field notes: @@ -17,6 +17,64 @@ Field notes: - Images: upload by hand to `public/assets/YYYYMMDD/` and link `/assets/YYYYMMDD/`. - The body editor opens in raw Markdown. Keep it there for tables, `file="..."` code labels and `> [!NOTE]` callouts. +## How sign-in works + +- Cloudflare Access (one-time PIN for the owner's email) gates the whole host, including `*.pages.dev`. +- "Sign In with GitHub" opens `public/auth.html` (config `base_url` + `auth_endpoint: auth`). It answers Sveltia's popup handshake with the placeholder token `cf-access`, so browser storage never holds a GitHub credential. +- Sveltia sends every GitHub call to `/gh/api/v3/*` and `/gh/api/graphql` (config `api_root`). `functions/gh/[[path]].ts`: + - accepts only same-origin requests (`Sec-Fetch-Site`, else `Origin`); + - verifies the Access JWT (`Cf-Access-Jwt-Assertion` header, else `CF_Authorization` cookie): RS256 only, key by `kid` from the team certs (5 min cache, refetch on an unknown `kid`), `aud`, `iss`, `exp`, `nbf` and `email` equal to `OWNER_EMAIL`; + - forwards only `/user`, `/repos/comdotlinux/blog/**` and `/graphql` to `api.github.com` with a GitHub App installation token (minted per hour, held in memory); it never forwards cookies, `Cf-*` headers or the incoming `Authorization`, and answers with `Cache-Control: no-store`; + - allows only the writes Sveltia's editorial workflow makes: no `DELETE`, no PR merge, ref updates and GraphQL commits only on `cms/` branches, GraphQL mutations limited to `createCommitOnBranch`, `createRef`, `convertPullRequestToDraft`, `markPullRequestReadyForReview` and `disablePullRequestAutoMerge`; + - serves `GET /user` from the public `comdotlinux` profile and adds `permissions.push` to the repository response, because GitHub answers installation tokens without either. +- Missing or invalid settings return 503 "CMS GitHub App not configured"; nothing reaches GitHub. +- Sveltia's "View on GitHub" links point at `/gh/comdotlinux/blog/...`; the function redirects exactly that prefix to `github.com` (no token involved). +- Sveltia's **Publish** tries auto-merge (`enablePullRequestAutoMerge`) and then a REST merge; the proxy refuses both with 403, so Publish shows an error and nothing is merged. Merge on GitHub instead. +- The Access session lasts 24 hours. When it ends, calls start failing with 401: reload `/admin/` to pass Access again. + +## One-time setup (owner) + +Until these steps are done the editor shows "Signing in" errors; the proxy fails closed. + +1. **Create the GitHub App.** github.com, avatar, Settings, Developer settings, GitHub Apps, New GitHub App. + - Name: for example `comdotlinux-blog-cms`. Homepage URL: `https://cms.blog.kulkarni.cloud/admin/`. + - Callback URL: empty. Uncheck "Expire user authorization tokens" and "Request user authorization (OAuth) during installation". + - Webhook: uncheck "Active". + - Repository permissions: Contents "Read and write", Pull requests "Read and write", Metadata "Read-only" (automatic). Nothing else. + - "Where can this GitHub App be installed?": "Only on this account". Create. +2. **Note the App ID** at the top of the app page (or the Client ID; both work). +3. **Generate a private key**: "Private keys", "Generate a private key". The browser downloads `..private-key.pem` (PKCS#1). +4. **Install the App**: "Install App", `comdotlinux`, "Only select repositories", `blog`, Install. The page URL ends in `/settings/installations/`: that number is the installation ID. +5. **Convert the key to PKCS#8** (WebCrypto cannot read PKCS#1), locally: + + ```sh + openssl pkcs8 -topk8 -nocrypt -in ~/Downloads/.*.private-key.pem -out ~/blog-cms-app.pk8.pem + ``` + + The result starts with `-----BEGIN PRIVATE KEY-----`. A key that starts with `-----BEGIN RSA PRIVATE KEY-----` is refused (503). + +6. **Add the variables** in the Cloudflare dashboard: Workers & Pages, `blog-cms`, Settings, Variables and Secrets, **Production** only: + + | Name | Type | Value | + | ---------------------------- | ---------- | ----------------------------------------- | + | `GITHUB_APP_ID` | Text | App ID (or Client ID) from step 2 | + | `GITHUB_APP_INSTALLATION_ID` | Text | Installation ID from step 4 | + | `GITHUB_APP_PRIVATE_KEY` | **Secret** | Full contents of `~/blog-cms-app.pk8.pem` | + | `OWNER_EMAIL` | **Secret** | The email address in the Access policy | + + Do not add them to Preview: the config points at the production host, so previews never need them, and every pushed branch would otherwise run with the key. + +7. **Redeploy** production (variables apply to new deployments): Deployments, latest production deployment, "Retry deployment", or merge the next change. +8. **Check** (keep the `.pem` files until this passes; a failed check may need the key again): + - Open `/admin/`, "Sign In with GitHub": the post list loads. + - Save a test post: branch `cms/posts/` and a pull request by the App bot appear. + - Open the Sveltia workflow view for that post (it lists the pull request and its checks). If it shows an error about checks or statuses, add the repository permissions "Checks: Read-only" and "Commit statuses: Read-only" to the App and accept the new permissions on the installation; nothing in the proxy needs to change. + - Close the test pull request on GitHub. + - In DevTools, Application, Local Storage holds `cf-access` and no `ghs_` value. +9. **Move both `.pem` files** into encrypted storage of your choice. + +If the key may be exposed: in the App settings revoke the key (and suspend the installation if needed), generate a new one and replace `GITHUB_APP_PRIVATE_KEY`. Rotate the key yearly. + ## Local development Everything runs from this directory with the versions in the repository's `mise.toml`. @@ -24,9 +82,9 @@ Everything runs from this directory with the versions in the repository's `mise. ```sh bun install --frozen-lockfile bun run format:check -bun run test:unit # config.yml against the blog schema, golden outputs, admin page pins +bun run test:unit # config.yml against the blog schema, golden outputs, admin page pins, auth page, /gh/ proxy bun run test:integration # serves public/ with python3 http.server, checks /admin/ and /admin/config.yml -bun run test:e2e # loads the admin page in Chromium; needs network for the Sveltia CDN +bun run test:e2e # loads the admin page in Chromium and runs the sign-in handshake against a stubbed /gh/; needs network for the Sveltia CDN bun run test:compat # builds the blog with test/fixtures and greps the rendered HTML ``` @@ -42,4 +100,4 @@ To try the editor against your working copy, serve `public/` (`bun run serve`), curl -sL https://unpkg.com/@sveltia/cms@/dist/sveltia-cms.js | openssl dgst -sha384 -binary | base64 ``` -Then run all tests above. +Then run all tests above. `test/e2e/auth.spec.ts` must pass: Sveltia upgrades can change the popup handshake, the `/user` call or how `api_root` maps to `/api/v3` and `/api/graphql`. diff --git a/cms/functions/gh/[[path]].ts b/cms/functions/gh/[[path]].ts new file mode 100644 index 0000000..2e4e0ff --- /dev/null +++ b/cms/functions/gh/[[path]].ts @@ -0,0 +1,457 @@ +/** + * Same-origin GitHub API proxy for Sveltia CMS (config.yml `api_root`). + * Every request needs a valid Cloudflare Access JWT for the owner. The proxy mints a GitHub App + * installation token, keeps it in memory and forwards only the calls Sveltia needs, so no GitHub + * credential reaches the browser. Never log tokens, keys or JWTs. + */ + +export interface Env { + GITHUB_APP_ID?: string; + GITHUB_APP_INSTALLATION_ID?: string; + GITHUB_APP_PRIVATE_KEY?: string; + OWNER_EMAIL?: string; +} + +const ACCESS_TEAM = "https://kulkarni.cloudflareaccess.com"; +const ACCESS_AUD = + "a9ed3790181fa358b0b922d6aa046c04abbb5f2df5134f0dfbd8c8e30893874e"; +const GITHUB = "https://api.github.com"; +const OWNER = "comdotlinux"; +const REPO = `/repos/${OWNER}/blog`; +const REST_PREFIX = "/gh/api/v3"; +const GRAPHQL_PATH = "/gh/api/graphql"; +const CERTS_TTL = 300; +const CERTS_MIN_REFETCH = 30; +const CLOCK_SKEW = 60; +const RSA = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }; +const GITHUB_HEADERS = { + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "blog-cms", +}; + +// Write calls Sveltia makes in the editorial workflow. Anything else that is not GET/HEAD gets 403, +// so DELETE, PR merges and ref updates outside cms/ branches never reach GitHub. +const WRITES: [string, RegExp][] = [ + ["POST", /^\/repos\/comdotlinux\/blog\/pulls$/], + ["PATCH", /^\/repos\/comdotlinux\/blog\/pulls\/\d+$/], + ["PATCH", /^\/repos\/comdotlinux\/blog\/issues\/\d+$/], + ["POST", /^\/repos\/comdotlinux\/blog\/issues\/\d+\/labels$/], + ["POST", /^\/repos\/comdotlinux\/blog\/pulls\/\d+\/reviews$/], + ["PUT", /^\/repos\/comdotlinux\/blog\/pulls\/\d+\/reviews\/\d+\/dismissals$/], + // Sveltia force-resets a stale workflow branch that has no open PR. + ["PATCH", /^\/repos\/comdotlinux\/blog\/git\/refs\/heads\/cms\/.+$/], +]; + +const MUTATIONS = new Set([ + "createCommitOnBranch", + "createRef", + "convertPullRequestToDraft", + "markPullRequestReadyForReview", + "disablePullRequestAutoMerge", +]); + +const encoder = new TextEncoder(); +const fromB64 = (s: string) => + Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => + c.charCodeAt(0) + ); +const toB64url = (bytes: ArrayBuffer | Uint8Array) => + btoa(String.fromCharCode(...new Uint8Array(bytes))) + .replace(/=+$/, "") + .replace(/\+/g, "-") + .replace(/\//g, "_"); +const decodeJson = (part: string): unknown => + JSON.parse(new TextDecoder().decode(fromB64(part))); +const isObject = (v: unknown): v is Record => + typeof v === "object" && v !== null && !Array.isArray(v); + +const json = (status: number, message: string) => + new Response(JSON.stringify({ message }), { + status, + headers: { + "Content-Type": "application/json", + "Cache-Control": "no-store", + }, + }); + +type Jwk = JsonWebKey & { kid?: string }; +let certs: { keys: Jwk[]; fetchedAt: number } | undefined; + +async function accessKey(kid: string, now: number): Promise { + const find = () => certs?.keys.find(k => k.kid === kid); + if ( + !certs || + now - certs.fetchedAt >= CERTS_TTL || + (!find() && now - certs.fetchedAt >= CERTS_MIN_REFETCH) + ) { + const res = await fetch(`${ACCESS_TEAM}/cdn-cgi/access/certs`); + if (!res.ok) throw new Error("certs unavailable"); + const body = (await res.json()) as { keys?: Jwk[] }; + certs = { keys: body.keys ?? [], fetchedAt: now }; + } + return find(); +} + +function accessToken(request: Request): string | undefined { + const header = request.headers.get("Cf-Access-Jwt-Assertion"); + if (header) return header; + for (const part of (request.headers.get("Cookie") ?? "").split(";")) { + const [name, ...value] = part.trim().split("="); + if (name === "CF_Authorization") return value.join("="); + } +} + +export async function verifyAccessJwt( + request: Request, + ownerEmail: string, + now: number +): Promise { + const token = accessToken(request); + if (!token) return false; + try { + const parts = token.split("."); + if (parts.length !== 3) return false; + const [h, p, s] = parts; + const header = decodeJson(h); + if ( + !isObject(header) || + header.alg !== "RS256" || + typeof header.kid !== "string" + ) + return false; + const jwk = await accessKey(header.kid, now); + if (!jwk || jwk.kty !== "RSA") return false; + const key = await crypto.subtle.importKey( + "jwk", + { kty: "RSA", n: jwk.n, e: jwk.e }, + RSA, + false, + ["verify"] + ); + if ( + !(await crypto.subtle.verify( + RSA.name, + key, + fromB64(s), + encoder.encode(`${h}.${p}`) + )) + ) + return false; + const c = decodeJson(p); + if (!isObject(c)) return false; + const aud = Array.isArray(c.aud) ? c.aud : [c.aud]; + return ( + aud.includes(ACCESS_AUD) && + c.iss === ACCESS_TEAM && + typeof c.exp === "number" && + c.exp > now && + typeof c.nbf === "number" && + c.nbf <= now + CLOCK_SKEW && + typeof c.email === "string" && + c.email.toLowerCase() === ownerEmail.trim().toLowerCase() + ); + } catch { + return false; + } +} + +export async function appJwt( + appId: string, + privateKeyPem: string, + now: number +): Promise { + const part = (o: object) => toB64url(encoder.encode(JSON.stringify(o))); + // GitHub takes the numeric App ID as a number, or the Client ID as a string. + const iss = /^\d+$/.test(appId) ? Number(appId) : appId; + const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part({ iat: now - 60, exp: now + 540, iss })}`; + const der = fromB64(privateKeyPem.replace(/-----[^-]+-----|\s/g, "")); + const key = await crypto.subtle.importKey("pkcs8", der, RSA, false, ["sign"]); + const sig = await crypto.subtle.sign(RSA.name, key, encoder.encode(unsigned)); + return `${unsigned}.${toB64url(sig)}`; +} + +let installation: { token: string; expiresAt: number } | undefined; + +async function installationToken(env: Required, now: number) { + if (installation && installation.expiresAt - now > 300) + return installation.token; + const res = await fetch( + `${GITHUB}/app/installations/${env.GITHUB_APP_INSTALLATION_ID}/access_tokens`, + { + method: "POST", + headers: { + ...GITHUB_HEADERS, + Accept: "application/vnd.github+json", + Authorization: `Bearer ${await appJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY, now)}`, + }, + body: JSON.stringify({ + repositories: ["blog"], + permissions: { + contents: "write", + pull_requests: "write", + metadata: "read", + }, + }), + } + ); + if (!res.ok) { + console.error("cms proxy: installation token request failed", res.status); + return undefined; + } + const body = (await res.json()) as { token: string; expires_at: string }; + installation = { + token: body.token, + expiresAt: Math.floor(Date.parse(body.expires_at) / 1000), + }; + return body.token; +} + +/** Validated GitHub path (still percent-encoded, as sent upstream) and its decoded form. */ +export function githubPath( + pathname: string +): { raw: string; path: string } | null { + if (pathname === GRAPHQL_PATH) return { raw: "/graphql", path: "/graphql" }; + if (!pathname.startsWith(`${REST_PREFIX}/`)) return null; + const raw = pathname.slice(REST_PREFIX.length); + if (/%(2f|5c|2e)/i.test(raw)) return null; + let path: string; + try { + path = decodeURIComponent(raw); + } catch { + return null; + } + // A `%` left after one decode means double encoding; GitHub could decode it again. + if (/[%\\\x00-\x1f\x7f]/.test(path)) return null; + if ( + path + .split("/") + .slice(1) + .some(s => s === "" || s === "." || s === "..") + ) + return null; + if (path === "/user" || path === REPO || path.startsWith(`${REPO}/`)) + return { raw, path }; + return null; +} + +export function writeAllowed(method: string, path: string): boolean { + return WRITES.some(([m, re]) => m === method && re.test(path)); +} + +function tokenize(query: string): string[] | null { + const re = + /\s+|,|#[^\n\r]*|("""[\s\S]*?(? { + const open = t[i]; + const close = open === "{" ? "}" : ")"; + for (let depth = 0; i < t.length; i++) { + if (t[i] === open) depth++; + else if (t[i] === close && --depth === 0) { + i++; + return true; + } + } + return false; + }; + const isName = (s: string | undefined) => /^[_A-Za-z]/.test(s ?? ""); + const fields: { name: string; args: string }[] = []; + while (i < t.length) { + const kind = t[i]; + if (kind === "{") { + if (!skip()) return null; + continue; + } + if (kind !== "query" && kind !== "mutation" && kind !== "fragment") + return null; + for (i++; i < t.length && t[i] !== "{";) + if (t[i] === "(") { + if (!skip()) return null; + } else i++; + if (i >= t.length) return null; + if (kind !== "mutation") { + if (!skip()) return null; + continue; + } + for (i++; t[i] !== "}";) { + // Fragment spreads, inline fragments and directives at the root are refused. + let name = t[i]; + if (!isName(name)) return null; + i++; + if (t[i] === ":") { + name = t[i + 1]; + i += 2; + if (!isName(name)) return null; + } + let args = ""; + if (t[i] === "(") { + const start = i; + if (!skip()) return null; + args = t.slice(start, i).join(""); + } + if (t[i] === "{" && !skip()) return null; + fields.push({ name, args }); + } + i++; + } + return fields; +} + +const isCmsBranch = (v: unknown, prefix = "") => + typeof v === "string" && v.startsWith(`${prefix}cms/`); + +/** Only Sveltia's own mutations, and commits or new refs only on cms/ branches (never main). */ +export function graphqlAllowed(body: unknown): boolean { + if (!isObject(body) || typeof body.query !== "string") return false; + const fields = mutationFields(body.query); + if (!fields) return false; + const input = isObject(body.variables) ? body.variables.input : undefined; + return fields.every(({ name, args }) => { + if (!MUTATIONS.has(name) || args !== "(input:$input)") return false; + if (!isObject(input)) return false; + if (name === "createCommitOnBranch") + return isObject(input.branch) && isCmsBranch(input.branch.branchName); + if (name === "createRef") return isCmsBranch(input.name, "refs/heads/"); + return true; + }); +} + +function configured(env: Env): env is Required { + return ( + /^[A-Za-z0-9.]+$/.test(env.GITHUB_APP_ID ?? "") && + /^\d+$/.test(env.GITHUB_APP_INSTALLATION_ID ?? "") && + /-----BEGIN PRIVATE KEY-----/.test(env.GITHUB_APP_PRIVATE_KEY ?? "") && + /@/.test(env.OWNER_EMAIL ?? "") + ); +} + +function sameOrigin(request: Request, origin: string): boolean { + const site = request.headers.get("Sec-Fetch-Site"); + if (site !== null) return site === "same-origin"; + return request.headers.get("Origin") === origin; +} + +export async function onRequest({ + request, + env, +}: { + request: Request; + env: Env; +}): Promise { + const url = new URL(request.url); + // Sveltia's "View on GitHub" links derive from api_root: /gh///... Plain redirect, no token. + if ( + request.method === "GET" && + (url.pathname === `/gh/${OWNER}/blog` || + url.pathname.startsWith(`/gh/${OWNER}/blog/`)) + ) + return new Response(null, { + status: 302, + headers: { + Location: `https://github.com${url.pathname.slice(3)}${url.search}`, + "Cache-Control": "no-store", + }, + }); + if (!configured(env)) { + console.error("cms proxy: GitHub App settings missing or invalid"); + return json(503, "CMS GitHub App not configured"); + } + if (!sameOrigin(request, url.origin)) return json(403, "Forbidden"); + const now = Math.floor(Date.now() / 1000); + if (!(await verifyAccessJwt(request, env.OWNER_EMAIL, now))) + return json(401, "Access required"); + + const target = githubPath(url.pathname); + if (!target) return json(404, "Not Found"); + const method = request.method; + const read = method === "GET" || method === "HEAD"; + let body: string | ArrayBuffer | undefined; + if (target.path === "/graphql") { + if (method !== "POST") return json(405, "Method Not Allowed"); + let parsed: unknown; + try { + parsed = await request.json(); + } catch { + return json(400, "Bad Request"); + } + if (!graphqlAllowed(parsed)) return json(403, "Forbidden"); + // Forward the parsed form, so GitHub sees exactly the query that was checked. + body = JSON.stringify(parsed); + } else if (!read) { + if (target.path === "/user" || !writeAllowed(method, target.path)) + return json(403, "Forbidden"); + body = await request.arrayBuffer(); + } else if (target.path === "/user" && method !== "GET") { + return json(405, "Method Not Allowed"); + } + + const token = await installationToken(env, now).catch(() => { + console.error("cms proxy: installation token could not be created"); + return undefined; + }); + if (!token) return json(502, "GitHub token unavailable"); + + // Installation tokens get 403 on /user, and GitHub omits `permissions` for them; Sveltia needs both. + const upstreamRaw = target.path === "/user" ? `/users/${OWNER}` : target.raw; + const headers: Record = { + ...GITHUB_HEADERS, + Authorization: `Bearer ${token}`, + Accept: request.headers.get("Accept") ?? "application/vnd.github+json", + }; + for (const name of ["Content-Type", "If-None-Match"]) { + const value = request.headers.get(name); + if (value) headers[name] = value; + } + // String concatenation onto the fixed origin; githubPath() already refused `//`, dots and encoded slashes. + const upstreamUrl = `${GITHUB}${upstreamRaw}${url.search}`; + if (new URL(upstreamUrl).origin !== GITHUB) return json(404, "Not Found"); + + let res: Response; + try { + res = await fetch(upstreamUrl, { method, headers, body }); + } catch { + console.error("cms proxy: GitHub request failed"); + return json(502, "GitHub unavailable"); + } + + const out = new Headers({ "Cache-Control": "no-store" }); + for (const name of [ + "Content-Type", + "ETag", + "Retry-After", + "X-RateLimit-Remaining", + ]) { + const value = res.headers.get(name); + if (value) out.set(name, value); + } + + if (res.status === 200 && method === "GET" && target.path === REPO) { + const repo = (await res.json()) as Record; + repo.permissions = { + admin: false, + maintain: false, + push: true, + triage: true, + pull: true, + }; + out.delete("ETag"); + return new Response(JSON.stringify(repo), { status: 200, headers: out }); + } + return new Response(res.body, { status: res.status, headers: out }); +} diff --git a/cms/playwright.config.ts b/cms/playwright.config.ts index 783d6c4..130e0fa 100644 --- a/cms/playwright.config.ts +++ b/cms/playwright.config.ts @@ -11,7 +11,7 @@ export default defineConfig({ { name: "integration", testMatch: "integration.spec.ts" }, { name: "e2e", - testMatch: "smoke.spec.ts", + testMatch: ["smoke.spec.ts", "auth.spec.ts"], // The admin shell loads Sveltia from the unpkg CDN; one retry absorbs a CDN blip. retries: 1, use: { ...devices["Desktop Chrome"] }, diff --git a/cms/public/admin/config.yml b/cms/public/admin/config.yml index 5b1f209..8bca596 100644 --- a/cms/public/admin/config.yml +++ b/cms/public/admin/config.yml @@ -3,6 +3,13 @@ backend: name: github repo: comdotlinux/blog branch: main + # Cloudflare Access is the only login. auth.html completes Sveltia's sign-in with a placeholder + # token; every GitHub call goes through the /gh/ proxy, which verifies Access and holds the + # GitHub App credential (functions/gh/[[path]].ts). + base_url: https://cms.blog.kulkarni.cloud + auth_endpoint: auth + api_root: https://cms.blog.kulkarni.cloud/gh/api/v3 + auth_methods: [oauth] # Each new post gets its own branch cms/posts/ and a pull request. publish_mode: editorial_workflow output: diff --git a/cms/public/auth.html b/cms/public/auth.html new file mode 100644 index 0000000..86399ef --- /dev/null +++ b/cms/public/auth.html @@ -0,0 +1,33 @@ + + + + + + + Blog CMS sign-in + + +

You can close this window.

+ + + + diff --git a/cms/test/e2e/auth.spec.ts b/cms/test/e2e/auth.spec.ts new file mode 100644 index 0000000..8ee9501 --- /dev/null +++ b/cms/test/e2e/auth.spec.ts @@ -0,0 +1,69 @@ +import { expect, test } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +const publicDir = join(import.meta.dirname, "../../public"); +const PRODUCTION = "https://cms.blog.kulkarni.cloud"; + +// Needs network: Sveltia itself comes from the unpkg CDN (pinned version, SRI). +test("sign-in uses auth.html and sends every GitHub call to the /gh/ proxy", async ({ + page, + context, + baseURL, +}) => { + const proxied: { url: string; authorization?: string }[] = []; + const direct: string[] = []; + + // Point the backend at this server; Pages serves /auth from auth.html, python http.server does not. + await context.route(/\/admin\/config\.yml(\?|$)/, route => + route.fulfill({ + contentType: "application/yaml", + body: readFileSync( + join(publicDir, "admin/config.yml"), + "utf8" + ).replaceAll(PRODUCTION, baseURL ?? ""), + }) + ); + await context.route(/\/auth(\?|$)/, route => + route.fulfill({ + contentType: "text/html", + body: readFileSync(join(publicDir, "auth.html"), "utf8"), + }) + ); + await context.route("**/gh/**", route => { + const request = route.request(); + proxied.push({ + url: new URL(request.url()).pathname, + authorization: request.headers().authorization, + }); + if (request.url().endsWith("/gh/api/v3/user")) { + return route.fulfill({ + contentType: "application/json", + body: JSON.stringify({ id: 1, login: "comdotlinux", name: "Owner" }), + }); + } + return route.fulfill({ status: 404, body: '{"message":"Not Found"}' }); + }); + await context.route(/^https:\/\/(api\.github\.com|github\.com)\//, route => { + direct.push(route.request().url()); + return route.abort(); + }); + + await page.goto("/admin/"); + const signIn = page.getByRole("button", { name: /Sign In with \W*GitHub/ }); + await expect(signIn).toBeVisible({ timeout: 30_000 }); + await expect( + page.getByRole("button", { name: /Sign In Using Access Token/ }) + ).toHaveCount(0); + + await signIn.click(); + await expect + .poll(() => proxied.find(r => r.url === "/gh/api/v3/user"), { + timeout: 15_000, + }) + .toBeDefined(); + expect(proxied.find(r => r.url === "/gh/api/v3/user")?.authorization).toBe( + "token cf-access" + ); + expect(direct).toEqual([]); +}); diff --git a/cms/test/unit/access-jwt.test.ts b/cms/test/unit/access-jwt.test.ts new file mode 100644 index 0000000..64a4d63 --- /dev/null +++ b/cms/test/unit/access-jwt.test.ts @@ -0,0 +1,193 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + AUD, + OWNER_EMAIL, + ORIGIN, + b64url, + fakeFetch, + now, + publicJwk, + rsaKeyPair, + sign, + validClaims, +} from "./proxy-helpers"; + +type Proxy = typeof import("../../functions/gh/[[path]]"); +let proxy: Proxy; +let keys: CryptoKeyPair; +let jwk: object; + +beforeEach(async () => { + vi.resetModules(); + proxy = await import("../../functions/gh/[[path]]"); + keys = await rsaKeyPair(); + jwk = await publicJwk(keys.publicKey, "kid-1"); +}); +afterEach(() => vi.unstubAllGlobals()); + +const header = { alg: "RS256", kid: "kid-1", typ: "JWT" }; +const withHeader = (token: string) => + new Request(`${ORIGIN}/gh/api/v3/user`, { + headers: { "Cf-Access-Jwt-Assertion": token }, + }); +const verify = (request: Request, email = OWNER_EMAIL) => + proxy.verifyAccessJwt(request, email, now()); + +describe("verifyAccessJwt", () => { + it("accepts a valid token from the Cf-Access-Jwt-Assertion header", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, header, validClaims()); + expect(await verify(withHeader(token))).toBe(true); + }); + + it("accepts a valid token from the CF_Authorization cookie", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, header, validClaims()); + const request = new Request(`${ORIGIN}/gh/api/v3/user`, { + headers: { Cookie: `other=1; CF_Authorization=${token}` }, + }); + expect(await verify(request)).toBe(true); + }); + + it("accepts aud as a plain string", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign( + keys.privateKey, + header, + validClaims({ aud: AUD }) + ); + expect(await verify(withHeader(token))).toBe(true); + }); + + it("compares the email case-insensitively", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign( + keys.privateKey, + header, + validClaims({ email: "Owner@Example.COM" }) + ); + expect(await verify(withHeader(token), " owner@example.com ")).toBe(true); + }); + + it.each([ + ["wrong aud", { aud: ["other-aud"] }], + ["wrong iss", { iss: "https://evil.cloudflareaccess.com" }], + ["expired", { exp: now() - 1 }], + ["missing exp", { exp: undefined }], + ["nbf in the future", { nbf: now() + 600 }], + ["missing nbf", { nbf: undefined }], + ["wrong email", { email: "someone@example.com" }], + ["missing email", { email: undefined }], + ])("rejects %s", async (_, overrides) => { + fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, header, validClaims(overrides)); + expect(await verify(withHeader(token))).toBe(false); + }); + + it("tolerates 60 s of clock skew on nbf", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign( + keys.privateKey, + header, + validClaims({ nbf: now() + 30 }) + ); + expect(await verify(withHeader(token))).toBe(true); + }); + + it("rejects a token signed by another key", async () => { + fakeFetch({ keys: [jwk] }); + const other = await rsaKeyPair(); + const token = await sign(other.privateKey, header, validClaims()); + expect(await verify(withHeader(token))).toBe(false); + }); + + it("rejects a tampered payload", async () => { + fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, header, validClaims()); + const [h, , s] = token.split("."); + const forged = b64url( + new TextEncoder().encode( + JSON.stringify(validClaims({ email: "x@example.com" })) + ) + ); + expect(await verify(withHeader(`${h}.${forged}.${s}`))).toBe(false); + }); + + it.each([ + ["HS256", { alg: "HS256", kid: "kid-1" }], + ["none", { alg: "none", kid: "kid-1" }], + ["RS512", { alg: "RS512", kid: "kid-1" }], + ["missing kid", { alg: "RS256" }], + ])("rejects alg/header %s", async (_, h) => { + fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, h, validClaims()); + expect(await verify(withHeader(token))).toBe(false); + }); + + it("rejects an unknown kid after one refetch", async () => { + const { calls } = fakeFetch({ keys: [jwk] }); + const token = await sign( + keys.privateKey, + { ...header, kid: "kid-unknown" }, + validClaims() + ); + expect(await verify(withHeader(token))).toBe(false); + expect(calls.filter(c => c.url.endsWith("/certs"))).toHaveLength(1); + }); + + it("refetches the certs for a new kid once the cache is 30 s old", async () => { + const { calls } = fakeFetch({ keys: [jwk] }); + const first = await sign(keys.privateKey, header, validClaims()); + expect( + await proxy.verifyAccessJwt(withHeader(first), OWNER_EMAIL, now()) + ).toBe(true); + + const rotated = await rsaKeyPair(); + const rotatedJwk = await publicJwk(rotated.publicKey, "kid-2"); + fakeFetch({ keys: [jwk, rotatedJwk] }); + const second = await sign( + rotated.privateKey, + { ...header, kid: "kid-2" }, + validClaims() + ); + // Within 30 s: no refetch, unknown kid fails. + expect( + await proxy.verifyAccessJwt(withHeader(second), OWNER_EMAIL, now() + 5) + ).toBe(false); + // After 30 s the unknown kid triggers a refetch. + expect( + await proxy.verifyAccessJwt(withHeader(second), OWNER_EMAIL, now() + 31) + ).toBe(true); + expect(calls.filter(c => c.url.endsWith("/certs"))).toHaveLength(1); + }); + + it("caches the certs between requests", async () => { + const { calls } = fakeFetch({ keys: [jwk] }); + const token = await sign(keys.privateKey, header, validClaims()); + await verify(withHeader(token)); + await verify(withHeader(token)); + expect(calls.filter(c => c.url.endsWith("/certs"))).toHaveLength(1); + }); + + it("rejects a missing token", async () => { + fakeFetch({ keys: [jwk] }); + expect(await verify(new Request(`${ORIGIN}/gh/api/v3/user`))).toBe(false); + }); + + it.each(["", "abc", "a.b", "a.b.c.d", "!!!.###.$$$"])( + "rejects malformed token %j", + async token => { + fakeFetch({ keys: [jwk] }); + const request = new Request(`${ORIGIN}/gh/api/v3/user`, { + headers: { Cookie: `CF_Authorization=${token}` }, + }); + expect(await verify(request)).toBe(false); + } + ); + + it("rejects (does not throw) when the certs endpoint fails", async () => { + fakeFetch({ keys: [jwk], certsStatus: 500 }); + const token = await sign(keys.privateKey, header, validClaims()); + expect(await verify(withHeader(token))).toBe(false); + }); +}); diff --git a/cms/test/unit/auth-page.test.ts b/cms/test/unit/auth-page.test.ts new file mode 100644 index 0000000..d4fe138 --- /dev/null +++ b/cms/test/unit/auth-page.test.ts @@ -0,0 +1,43 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { cmsRoot } from "./helpers"; + +const html = readFileSync(join(cmsRoot, "public/auth.html"), "utf8"); +const script = /