From d1565117bb6f2fef94fef3f7f2ab78377e9ec288 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:10 +0700 Subject: [PATCH 01/14] fix: keep CSRF stable across session reads --- auth-worker/src/index.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/auth-worker/src/index.js b/auth-worker/src/index.js index 3f3eee4..45d5208 100644 --- a/auth-worker/src/index.js +++ b/auth-worker/src/index.js @@ -88,8 +88,11 @@ async function saveCredential(user, token, kind, scopes, env) { await env.DB.prepare("INSERT INTO auth_users(github_id, github_login, token_ciphertext, token_kind, scopes, updated_at) VALUES(?, ?, ?, ?, ?, ?) ON CONFLICT(github_id) DO UPDATE SET github_login=excluded.github_login, token_ciphertext=excluded.token_ciphertext, token_kind=excluded.token_kind, scopes=excluded.scopes, updated_at=excluded.updated_at") .bind(String(user.id), user.login, encrypted, kind, JSON.stringify(scopes || []), Date.now()).run(); } +async function csrfForSession(id, env) { + return hmac("csrf:" + id, env.SESSION_SECRET); +} async function createSession(githubId, env) { - const id = randomToken(), csrf = randomToken(), expires = Date.now() + SESSION_TTL * 1000; + const id = randomToken(), csrf = await csrfForSession(id, env), expires = Date.now() + SESSION_TTL * 1000; await env.DB.prepare("INSERT INTO auth_sessions(id_hash, github_id, csrf_hash, expires_at) VALUES(?, ?, ?, ?)").bind(await hmac(id, env.SESSION_SECRET), String(githubId), await hmac(csrf, env.SESSION_SECRET), expires).run(); return { id, csrf }; } @@ -172,8 +175,8 @@ async function handle(request, env) { if (path === "/auth/session" && request.method === "GET") { const session = await findSession(request, env); if (!session) return json({ connected: false }); - const csrf = randomToken(); - await env.DB.prepare("UPDATE auth_sessions SET csrf_hash=? WHERE id_hash=?").bind(await hmac(csrf, env.SESSION_SECRET), session.id_hash).run(); + const sessionId = cookies(request)[COOKIE]; + const csrf = await csrfForSession(sessionId, env); return json({ connected: true, user: publicUser(session), csrfToken: csrf }); } if (path === "/auth/logout" && request.method === "POST") { From babe87cc3bb05856aeaa6e28c3aa70624ca7ee27 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:15 +0700 Subject: [PATCH 02/14] fix: validate same-origin Pages requests and preserve 304 --- functions/[[path]].js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/functions/[[path]].js b/functions/[[path]].js index 95adb0d..5038e2f 100644 --- a/functions/[[path]].js +++ b/functions/[[path]].js @@ -9,11 +9,23 @@ export async function onRequest(context) { // Keep authentication and API requests on the Pages origin so Safari treats // the HttpOnly session cookie as first-party rather than a third-party cookie. if (AUTH_ROUTE.test(url.pathname)) { - return authWorker.fetch(request, { ...env, APP_ORIGIN: url.origin }); + const origin = request.headers.get("Origin"); + const fetchSite = request.headers.get("Sec-Fetch-Site"); + if ((origin && origin !== url.origin) || fetchSite === "cross-site") { + return new Response(JSON.stringify({ error: "origin_not_allowed" }), { + status: 403, + headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } + }); + } + const headers = new Headers(request.headers); + if (!origin) headers.set("Origin", url.origin); + const sameOriginRequest = new Request(request, { headers }); + return authWorker.fetch(sameOriginRequest, { ...env, APP_ORIGIN: url.origin }); } // Pass static assets through to the Pages asset pipeline. const response = await context.next(); + if ([204, 205, 304].includes(response.status)) return response; const contentType = response.headers.get("content-type") || ""; if (!contentType.includes("text/html")) return response; From 7ba408b92b31c80e1aa8ae947ca59e3cf4f411df Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:24 +0700 Subject: [PATCH 03/14] test: exercise Pages auth routing and browser edge cases --- auth-worker/test/pages-function.test.mjs | 122 +++++++++++++++++++++-- 1 file changed, 113 insertions(+), 9 deletions(-) diff --git a/auth-worker/test/pages-function.test.mjs b/auth-worker/test/pages-function.test.mjs index 2172fdc..db68ce8 100644 --- a/auth-worker/test/pages-function.test.mjs +++ b/auth-worker/test/pages-function.test.mjs @@ -1,16 +1,120 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; +import { webcrypto } from "node:crypto"; +import { onRequest } from "../../functions/[[path]].js"; -const source = await readFile(new URL("../../functions/[[path]].js", import.meta.url), "utf8"); +if (!globalThis.crypto) globalThis.crypto = webcrypto; -test("Pages Functions routes auth endpoints through the same-origin Worker", () => { - assert.match(source, /AUTH_ROUTE/); - assert.match(source, /authWorker\.fetch\(request, \{ \.\.\.env, APP_ORIGIN: url\.origin \}\)/); - assert.match(source, /context\.next\(\)/); +const secret = "test-session-secret-for-pages-contract"; +const sessionId = "test-session-cookie-value"; +const b64url = bytes => Buffer.from(bytes).toString("base64url"); +async function hmac(value) { + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"] + ); + return b64url(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value))); +} + +function envWithDb(first) { + return { + SESSION_SECRET: secret, + TOKEN_ENCRYPTION_KEY: Buffer.alloc(32, 7).toString("base64"), + DB: { + prepare() { + return { + bind() { return this; }, + async first() { return first; } + }; + } + } + }; +} + +test("Pages routes health requests through the auth Worker", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/health"), + env: {}, + next: async () => { throw new Error("static asset pipeline must not run"); } + }); + assert.equal(response.status, 200); + assert.equal((await response.json()).service, "ocodejs-auth-worker"); +}); + +test("Pages safely supplies Origin for same-origin GET requests without Origin", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/api/github/user"), + env: envWithDb(null), + next: async () => { throw new Error("auth route must not reach static assets"); } + }); + assert.equal(response.status, 401); + assert.deepEqual(await response.json(), { error: "not_authenticated" }); +}); + +test("session reads return a stable CSRF token across tabs", async () => { + const csrf = await hmac("csrf:" + sessionId); + const row = { + id_hash: await hmac(sessionId), + github_id: "123", + csrf_hash: await hmac(csrf), + expires_at: Date.now() + 60_000, + github_login: "ocodejs-test", + token_ciphertext: "unused", + token_kind: "pat", + scopes: "[]" + }; + const env = envWithDb(row); + const readSession = () => onRequest({ + request: new Request("https://preview.pages.dev/auth/session", { + headers: { Cookie: "ocode_session=" + sessionId } + }), + env, + next: async () => { throw new Error("auth route must not reach static assets"); } + }); + const first = await (await readSession()).json(); + const second = await (await readSession()).json(); + assert.equal(first.connected, true); + assert.equal(first.csrfToken, second.csrfToken); + assert.equal(first.csrfToken, csrf); +}); + +test("HTML responses receive the active Pages origin configuration", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/"), + env: {}, + next: async () => new Response("ok", { + headers: { "content-type": "text/html; charset=utf-8" } + }) + }); + assert.match(await response.text(), /window\.OCODE_AUTH_API = location\.origin/); +}); + +test("conditional HTML requests preserve bodyless 304 responses", async () => { + const original = new Response(null, { + status: 304, + headers: { "content-type": "text/html; charset=utf-8", etag: '"cached"' } + }); + const response = await onRequest({ + request: new Request("https://preview.pages.dev/"), + env: {}, + next: async () => original + }); + assert.equal(response.status, 304); + assert.equal(await response.text(), ""); + assert.equal(response.headers.get("etag"), '"cached"'); }); -test("Pages HTML configures the auth API to use the current origin", () => { - assert.match(source, /window\.OCODE_AUTH_API = location\.origin/); - assert.match(source, /contentType\.includes\("text\/html"\)/); +test("cross-site auth requests are rejected before reaching the Worker", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/auth/logout", { + method: "POST", + headers: { Origin: "https://attacker.example", "Sec-Fetch-Site": "cross-site" } + }), + env: {}, + next: async () => { throw new Error("auth route must not reach static assets"); } + }); + assert.equal(response.status, 403); }); From b5c5f0f6c3417a0c2be843ec3c56ed7377a70896 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:42 +0700 Subject: [PATCH 04/14] docs: record Pages auth review fixes --- auth-worker/PAGES_STAGING.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/auth-worker/PAGES_STAGING.md b/auth-worker/PAGES_STAGING.md index 158ffde..ae4edc8 100644 --- a/auth-worker/PAGES_STAGING.md +++ b/auth-worker/PAGES_STAGING.md @@ -11,7 +11,7 @@ The CLI Hub staging host is isolated from the existing OCodeJS production servic ## Same-origin auth -`functions/[[path]].js` sends `/health`, `/auth/*`, and `/api/*` to the existing auth Worker module. Other requests continue to the static Pages asset pipeline. HTML responses set `window.OCODE_AUTH_API` to the current Pages origin. This keeps the HttpOnly session cookie first-party in Safari. +`functions/[[path]].js` sends `/health`, `/auth/*`, and `/api/*` to the existing auth Worker module. It rejects mismatched Origin and Fetch Metadata cross-site requests, then supplies the active Pages origin for same-origin browser GET requests that omit Origin. Other requests continue to the static Pages asset pipeline. HTML responses set `window.OCODE_AUTH_API` to the current Pages origin. This keeps the HttpOnly session cookie first-party in Safari. The staging D1 migration `auth-worker/migrations/0001_init.sql` has been applied and the Pages deployment configuration has the `DB` binding in both preview and production environments. @@ -23,9 +23,9 @@ Already configured for both Preview and Production: - `TOKEN_ENCRYPTION_KEY` — generated as a base64-encoded 32-byte key and stored as an encrypted Pages secret. - `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` — not configured; only required to enable GitHub OAuth. -The Pages Function sets `APP_ORIGIN` from the exact active Pages request origin at runtime. This supports both the stable staging hostname and branch-preview hostnames without allowing cross-origin requests. PAT login is backend-configured. GitHub OAuth remains disabled until its dedicated OAuth App credentials are configured. GitHub OAuth additionally requires a dedicated OAuth App whose callback URL is `https://ocodejs-cli-hub-staging.pages.dev/auth/github/callback`. +The Pages Function sets `APP_ORIGIN` from the exact active Pages request origin at runtime. This supports both the stable staging hostname and branch-preview hostnames without allowing cross-origin requests. The auth Worker now derives a stable per-session CSRF token so parallel tabs do not invalidate each other's tokens; session lookup also rejects expired sessions at the SQL query. PAT login is backend-configured. GitHub OAuth remains disabled until its dedicated OAuth App credentials are configured. GitHub OAuth additionally requires a dedicated OAuth App whose callback URL is `https://ocodejs-cli-hub-staging.pages.dev/auth/github/callback`. Do not copy secrets into GitHub files, commits, issue comments, or chat. Do not attach a custom domain or alter existing `app`, `mcp`, or auth Workers. -Cloudflare Pages is connected to this repository for the isolated staging project. Only the `feat/cloudflare-pages-same-origin-auth` branch is included for Preview deployments; automatic deployments from `main` are disabled. +Cloudflare Pages is connected to this repository for the isolated staging project. Only the `feat/cloudflare-pages-same-origin-auth` branch is included for Preview deployments; automatic deployments from `main` are disabled. The current review fixes are being developed in `fix/auth-session-and-pages-review` and will require the Pages Preview branch filter to include that branch before deployment. From e89608c4459cebe53cc54155000644710d9c8995 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:14 +0700 Subject: [PATCH 05/14] test: guard session expiry and stable CSRF invariants --- auth-worker/test/contract.test.mjs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/auth-worker/test/contract.test.mjs b/auth-worker/test/contract.test.mjs index 0de8912..0d8a3ea 100644 --- a/auth-worker/test/contract.test.mjs +++ b/auth-worker/test/contract.test.mjs @@ -47,3 +47,10 @@ test("D1 migration creates only auth-owned tables and indexes", () => { assert.match(migration, /FOREIGN KEY\(github_id\) REFERENCES auth_users/); assert.match(migration, /auth_sessions_expiry_idx/); }); + +test("session lookup rejects expired rows and CSRF does not rotate on reads", () => { + assert.match(worker, /s\.expires_at>\?/); + assert.match(worker, /csrfForSession\(id, env\)/); + assert.match(worker, /csrfForSession\(sessionId, env\)/); + assert.doesNotMatch(worker, /UPDATE auth_sessions SET csrf_hash/); +}); From 30d1b00bfbb8bc1710a67a4c10a0e6cd6dd458ac Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:04:17 +0700 Subject: [PATCH 06/14] docs: update staging review branch status --- auth-worker/PAGES_STAGING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth-worker/PAGES_STAGING.md b/auth-worker/PAGES_STAGING.md index ae4edc8..cd7c7b1 100644 --- a/auth-worker/PAGES_STAGING.md +++ b/auth-worker/PAGES_STAGING.md @@ -28,4 +28,4 @@ The Pages Function sets `APP_ORIGIN` from the exact active Pages request origin Do not copy secrets into GitHub files, commits, issue comments, or chat. Do not attach a custom domain or alter existing `app`, `mcp`, or auth Workers. -Cloudflare Pages is connected to this repository for the isolated staging project. Only the `feat/cloudflare-pages-same-origin-auth` branch is included for Preview deployments; automatic deployments from `main` are disabled. The current review fixes are being developed in `fix/auth-session-and-pages-review` and will require the Pages Preview branch filter to include that branch before deployment. +Cloudflare Pages is connected to this repository for the isolated staging project. Only the `feat/cloudflare-pages-same-origin-auth` branch is included for Preview deployments; automatic deployments from `main` are disabled. The current review fixes are in `fix/auth-session-and-pages-review` (PR #5). The Pages Preview branch filter includes this branch; automatic Production deployments remain disabled. From 571af8792647a1513c2c8d511c03e8083f34ed31 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:06:29 +0700 Subject: [PATCH 07/14] fix: allow verified OAuth callback navigations --- functions/[[path]].js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/functions/[[path]].js b/functions/[[path]].js index 5038e2f..213210d 100644 --- a/functions/[[path]].js +++ b/functions/[[path]].js @@ -11,14 +11,15 @@ export async function onRequest(context) { if (AUTH_ROUTE.test(url.pathname)) { const origin = request.headers.get("Origin"); const fetchSite = request.headers.get("Sec-Fetch-Site"); - if ((origin && origin !== url.origin) || fetchSite === "cross-site") { + const isOAuthCallback = url.pathname === "/auth/github/callback" && request.method === "GET"; + if (!isOAuthCallback && ((origin && origin !== url.origin) || fetchSite === "cross-site")) { return new Response(JSON.stringify({ error: "origin_not_allowed" }), { status: 403, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } }); } const headers = new Headers(request.headers); - if (!origin) headers.set("Origin", url.origin); + if (isOAuthCallback || !origin) headers.set("Origin", url.origin); const sameOriginRequest = new Request(request, { headers }); return authWorker.fetch(sameOriginRequest, { ...env, APP_ORIGIN: url.origin }); } From f20c5e29d2ef72fd20b7d09cda1d25724b5297e1 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:06:33 +0700 Subject: [PATCH 08/14] fix: migrate legacy session CSRF hashes --- auth-worker/src/index.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/auth-worker/src/index.js b/auth-worker/src/index.js index 45d5208..db906f9 100644 --- a/auth-worker/src/index.js +++ b/auth-worker/src/index.js @@ -177,6 +177,13 @@ async function handle(request, env) { if (!session) return json({ connected: false }); const sessionId = cookies(request)[COOKIE]; const csrf = await csrfForSession(sessionId, env); + const csrfHash = await hmac(csrf, env.SESSION_SECRET); + // Migrate pre-deterministic CSRF hashes once. Concurrent reads calculate + // the same token and write the same hash, so active tabs remain compatible. + if (csrfHash !== session.csrf_hash) { + await env.DB.prepare("UPDATE auth_sessions SET csrf_hash=? WHERE id_hash=?") + .bind(csrfHash, session.id_hash).run(); + } return json({ connected: true, user: publicUser(session), csrfToken: csrf }); } if (path === "/auth/logout" && request.method === "POST") { From 6b1d50d779d8b62b4c8515e5a1f31514372c6f02 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:06:36 +0700 Subject: [PATCH 09/14] test: cover OAuth callback and legacy CSRF migration --- auth-worker/test/pages-function.test.mjs | 42 +++++++++++++++++++----- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/auth-worker/test/pages-function.test.mjs b/auth-worker/test/pages-function.test.mjs index db68ce8..1204579 100644 --- a/auth-worker/test/pages-function.test.mjs +++ b/auth-worker/test/pages-function.test.mjs @@ -19,15 +19,27 @@ async function hmac(value) { return b64url(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value))); } -function envWithDb(first) { +function envWithDb(initialRow) { + let row = initialRow; + const updates = []; return { SESSION_SECRET: secret, TOKEN_ENCRYPTION_KEY: Buffer.alloc(32, 7).toString("base64"), + __updates: updates, + __getRow: () => row, DB: { - prepare() { + prepare(sql) { + let values = []; return { - bind() { return this; }, - async first() { return first; } + bind(...args) { values = args; return this; }, + async first() { return row; }, + async run() { + if (sql.startsWith("UPDATE auth_sessions")) { + updates.push(values); + row = { ...row, csrf_hash: values[0] }; + } + return { success: true }; + } }; } } @@ -54,12 +66,12 @@ test("Pages safely supplies Origin for same-origin GET requests without Origin", assert.deepEqual(await response.json(), { error: "not_authenticated" }); }); -test("session reads return a stable CSRF token across tabs", async () => { - const csrf = await hmac("csrf:" + sessionId); +test("session reads migrate legacy CSRF hashes and stay stable across tabs", async () => { + const legacyHash = await hmac("legacy-random-csrf-token"); const row = { id_hash: await hmac(sessionId), github_id: "123", - csrf_hash: await hmac(csrf), + csrf_hash: legacyHash, expires_at: Date.now() + 60_000, github_login: "ocodejs-test", token_ciphertext: "unused", @@ -78,7 +90,9 @@ test("session reads return a stable CSRF token across tabs", async () => { const second = await (await readSession()).json(); assert.equal(first.connected, true); assert.equal(first.csrfToken, second.csrfToken); - assert.equal(first.csrfToken, csrf); + assert.equal(first.csrfToken, await hmac("csrf:" + sessionId)); + assert.equal(env.__updates.length, 1); + assert.equal(env.__getRow().csrf_hash, await hmac(first.csrfToken)); }); test("HTML responses receive the active Pages origin configuration", async () => { @@ -118,3 +132,15 @@ test("cross-site auth requests are rejected before reaching the Worker", async ( }); assert.equal(response.status, 403); }); + +test("GitHub OAuth callback permits cross-site top-level GET navigation", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/auth/github/callback?error=access_denied", { + headers: { Origin: "https://github.com", "Sec-Fetch-Site": "cross-site" } + }), + env: {}, + next: async () => { throw new Error("auth route must not reach static assets"); } + }); + assert.equal(response.status, 302); + assert.equal(response.headers.get("location"), "https://preview.pages.dev/?auth=cancelled"); +}); From 78b6efb6b6c2dc4263d6a0607ce4f0febd0f5390 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:06:39 +0700 Subject: [PATCH 10/14] test: require compatibility migration for stored CSRF hashes --- auth-worker/test/contract.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth-worker/test/contract.test.mjs b/auth-worker/test/contract.test.mjs index 0d8a3ea..b1fa868 100644 --- a/auth-worker/test/contract.test.mjs +++ b/auth-worker/test/contract.test.mjs @@ -52,5 +52,5 @@ test("session lookup rejects expired rows and CSRF does not rotate on reads", () assert.match(worker, /s\.expires_at>\?/); assert.match(worker, /csrfForSession\(id, env\)/); assert.match(worker, /csrfForSession\(sessionId, env\)/); - assert.doesNotMatch(worker, /UPDATE auth_sessions SET csrf_hash/); + assert.match(worker, /UPDATE auth_sessions SET csrf_hash/); }); From b33a1ae357da6fa1dfcd290d0c81dcb85c3329b6 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:06:42 +0700 Subject: [PATCH 11/14] docs: document OAuth callback and legacy CSRF compatibility --- auth-worker/PAGES_STAGING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth-worker/PAGES_STAGING.md b/auth-worker/PAGES_STAGING.md index cd7c7b1..feeda9e 100644 --- a/auth-worker/PAGES_STAGING.md +++ b/auth-worker/PAGES_STAGING.md @@ -23,7 +23,7 @@ Already configured for both Preview and Production: - `TOKEN_ENCRYPTION_KEY` — generated as a base64-encoded 32-byte key and stored as an encrypted Pages secret. - `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` — not configured; only required to enable GitHub OAuth. -The Pages Function sets `APP_ORIGIN` from the exact active Pages request origin at runtime. This supports both the stable staging hostname and branch-preview hostnames without allowing cross-origin requests. The auth Worker now derives a stable per-session CSRF token so parallel tabs do not invalidate each other's tokens; session lookup also rejects expired sessions at the SQL query. PAT login is backend-configured. GitHub OAuth remains disabled until its dedicated OAuth App credentials are configured. GitHub OAuth additionally requires a dedicated OAuth App whose callback URL is `https://ocodejs-cli-hub-staging.pages.dev/auth/github/callback`. +The Pages Function allows the exact GitHub OAuth callback GET to return from a cross-site top-level navigation, while still rejecting other cross-site auth requests. It sets `APP_ORIGIN` from the exact active Pages request origin at runtime. This supports both the stable staging hostname and branch-preview hostnames without allowing cross-origin requests. The auth Worker now derives a stable per-session CSRF token so parallel tabs do not invalidate each other's tokens. Legacy session CSRF hashes are migrated on the first session read, and session lookup rejects expired sessions at the SQL query. PAT login is backend-configured. GitHub OAuth remains disabled until its dedicated OAuth App credentials are configured. GitHub OAuth additionally requires a dedicated OAuth App whose callback URL is `https://ocodejs-cli-hub-staging.pages.dev/auth/github/callback`. Do not copy secrets into GitHub files, commits, issue comments, or chat. Do not attach a custom domain or alter existing `app`, `mcp`, or auth Workers. From 1086750d6253b2bf308e0baf810fbcf209368f92 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:07:13 +0700 Subject: [PATCH 12/14] fix: require Origin on writes and preserve OAuth callback --- functions/[[path]].js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/functions/[[path]].js b/functions/[[path]].js index 213210d..c83a80f 100644 --- a/functions/[[path]].js +++ b/functions/[[path]].js @@ -2,7 +2,7 @@ import authWorker from "../auth-worker/src/index.js"; const AUTH_ROUTE = /^\/(?:health|auth(?:\/|$)|api(?:\/|$))/; -export async function onRequest(context) { +export async function onRequest(context, auth = authWorker) { const { request, env } = context; const url = new URL(request.url); @@ -12,16 +12,20 @@ export async function onRequest(context) { const origin = request.headers.get("Origin"); const fetchSite = request.headers.get("Sec-Fetch-Site"); const isOAuthCallback = url.pathname === "/auth/github/callback" && request.method === "GET"; - if (!isOAuthCallback && ((origin && origin !== url.origin) || fetchSite === "cross-site")) { + if (!isOAuthCallback && ( + (origin && origin !== url.origin) || + fetchSite === "cross-site" || + (request.method !== "GET" && !origin) + )) { return new Response(JSON.stringify({ error: "origin_not_allowed" }), { status: 403, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } }); } const headers = new Headers(request.headers); - if (isOAuthCallback || !origin) headers.set("Origin", url.origin); + if (isOAuthCallback || (!origin && request.method === "GET")) headers.set("Origin", url.origin); const sameOriginRequest = new Request(request, { headers }); - return authWorker.fetch(sameOriginRequest, { ...env, APP_ORIGIN: url.origin }); + return auth.fetch(sameOriginRequest, { ...env, APP_ORIGIN: url.origin }); } // Pass static assets through to the Pages asset pipeline. From 5e6eeb11cbc5455a08cd361ed08d5f0fa40fad17 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:07:16 +0700 Subject: [PATCH 13/14] test: verify Worker delegation and reject originless writes --- auth-worker/test/pages-function.test.mjs | 30 +++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/auth-worker/test/pages-function.test.mjs b/auth-worker/test/pages-function.test.mjs index 1204579..d12eda4 100644 --- a/auth-worker/test/pages-function.test.mjs +++ b/auth-worker/test/pages-function.test.mjs @@ -46,14 +46,25 @@ function envWithDb(initialRow) { }; } -test("Pages routes health requests through the auth Worker", async () => { +test("Pages delegates health requests to the injected auth Worker", async () => { + const calls = []; + const worker = { + async fetch(request, env) { + calls.push({ url: request.url, origin: request.headers.get("Origin"), appOrigin: env.APP_ORIGIN }); + return Response.json({ service: "test-worker" }); + } + }; const response = await onRequest({ request: new Request("https://preview.pages.dev/health"), env: {}, next: async () => { throw new Error("static asset pipeline must not run"); } - }); + }, worker); assert.equal(response.status, 200); - assert.equal((await response.json()).service, "ocodejs-auth-worker"); + assert.equal((await response.json()).service, "test-worker"); + assert.equal(calls.length, 1); + assert.equal(new URL(calls[0].url).pathname, "/health"); + assert.equal(calls[0].origin, "https://preview.pages.dev"); + assert.equal(calls[0].appOrigin, "https://preview.pages.dev"); }); test("Pages safely supplies Origin for same-origin GET requests without Origin", async () => { @@ -121,6 +132,19 @@ test("conditional HTML requests preserve bodyless 304 responses", async () => { assert.equal(response.headers.get("etag"), '"cached"'); }); +test("state-changing auth requests without Origin are rejected", async () => { + const response = await onRequest({ + request: new Request("https://preview.pages.dev/auth/pat", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ token: "ghp_exampletokenvalue1234567890" }) + }), + env: {}, + next: async () => { throw new Error("auth route must not reach static assets"); } + }); + assert.equal(response.status, 403); +}); + test("cross-site auth requests are rejected before reaching the Worker", async () => { const response = await onRequest({ request: new Request("https://preview.pages.dev/auth/logout", { From 46b007543c8fa5516cd8ec8ad302019f02d994f8 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:08:04 +0700 Subject: [PATCH 14/14] test: provide D1 rate-limit stub for OAuth callback --- auth-worker/test/pages-function.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth-worker/test/pages-function.test.mjs b/auth-worker/test/pages-function.test.mjs index d12eda4..112d731 100644 --- a/auth-worker/test/pages-function.test.mjs +++ b/auth-worker/test/pages-function.test.mjs @@ -162,7 +162,7 @@ test("GitHub OAuth callback permits cross-site top-level GET navigation", async request: new Request("https://preview.pages.dev/auth/github/callback?error=access_denied", { headers: { Origin: "https://github.com", "Sec-Fetch-Site": "cross-site" } }), - env: {}, + env: envWithDb(null), next: async () => { throw new Error("auth route must not reach static assets"); } }); assert.equal(response.status, 302);