Skip to content

fix(core): read OAuth env via virtual module, not locals.runtime.env - #1845

Merged
ascorbic merged 4 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1736-oauth-cloudflare-env
Jul 20, 2026
Merged

ascorbic merged 4 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1736-oauth-cloudflare-env

Conversation

@ColoradoClimbr

Copy link
Copy Markdown
Contributor

What does this PR do?

Astro 6 removed Astro.locals.runtime.env — accessing it now throws rather than returning undefined, so the existing locals.runtime?.env ?? import.meta.env fallback never reached import.meta.env: the throw propagated into the route's outer try/catch and surfaced as a generic oauth_error, masking the real provider_not_configured diagnosis. Both OAuth routes (start + callback) hit this; passkey auth was unaffected since it doesn't read this env.

Added a virtual:emdash/env module (mirrors the existing virtual:emdash/wait-until pattern exactly): re-exports Cloudflare's env from cloudflare:workers under that adapter, undefined otherwise. Core stays adapter-agnostic this way — a direct cloudflare:workers import would fail to resolve on a Node build. Both routes now read through it instead of locals.runtime.

Closes #1736

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (n/a — server route, no UI strings)
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion (n/a — bug fix)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Sonnet 5

Screenshots / test output

packages/core/tests/unit/astro/integration/virtual-modules.test.ts + tests/unit/auth/oauth-start-route.test.ts — 20/20 pass; pnpm lint:quick clean; pnpm typecheck clean.

Opened as draft: fork already has several open PRs against this repo (non-collaborator open-PR limit).

@changeset-bot

changeset-bot Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d833b18

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/admin@1845

@emdash-cms/auth

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/auth@1845

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/auth-atproto@1845

@emdash-cms/blocks

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/blocks@1845

@emdash-cms/cloudflare

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/cloudflare@1845

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/contentful-to-portable-text@1845

emdash

npm i https://pkg.pr.new/emdash-cms/emdash@1845

create-emdash

npm i https://pkg.pr.new/emdash-cms/emdash/create-emdash@1845

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/gutenberg-to-portable-text@1845

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-cli@1845

@emdash-cms/plugin-types

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-types@1845

@emdash-cms/registry-client

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-client@1845

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-lexicons@1845

@emdash-cms/registry-verification

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/registry-verification@1845

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/sandbox-workerd@1845

@emdash-cms/x402

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/x402@1845

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-ai-moderation@1845

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-atproto@1845

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-audit-log@1845

@emdash-cms/plugin-color

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-color@1845

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-embeds@1845

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-field-kit@1845

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-forms@1845

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/emdash-cms/emdash/@emdash-cms/plugin-webhook-notifier@1845

commit: d833b18

@afonsojramos

Copy link
Copy Markdown
Contributor

Can confirm that this solves the issue

@ColoradoClimbr
ColoradoClimbr marked this pull request as ready for review July 7, 2026 17:24
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jul 7, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is the right fix for the right problem. Astro 6 removed Astro.locals.runtime.env, and EmDash’s existing optional-chaining fallback could not catch a throwing getter. Adding a virtual:emdash/env module mirrors the already-established virtual:emdash/wait-until pattern, keeps core adapter-agnostic, and restores the import.meta.env fallback on Node builds. Both affected OAuth routes are updated consistently.

I reviewed the diff and the changed files statically; I did not run tests or builds. The changeset is present and correctly targets the emdash package, and there are no SQL, localization, RTL, authorization, or locale-filtering concerns in this server-only change.

No blocking issues. I have two minor suggestions around test hygiene and coverage symmetry, both non-blocking.

