Skip to content

fix: harden Pages same-origin auth and session CSRF - #5

Merged
zskbot merged 14 commits into
mainfrom
fix/auth-session-and-pages-review
Nov 12, 2026
Merged

zskbot merged 14 commits into
mainfrom
fix/auth-session-and-pages-review

Conversation

@zskbot

@zskbot zskbot commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Keep CSRF tokens deterministic per session so concurrent tabs do not invalidate one another.
  • Migrate legacy session CSRF hashes on the first session read, preserving active sessions.
  • Validate Pages requests with Origin and Fetch Metadata; reject originless state-changing requests and cross-site requests.
  • Permit only the exact GitHub OAuth callback GET to cross the site boundary, then delegate it to the Worker for OAuth state validation.
  • Preserve bodyless 204/205/304 responses.
  • Add behavioral tests for Worker delegation, OAuth callback, CSRF migration, same-origin GET, originless POST rejection, and response handling.

Review findings

  • All six automated review findings are addressed; all review threads are resolved.
  • Expired sessions are rejected by the SQL predicate s.expires_at > ?; regression coverage preserves it.

Cloudflare staging

Validation and hosting fallback

  • Catalog + 52 unit tests: success.
  • CodeQL Advanced: success.
  • Vercel status checks are failing because the Vercel account is blocked / build-rate-limited; Cloudflare Pages is the working staging alternative.
  • PR remains open and unmerged.

Safety

  • No custom domains, DNS, existing Workers, or production services changed.
  • No Production deployment initiated.

@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because your trial has ended. Ask your workspace admin to add credits to resume reviews. Manage billing

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Enforce same-origin checks on Pages auth routes, allow the GitHub OAuth callback navigation, synthesize Origin for eligible GETs, and preserve bodyless asset responses.

  • functions/[[path]].js L5, L12-28, L33

Implementation

Derive CSRF tokens deterministically from the session ID and migrate legacy stored hashes so session reads do not invalidate other tabs.

  • auth-worker/src/index.js L91-95, L178-186

Documentation

Document the Pages origin protections, OAuth callback exception, stable CSRF migration, and current staging review branch.

  • auth-worker/PAGES_STAGING.md L14, L26, L31

Tests

Add behavioral coverage for Pages routing, origin enforcement, OAuth callback navigation, HTML configuration, and bodyless responses.

  • auth-worker/test/pages-function.test.mjs L3-169

Guard against regressions in session expiry handling and stable CSRF token behavior.

  • auth-worker/test/contract.test.mjs L50-56

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T16:12:06.205054Z 46b0075 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Deploying ocodejs-cli-hub-staging with  Cloudflare Pages  Cloudflare Pages

Latest commit: 46b0075
Status: ✅  Deploy successful!
Preview URL: https://ce03f438.ocodejs-cli-hub-staging.pages.dev
Branch Preview URL: https://fix-auth-session-and-pages-r.ocodejs-cli-hub-staging.pages.dev

View logs

@vercel

vercel Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
auth-server Ready Ready Preview Nov 12, 2026 4:08pm UTC
cli Ready Ready Preview Nov 12, 2026 4:08pm UTC
cli-hub-auth-server Ready Ready Preview Nov 12, 2026 4:08pm UTC

Request Review

@vercel

vercel Bot commented Nov 12, 2026

Copy link
Copy Markdown

Deployment failed for project cli with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/ocodejs-co?upgradeToPro=build-rate-limit

@vercel

vercel Bot commented Nov 12, 2026

Copy link
Copy Markdown

Deployment failed for project cli-hub-auth-server with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/ocodejs-co?upgradeToPro=build-rate-limit

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b5c5f0f6c3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread functions/[[path]].js Resolved
Comment thread auth-worker/src/index.js Resolved

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="functions/[[path]].js" line_range="21" />
<code_context>
+      });
+    }
+    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 });
</code_context>
<issue_to_address>
**Victim gets attacker’s account**

When a cross-site POST to `/auth/pat` reaches Pages without `Origin` or `Sec-Fetch-Site`, `onRequest` supplies the Pages origin, so `originAllowed` accepts the request and `/auth/pat` creates a session for the submitted GitHub account. The victim ends up signed in to the attacker’s account.

Do not fabricate a trusted Origin for cross-site POSTs; reject auth POSTs that lack a valid Origin or other CSRF protection.
</issue_to_address>

### Comment 2
<location path="functions/[[path]].js" line_range="14" />
<code_context>
-    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,
</code_context>
<issue_to_address>
**GitHub sign-in cannot complete**

When gitHub OAuth is enabled and the browser follows GitHub’s cross-site redirect to the callback with `Sec-Fetch-Site: cross-site`, `onRequest` returns 403 before the auth Worker can validate the OAuth state or exchange the code, so the user cannot complete sign-in.

Allow the OAuth callback through the Pages guard so the auth Worker can validate its state and complete the sign-in.
</issue_to_address>

### Comment 3
<location path="auth-worker/src/index.js" line_range="179" />
<code_context>
-    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 });
   }
</code_context>
<issue_to_address>
**Existing sessions fail protected requests**

When an unexpired session created before this change is read after deployment, `csrfForSession` returns a token derived from the session ID, but the row still stores the hash of the old random token. `requireSession` rejects the derived token, so protected requests—including API calls, logout, and disconnect—fail with 403.

Update the stored `csrf_hash` to the HMAC of the derived token when returning it for an existing session.
</issue_to_address>

### Comment 4
<location path="auth-worker/test/pages-function.test.mjs" line_range="44" />
<code_context>
+    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");
+});
+
</code_context>
<issue_to_address>
**Health routing regression passes**

When the Pages handler returns a hard-coded response with `service: "ocodejs-auth-worker"`, the `Pages routes health requests through the auth Worker` test checks only `service` at line 44; a Pages handler that returns that field directly without delegating still passes, so a broken Worker route appears healthy.

Make the Worker call observable in the test, for example through an injectable Worker dependency that can be spied on.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and the Pages Function rejects a mismatched Origin, but it also supplies the Pages origin whenever Origin is absent, for every method—not just browser GETs. If an auth mutation relies on Origin as a guard and lacks an independent CSRF check, a request without Origin could be treated as same-origin; reverting restores the prior behavior, but any access or data exposure before then cannot be undone.

Blocking findings: functions/[[path]].js:21, functions/[[path]].js:14, auth-worker/src/index.js:179, auth-worker/test/pages-function.test.mjs:44


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread functions/[[path]].js Resolved
Comment thread functions/[[path]].js Resolved
Comment thread auth-worker/src/index.js Resolved
@zskbot
zskbot merged commit bd23723 into main Nov 12, 2026
9 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant