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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions auth-worker/PAGES_STAGING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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 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.


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 in `fix/auth-session-and-pages-review` (PR #5). The Pages Preview branch filter includes this branch; automatic Production deployments remain disabled.
16 changes: 13 additions & 3 deletions auth-worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
Expand Down Expand Up @@ -172,8 +175,15 @@ 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);
Comment thread
zskbot marked this conversation as resolved.
Resolved
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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") {
Expand Down
7 changes: 7 additions & 0 deletions auth-worker/test/contract.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.match(worker, /UPDATE auth_sessions SET csrf_hash/);
});
172 changes: 163 additions & 9 deletions auth-worker/test/pages-function.test.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,170 @@
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(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(sql) {
let values = [];
return {
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 };
}
};
}
}
};
}

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, "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 () => {
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 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: legacyHash,
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, 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 () => {
const response = await onRequest({
request: new Request("https://preview.pages.dev/"),
env: {},
next: async () => new Response("<html><head></head><body>ok</body></html>", {
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("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", {
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);
});

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("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: envWithDb(null),
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");
});
21 changes: 19 additions & 2 deletions functions/[[path]].js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,35 @@ 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);

// 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");
const isOAuthCallback = url.pathname === "/auth/github/callback" && request.method === "GET";
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 && request.method === "GET")) headers.set("Origin", url.origin);
const sameOriginRequest = new Request(request, { headers });
return auth.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;

Expand Down
Loading