Skip to content

feat: deploy same-origin auth on isolated Cloudflare Pages staging - #4

Merged
zskbot merged 8 commits into
mainfrom
feat/cloudflare-pages-same-origin-auth
Nov 12, 2026
Merged

zskbot merged 8 commits into
mainfrom
feat/cloudflare-pages-same-origin-auth

Conversation

@zskbot

@zskbot zskbot commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add a Cloudflare Pages catch-all Function that routes /health, /auth/*, and /api/* to the existing auth Worker module.
  • Keep static assets flowing through context.next() and inject the active Pages origin into HTML, so session cookies remain first-party in Safari.
  • Validate credential-changing requests against the exact active Pages hostname, including branch-preview hostnames.
  • Add contract tests and staging setup documentation.

Staging infrastructure and deployment

  • Pages project: ocodejs-cli-hub-staging
  • Latest successful Preview: https://feat-cloudflare-pages-same-o.ocodejs-cli-hub-staging.pages.dev
  • Deployment ID: 440ca5c3-f730-4a06-8a5d-695e8af3cc37; all stages succeeded, Functions compiled, and 67 static assets were published/retained.
  • D1 database: ocodejs-cli-auth-staging (APAC); migration 0001_init.sql applied and schema verified.
  • D1 binding DB configured for Preview and Production.
  • SESSION_SECRET and TOKEN_ENCRYPTION_KEY generated cryptographically inside the Cloudflare execution environment and stored as encrypted Pages secrets in Preview and Production. Values are not in GitHub or chat.
  • GitHub source connected. Only the feature branch is enabled for Preview; automatic deployments from main are disabled.

Remaining

  • GitHub OAuth needs a dedicated OAuth App with callback https://ocodejs-cli-hub-staging.pages.dev/auth/github/callback. PAT auth backend secrets are provisioned.
  • Browser-level UI/endpoint verification from this session is unavailable; Cloudflare deployment metadata and logs confirm successful publication.

Safety

  • No custom domains or DNS changes.
  • No existing Worker or production application was changed.
  • No paid plan or production deployment enabled.
  • PR remains open for review; no merge performed.

@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 3:51pm UTC
cli Ready Ready Preview Nov 12, 2026 3:51pm UTC
cli-hub-auth-server Ready Ready Preview Nov 12, 2026 3:51pm UTC

Request Review

@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

Uses of the API

Add a Pages catch-all Function that routes auth and API requests to the existing Worker and passes other requests through while configuring HTML for the active origin.

  • functions/[[path]].js L1-35

Documentation

Document the isolated staging Pages project, its auth setup, and deployment constraints.

  • auth-worker/PAGES_STAGING.md L1-31

Tests

Add contract checks for same-origin auth routing and dynamic origin configuration in Pages HTML.

  • auth-worker/test/pages-function.test.mjs L1-16

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-12T15:52:03.104705Z d68b1fc PR opened
ℹ️ 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: f7cb1d2
Status: ✅  Deploy successful!
Preview URL: https://440ca5c3.ocodejs-cli-hub-staging.pages.dev
Branch Preview URL: https://feat-cloudflare-pages-same-o.ocodejs-cli-hub-staging.pages.dev

View logs

@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 8 issues

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

## Individual Comments

### Comment 1
<location path="auth-worker/PAGES_STAGING.md" line_range="7" />
<code_context>
+
+- Pages project: `ocodejs-cli-hub-staging`
+- Host: https://ocodejs-cli-hub-staging.pages.dev
+- D1 database: `ocodejs-cli-auth-staging` (APAC)
+- D1 binding: `DB`
+- No custom domain or DNS changes
</code_context>
<issue_to_address>
**Shared credentials become unreadable**

When preview and Production use different `TOKEN_ENCRYPTION_KEY` values and a user with an existing Production session logs into Preview with the same GitHub account, preview can save a user's token encrypted with its `TOKEN_ENCRYPTION_KEY` into the shared D1 row; a later Production API request for that user's existing session decrypts it with Production's different key, fails AES-GCM authentication, and returns 502.

Require the same stable encryption key in both environments when they share D1, or give each environment a separate database.

Also at `auth-worker/PAGES_STAGING.md:20`, `auth-worker/PAGES_STAGING.md:23`.
</issue_to_address>

### Comment 2
<location path="functions/[[path]].js" line_range="12" />
<code_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);
+  }
+
</code_context>
<issue_to_address>
**Expired sessions remain valid**

When a session cookie is replayed after its stored `expires_at`, `findSession` returns a matching row without checking `expires_at`, and `requireSession` accepts any returned session. A replayed session cookie therefore remains authenticated after its seven-day lifetime, so protected API requests continue to succeed.

Require `expires_at` to be in the future in the session lookup, and remove expired session rows as appropriate.
</issue_to_address>

### Comment 3
<location path="functions/[[path]].js" line_range="23" />
<code_context>
+  const html = await response.text();
+  const configured = html.replace(
+    "</head>",
+    '<script>window.OCODE_AUTH_API = location.origin;</script></head>'
+  );
+  const headers = new Headers(response.headers);
</code_context>
<issue_to_address>
**Preview users cannot authenticate**

When a Pages preview uses a hostname different from the configured staging origin, `authWorker.fetch` rejects preview-origin requests because `corsHeaders` and `originAllowed` require `APP_ORIGIN`, and OAuth callbacks use the configured staging origin instead of the preview host. Preview users cannot complete authentication.

Update the origin validation and OAuth callback handling so supported preview deployments can authenticate, and document the resulting configuration.

Also at `auth-worker/PAGES_STAGING.md:20`, `auth-worker/PAGES_STAGING.md:26`, `functions/[[path]].js:12`.
</issue_to_address>

### Comment 4
<location path="functions/[[path]].js" line_range="31" />
<code_context>
+  headers.delete("etag");
+  headers.set("cache-control", "no-store");
+  return new Response(configured, {
+    status: response.status,
+    statusText: response.statusText,
+    headers
</code_context>
<issue_to_address>
**Conditional HTML requests fail**

When the static asset pipeline returns a 304 response for HTML, `response.text()` produces an empty string, and `new Response(configured, { status: 304 })` rejects a response with a body for status 304. The Pages Function errors instead of returning the not-modified response.

Return the 304 response without a body instead of constructing a new response with `configured` as its body.
</issue_to_address>

### Comment 5
<location path="functions/[[path]].js" line_range="12" />
<code_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);
+  }
+
</code_context>
<issue_to_address>
**Same-origin API reads are rejected**

When a browser caller uses either API GET endpoint through the new same-origin route, when a browser makes a same-origin GET to `/api/github/user` or `/api/github/repos`, it omits the `Origin` header; the Worker’s `originAllowed` check rejects the request with 403, so callers cannot use these API endpoints through Pages. Allow validated same-origin GETs without `Origin`, or have the Pages Function provide an origin the Worker can safely validate.

Handle same-origin GET requests without an `Origin` header using a safe same-origin validation strategy.
</issue_to_address>

### Comment 6
<location path="functions/[[path]].js" line_range="12" />
<code_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);
+  }
+
</code_context>
<issue_to_address>
**Other tabs lose CSRF access**

When two tabs or overlapping `authRefresh()` calls read `/auth/session` for the same session, each `/auth/session` call replaces the session’s CSRF hash, so whichever tab’s update runs last invalidates the token returned to the other tab. That tab’s next logout or disconnect request then fails with 403.

Keep the CSRF token stable across session reads, or coordinate token rotation so other active tabs cannot retain an invalid token.
</issue_to_address>

### Comment 7
<location path="auth-worker/test/pages-function.test.mjs" line_range="8-10" />
<code_context>
+const source = await readFile(new URL("../../functions/[[path]].js", import.meta.url), "utf8");
+
+test("Pages Functions routes auth endpoints through the same-origin Worker", () => {
+  assert.match(source, /AUTH_ROUTE/);
+  assert.match(source, /authWorker\.fetch\(request, env\)/);
+  assert.match(source, /context\.next\(\)/);
+});
+
</code_context>
<issue_to_address>
**Route test passes despite broken routing**

When a later edit leaves the searched strings in the source but changes the route condition, the test only searches the source for expected strings and never invokes `onRequest`, so it passes even when auth requests do not reach `authWorker.fetch`; CI gives false confidence that same-origin auth works.

Test `onRequest` with an auth request and assert that it reaches the Worker.

Also at `auth-worker/test/pages-function.test.mjs:14-15`.
</issue_to_address>

### Comment 8
<location path="auth-worker/test/pages-function.test.mjs" line_range="14-15" />
<code_context>
+});
+
+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"\)/);
+});
</code_context>
<issue_to_address>
**Missing HTML injection goes unnoticed**

When the Function stops returning its configured HTML response but retains the origin-assignment literal and content-type check, the “Pages HTML configures the auth API to use the current origin” test passes because lines 14–15 only search the source for the script text and content-type check; it never checks the returned HTML, so Pages can serve HTML without the auth configuration.

Call `onRequest` with an HTML response and assert that the returned body contains the origin configuration.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and the Pages host will expose the existing auth and API handlers with first-party session cookies, and configured PAT login can store credentials in the staging D1 database. Reverting removes the routes, but it cannot undo any access or credential data already exposed or stored; the separate staging database bounds the impact.

Blocking findings: auth-worker/PAGES_STAGING.md:7, functions/[[path]].js:12, functions/[[path]].js:23, functions/[[path]].js:31, functions/[[path]].js:12, and 3 more


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

Comment thread auth-worker/PAGES_STAGING.md Resolved
Comment thread functions/[[path]].js Resolved
Comment thread functions/[[path]].js Resolved
Comment thread functions/[[path]].js Resolved
Comment thread functions/[[path]].js Resolved
Comment thread functions/[[path]].js Resolved

@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: d68b1fc34e

ℹ️ 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
@zskbot
zskbot merged commit d25dc83 into main Nov 12, 2026
12 of 13 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