Comment on lines +32 to +83
describe("OAuth start route (#1736)", () => {
it("does not throw when locals.runtime.env is a throwing getter (Astro 6+ Cloudflare)", async () => {
const request = new Request("http://localhost:4321/_emdash/api/auth/oauth/google");

const response = await startOAuth({
params: { provider: "google" },
request,
locals: makeThrowingRuntimeLocals(),
redirect: (url: string) => new Response(null, { status: 302, headers: { Location: url } }),
} as unknown as Parameters<typeof startOAuth>[0]);

// No credentials configured in this test env -- the route should
// reach the provider-configured check (not crash into the generic
// oauth_error path the old code hit when locals.runtime.env threw).
const location = response.headers.get("Location") ?? "";
expect(location).toContain("error=provider_not_configured");
expect(location).not.toContain("error=oauth_error");
});

it("reads provider credentials from the virtual:emdash/env module on Cloudflare", async () => {
vi.resetModules();
vi.doMock(
"virtual:emdash/env",
() => ({
env: {
EMDASH_OAUTH_GOOGLE_CLIENT_ID: "test-client-id",
EMDASH_OAUTH_GOOGLE_CLIENT_SECRET: "test-client-secret",
},
}),
{ virtual: true },
);
const { GET: startOAuthWithEnv } =
await import("../../../src/astro/routes/api/auth/oauth/[provider].js");

const request = new Request("http://localhost:4321/_emdash/api/auth/oauth/google");
const response = await startOAuthWithEnv({
params: { provider: "google" },
request,
locals: { emdash: { db: {} as never, config: {} } },
redirect: (url: string) => new Response(null, { status: 302, headers: { Location: url } }),
} as unknown as Parameters<typeof startOAuth>[0]);

// Credentials found -- the route proceeds past the provider-configured
// check into building the real authorization URL (which then fails on
// the unmocked DB, but NOT with provider_not_configured or oauth_error
// from the env-reading step itself).
const location = response.headers.get("Location") ?? "";
expect(location).not.toContain("error=provider_not_configured");

vi.doUnmock("virtual:emdash/env");
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[suggestion] The vi.doMock("virtual:emdash/env") and vi.resetModules() in the second test are not cleaned up after the file finishes. If more tests are added later (here or in another file sharing the same worker), they may see the mocked Cloudflare env instead of the Vitest stub.

Use an afterEach hook to reset module state and unmock the virtual module after each test:

Suggested change
describe("OAuth start route (#1736)", () => {
it("does not throw when locals.runtime.env is a throwing getter (Astro 6+ Cloudflare)", async () => {
const request = new Request("http://localhost:4321/_emdash/api/auth/oauth/google");
const response = await startOAuth({
params: { provider: "google" },
request,
locals: makeThrowingRuntimeLocals(),
redirect: (url: string) => new Response(null, { status: 302, headers: { Location: url } }),
} as unknown as Parameters<typeof startOAuth>[0]);
// No credentials configured in this test env -- the route should
// reach the provider-configured check (not crash into the generic
// oauth_error path the old code hit when locals.runtime.env threw).
const location = response.headers.get("Location") ?? "";
expect(location).toContain("error=provider_not_configured");
expect(location).not.toContain("error=oauth_error");
});
it("reads provider credentials from the virtual:emdash/env module on Cloudflare", async () => {
vi.resetModules();
vi.doMock(
"virtual:emdash/env",
() => ({
env: {
EMDASH_OAUTH_GOOGLE_CLIENT_ID: "test-client-id",
EMDASH_OAUTH_GOOGLE_CLIENT_SECRET: "test-client-secret",
},
}),
{ virtual: true },
);
const { GET: startOAuthWithEnv } =
await import("../../../src/astro/routes/api/auth/oauth/[provider].js");
const request = new Request("http://localhost:4321/_emdash/api/auth/oauth/google");
const response = await startOAuthWithEnv({
params: { provider: "google" },
request,
locals: { emdash: { db: {} as never, config: {} } },
redirect: (url: string) => new Response(null, { status: 302, headers: { Location: url } }),
} as unknown as Parameters<typeof startOAuth>[0]);
// Credentials found -- the route proceeds past the provider-configured
// check into building the real authorization URL (which then fails on
// the unmocked DB, but NOT with provider_not_configured or oauth_error
// from the env-reading step itself).
const location = response.headers.get("Location") ?? "";
expect(location).not.toContain("error=provider_not_configured");
vi.doUnmock("virtual:emdash/env");
});
});
describe("OAuth start route (#1736)", () => {
afterEach(() => {
vi.doUnmock("virtual:emdash/env");
vi.resetModules();
});
it("does not throw when locals.runtime.env is a throwing getter (Astro 6+ Cloudflare)", async () => {

@@ -115,11 +115,18 @@ export const GET: APIRoute = async ({ params, request, locals, session, redirect
}

try {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[suggestion] The callback route has the same virtual:emdash/env change as the start route, but only the start route has a new regression test. Consider adding a mirrored test (e.g. oauth-callback-route.test.ts) that exercises the callback route with a throwing locals.runtime.env getter and verifies it reaches provider_not_configured rather than oauth_error. This closes the symmetry gap and prevents the callback path from silently regressing if someone reintroduces locals.runtime access.

@github-actions github-actions Bot added review/approved Approved; no new commits since size/L review/needs-rereview New commits since the last review overlap and removed review/needs-review No maintainer or bot review yet size/M review/approved Approved; no new commits since labels Jul 7, 2026
@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Overlapping PRs

This PR modifies files that are also changed by other open PRs:

This may cause merge conflicts or duplicated work. A maintainer will coordinate.

ColoradoClimbr and others added 2 commits July 12, 2026 09:31
…1736)

Astro 6 removed Astro.locals.runtime.env -- accessing it now throws
rather than returning undefined, so the existing `locals.runtime?.env
?? import.meta.env` fallback never reached import.meta.env: the throw
propagated into the route's outer try/catch and surfaced as a generic
"oauth_error", masking the real provider_not_configured diagnosis.
Both OAuth routes (start + callback) hit this; passkey auth was
unaffected since it doesn't read this env.

Added a `virtual:emdash/env` module (mirrors the existing
`virtual:emdash/wait-until` pattern exactly): re-exports Cloudflare's
`env` from `cloudflare:workers` under that adapter, `undefined`
otherwise. Core stays adapter-agnostic this way -- a direct
`cloudflare:workers` import would fail to resolve on a Node build.
Both routes now read through it instead of `locals.runtime`.

Co-Authored-By: Claude Opus 4.8 ultracode <noreply@anthropic.com>
Addresses review feedback on #1845: unmock virtual:emdash/env and reset
modules in afterEach so later tests in the same worker don't see a leaked
mock, and add a regression test for the callback route mirroring the
existing start-route coverage for #1736.
@ColoradoClimbr
ColoradoClimbr force-pushed the fix/1736-oauth-cloudflare-env branch from ff14694 to b17e790 Compare July 12, 2026 14:33
…ta.env

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review of #1845 for #1736. The approach is still correct: virtual:emdash/env mirrors the established virtual:emdash/wait-until pattern, keeps core adapter-agnostic, and restores the import.meta.env fallback on Node builds. Both OAuth routes are migrated consistently, and I found no other locals.runtime.env accesses in packages/core. The changeset is present and well-written, and the regression tests cover the throwing-getter case.

This is an approve, with two non-blocking test suggestions carried over from the previous review:

  1. Coverage symmetry — oauth-callback-route.test.ts only has the throwing-getter regression test, while oauth-start-route.test.ts also verifies that credentials provided via virtual:emdash/env are actually consumed. The callback route should get the same second test.
  2. Test hygiene — oauth-start-route.test.ts calls vi.doUnmock("virtual:emdash/env") inside the second test even though the afterEach hook already does it. Remove the body-level call.

I also noticed a sibling implementation that will hit the same Astro 6 issue, though it is out of scope for this PR: packages/cloudflare/src/plugins/vectorize-search.ts still reads locals?.runtime?.env and should be migrated in a follow-up.

I reviewed statically only.


Findings

  • [suggestion] packages/core/tests/unit/auth/oauth-callback-route.test.ts:30-51

    The callback route test file only covers the throwing-getter regression. The start route has an additional test that mocks virtual:emdash/env with provider credentials and asserts the provider configured check is reached. Add a matching second test here so callback route coverage stays symmetric and the credentials-from-env path is also exercised for the callback route.

  • [suggestion] packages/core/tests/unit/auth/oauth-start-route.test.ts:86

    This vi.doUnmock("virtual:emdash/env") call is redundant; the afterEach hook already un-mocks the module after every test. Remove the body-level call to keep mock teardown in one place.

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-rereview New commits since the last review labels Jul 20, 2026
@segmentationfaulter

Copy link
Copy Markdown
Contributor

can it be merged? This is the only PR left which will fix oAtuh providers login.

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks

@ascorbic
ascorbic merged commit ca660c6 into emdash-cms:main Jul 20, 2026
45 checks passed
@emdashbot emdashbot Bot mentioned this pull request Jul 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OAuth login (Google/GitHub) fails with "Failed to start OAuth flow" — route reads Astro.locals.runtime.env, removed in Astro 6+

4 participants