Repository navigation
fix(core): resolve OAuth env safely on Cloudflare - #2339
richardjoo wants to merge 8 commits into
Conversation
🦋 Changeset detectedLatest commit: 53c12d1 The changes in this PR will be included in the next version bump. This PR includes changesets to release 17 packages
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 |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
Pull request overview
This PR fixes OAuth provider login on Astro/Cloudflare combinations where accessing locals.runtime.env can throw, by centralizing env resolution into a safe helper and updating both OAuth routes to use it.
Changes:
- Add
resolveOAuthEnv()helper to safely resolve env fromlocals.runtime.env,virtual:emdash/env,cloudflare:workers, thenimport.meta.env. - Update OAuth start and callback routes to use the helper instead of directly importing the virtual env module.
- Add a unit test for
resolveOAuthEnv()and a changeset for a patch release.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| packages/core/tests/unit/astro/oauth-env.test.ts | Adds unit coverage for env resolution behavior and fallbacks. |
| packages/core/src/astro/routes/api/auth/oauth/env.ts | Introduces shared env resolution helper for OAuth routes. |
| packages/core/src/astro/routes/api/auth/oauth/[provider]/callback.ts | Switches callback route to use the shared env resolver. |
| packages/core/src/astro/routes/api/auth/oauth/[provider].ts | Switches OAuth start route to use the shared env resolver. |
| .changeset/fair-rules-joke.md | Publishes a patch changeset for the OAuth fix. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| async function loadWorkersEnv(): Promise<Record<string, unknown> | undefined> { | ||
| try { | ||
| const { env } = await import("cloudflare:workers"); | ||
| if (typeof env === "object" && env !== null) { | ||
| return Object.fromEntries(Object.entries(env)); | ||
| } |
There was a problem hiding this comment.
This is the right change for the reported issue. Extracting the env-resolution logic into a small helper keeps the OAuth routes readable and gives the runtime-specific Reflect.get/try-catch a clear home. The precedence order (locals.runtime.env → virtual:emdash/env → cloudflare:workers → import.meta.env) is the correct fix for the Astro 6+ Cloudflare getter-throw regression.
What I checked:
- The new
env.tshelper and both OAuth routes. - The existing route regression tests (
tests/unit/auth/oauth-*.test.ts) and the new helper unit test. - The
virtual:emdash/envmodule generation in the Astro integration, to confirm how the fallback chain behaves under the Cloudflare vs Node adapters. - AGENTS.md conventions (comments, import discipline, changesets).
Headline conclusion:
- Code logic is sound: all runtime accesses are wrapped in try/catch, and
Reflect.getavoids the optional-chaining getter trap. - The changeset is present and user-focused.
- The main issues are stale/misleading comments in the pre-existing OAuth route regression tests: they claim the route "no longer touches
locals.runtime", but the new helper intentionally readslocals.runtime.envand catches any throwing getter before falling back. Those comments also reference#1736, which violates AGENTS.md comment discipline. - The new helper unit test should also pin the throwing-getter and non-object
locals/runtimebranches directly; the route tests currently cover that regression indirectly. - Minor systemic concern (unverified without a build run): the helper introduces a runtime dynamic
import("cloudflare:workers")that is not used anywhere else in core. On Node buildsvirtual:emdash/envwill already exportundefined, so every OAuth request will attempt the import and catch its failure. This works, but adds an unnecessary dynamic import on the non-Cloudflare path and may complicate bundling. Consider whether the virtual module alone is sufficient, or add a brief inline note explaining why the direct import is needed.
Findings
-
[needs fixing]
packages/core/tests/unit/auth/oauth-start-route.test.ts:5-17This comment is now misleading. The new
resolveOAuthEnvhelper deliberately readsAstro.locals.runtime.envviaReflect.getand catches any throwing getter before falling back throughvirtual:emdash/env,cloudflare:workers, andimport.meta.env. The route does touchlocals.runtime; it just does so safely. The reference to#1736also violates AGENTS.md's comment discipline (comments should not reference issues/PRs)./** * Regression for the Astro 6+ Cloudflare case where `locals.runtime.env` * is a throwing getter. `resolveOAuthEnv` reads it safely and falls back * through the configured env sources, so the route reaches the provider * check instead of crashing with a generic oauth_error. */ -
[needs fixing]
packages/core/tests/unit/auth/oauth-callback-route.test.ts:5-17This comment is now misleading. The new
resolveOAuthEnvhelper deliberately readsAstro.locals.runtime.envviaReflect.getand catches any throwing getter before falling back throughvirtual:emdash/env,cloudflare:workers, andimport.meta.env. The route does touchlocals.runtime; it just does so safely. The reference to#1736also violates AGENTS.md's comment discipline (comments should not reference issues/PRs)./** * Regression for the Astro 6+ Cloudflare case where `locals.runtime.env` * is a throwing getter. `resolveOAuthEnv` reads it safely and falls back * through the configured env sources, so the callback reaches the provider * check instead of crashing with a generic oauth_error. */ -
[suggestion]
packages/core/tests/unit/astro/oauth-env.test.ts:4-33The helper unit test covers the happy path and the injected
loadEnvfallback, but it does not pin the actual regression this PR fixes: a throwing getter onlocals.runtime.env(or onlocals.runtimeitself), or the non-objectlocals/runtimebranches. The existing OAuth route tests exercise this indirectly, but the dedicated helper test should assert its own contract directly so a future refactor doesn't lose the safe-read behavior.it("falls back safely when locals.runtime.env is a throwing getter", async () => { const fallbackEnv = { GITHUB_CLIENT_ID: "fallback-id" }; const workersEnv = { GITHUB_CLIENT_ID: "workers-id" }; const locals = { get runtime() { return { get env(): never { throw new Error("locals.runtime.env has been removed in Astro 6+"); }, }; }, }; await expect(resolveOAuthEnv(locals, fallbackEnv, async () => workersEnv)).resolves.toBe( workersEnv, ); }); it("falls back safely when locals is not an object", async () => { const fallbackEnv = { GITHUB_CLIENT_ID: "fallback-id" }; const workersEnv = { GITHUB_CLIENT_ID: "workers-id" }; await expect(resolveOAuthEnv(null, fallbackEnv, async () => workersEnv)).resolves.toBe( workersEnv, ); await expect(resolveOAuthEnv(undefined, fallbackEnv, async () => workersEnv)).resolves.toBe( workersEnv, ); });
There was a problem hiding this comment.
This is still the right change for #1736. Extracting the env-resolution logic into resolveOAuthEnv keeps the OAuth routes readable and gives the safe Reflect.get/try-catch a clear home.
What I checked: the new env.ts helper, both OAuth routes, the existing route regression tests (oauth-start-route / oauth-callback-route), the new helper unit test, and generateEnvModule/vite-config.ts to see how virtual:emdash/env is produced.
Headline conclusion: the prior round's feedback is addressed. The stale #1736 comments are gone and the helper test now pins the throwing-getter and non-object locals branches directly. The remaining issue is the last-resort import("cloudflare:workers") fallback in the helper. On non-Cloudflare builds, virtual:emdash/env intentionally exports undefined, so every OAuth request will now attempt a dynamic cloudflare:workers import, let it fail, and only then fall back to import.meta.env. This reintroduces the exact Cloudflare-specific import that virtual:emdash/env was designed to keep out of core (see generateEnvModule: “core stays adapter-agnostic, with no direct cloudflare:workers import that would fail to resolve under a Node build”). The virtual module already re-exports cloudflare:workers env under the Cloudflare adapter, so the direct import is redundant when it would work and a failing round-trip on the logged-out Node path.
Verdict: comment — one needs_fixing item to remove the redundant direct import.
| async function loadWorkersEnv(): Promise<Record<string, unknown> | undefined> { | ||
| try { | ||
| const { env } = await import("cloudflare:workers"); | ||
| if (typeof env === "object" && env !== null) { | ||
| return Object.fromEntries(Object.entries(env)); | ||
| } | ||
|
|
||
| return undefined; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| export async function resolveOAuthEnv( | ||
| locals: unknown, | ||
| fallbackEnv: Record<string, unknown>, | ||
| loadEnv: () => Promise<Record<string, unknown> | undefined> = loadWorkersEnv, | ||
| ): Promise<Record<string, unknown>> { |
There was a problem hiding this comment.
[needs fixing] The default loadWorkersEnv fallback in lines 32-43 and the default argument on line 48 introduce a direct import("cloudflare:workers") into core. Since virtual:emdash/env is generated to re-export cloudflare:workers env under the Cloudflare adapter and undefined otherwise, this fallback is only reachable when it will either be dead code (Cloudflare) or a guaranteed failed import (Node). It also reintroduces the cross-adapter boundary that generateEnvModule/vite-config.ts were designed to avoid.
The virtual module already covers the Cloudflare path, so the helper can trust it and default loadEnv to a no-op. The injected loadEnv can stay for tests.
| async function loadWorkersEnv(): Promise<Record<string, unknown> | undefined> { | |
| try { | |
| const { env } = await import("cloudflare:workers"); | |
| if (typeof env === "object" && env !== null) { | |
| return Object.fromEntries(Object.entries(env)); | |
| } | |
| return undefined; | |
| } catch { | |
| return undefined; | |
| } | |
| } | |
| export async function resolveOAuthEnv( | |
| locals: unknown, | |
| fallbackEnv: Record<string, unknown>, | |
| loadEnv: () => Promise<Record<string, unknown> | undefined> = loadWorkersEnv, | |
| ): Promise<Record<string, unknown>> { | |
| export async function resolveOAuthEnv( | |
| locals: unknown, | |
| fallbackEnv: Record<string, unknown>, | |
| loadEnv: () => Promise<Record<string, unknown> | undefined> = async () => undefined, | |
| ): Promise<Record<string, unknown>> { |
a811512 to
61ba7c7
Compare
There was a problem hiding this comment.
This is the right fix for #1736. Extracting the safe env-resolution logic into resolveOAuthEnv keeps both OAuth routes readable, preserves the adapter-agnostic rule that core reads Cloudflare env only through virtual:emdash/env, and the new unit test pins the throwing-getter and non-object-locals branches. As a re-review: the previous blocker is addressed — the redundant direct cloudflare:workers import fallback has been removed, and the stale #1736 route comments are gone (replaced with behavior-focused regression comments).
I reviewed packages/core/src/astro/routes/api/auth/oauth/env.ts, both OAuth routes, generateEnvModule/vite-config.ts, packages/core/src/astro/integration/routes.ts, the changeset, and the new/changed tests. I found no logic regressions, security issues, broken contracts, or new queries on the logged-out OAuth paths. The remaining items are minor maintainability suggestions.
Findings
-
[suggestion]
packages/core/src/astro/routes/api/auth/oauth/env.ts:1Placing a non-route helper inside
src/astro/routesmeanstsdown.config.ts’s route scanner bundles and publicly exports it asemdash/routes/api/auth/oauth/env, even though it is never injected as a route entrypoint. Prefer moving internal helpers like this out of the routes tree (e.g.,src/auth/oauth-env.tsor a sharedsrc/astro/utils/path) and import them from the route files. -
[suggestion]
packages/core/src/astro/routes/api/auth/oauth/env.ts:32The
loadEnvparameter is only used by tests: no production caller passes it, and its default is a no-op. This makes the function signature describe a fallback chain that the real code never executes. The Cloudflare path is already covered byvirtual:emdash/env, so this seam is unnecessary. Simplify the helper and update the tests to mockvirtual:emdash/envfor the fallback branch.export async function resolveOAuthEnv( locals: unknown, fallbackEnv: Record<string, unknown>, ): Promise<Record<string, unknown>> { const runtimeEnv = readRuntimeEnv(locals); if (runtimeEnv) return runtimeEnv; const virtualEnv = await loadVirtualEnv(); return virtualEnv ?? fallbackEnv; } -
[suggestion]
packages/core/tests/unit/astro/oauth-env.test.ts:1This spec is at
tests/unit/astro/oauth-env.test.tswhile the source it covers issrc/astro/routes/api/auth/oauth/env.ts. AGENTS.md asks test files to mirror source structure. Move it totests/unit/astro/routes/api/auth/oauth/env.test.tsand adjust the import accordingly. -
[suggestion]
packages/core/tests/unit/auth/oauth-start-route.test.ts:78The assertion only confirms the response is not
error=provider_not_configured, so it passes even if the route throws while building the authorization URL (with the unmocked DB) and redirects witherror=oauth_error. That doesn’t prove the virtual-module env was actually read. Assert the redirect points to the provider’s authorization URL (e.g.,accounts.google.com), or mock the state store /createAuthorizationUrlso the test isolates the env-reading behavior.
|
Thanks for this. I think we can skip checking |
| function readRuntimeEnv(locals: unknown): Record<string, unknown> | undefined { | ||
| try { | ||
| if (typeof locals !== "object" || locals === null) return undefined; | ||
|
|
||
| const runtime = Reflect.get(locals, "runtime"); | ||
| if (!isRecord(runtime)) return undefined; | ||
|
|
||
| const env = Reflect.get(runtime, "env"); | ||
| return isRecord(env) ? env : undefined; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } |
There was a problem hiding this comment.
This is backwards compat for an Astro version that EmDash doesn't support. It should be removed
…th-env-cloudflare
…th-env-cloudflare
|
Closing this PR as superseded, rather than because the latest implementation or CI is failing. After synchronizing this branch with current upstream and reviewing the resulting diff, I confirmed that the original OAuth production fix already landed in PR #1845 as commit The review feedback on this PR was addressed: the unsupported Keeping this open would therefore require more reviewer time and create a duplicate release note without delivering an additional Cloudflare login correction. If centralizing this lookup is still desirable, it should be proposed separately as a narrowly scoped refactor with a description and changeset decision that reflect its actual behavior. Thank you to everyone who reviewed the iterations and clarified the supported adapter boundary. |
What does this PR do?
Fixes OAuth provider login on Cloudflare Workers when newer Astro runtimes no longer expose a safe
locals.runtime.envpath.This replaces the older approach in #1482 with the current local fix path that:
locals.runtime.envwhen it exists and can be read safelyvirtual:emdash/env, thencloudflare:workers, thenimport.meta.envCloses #1736
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.AI-generated code disclosure
Screenshots / test output
pnpm exec oxlint --type-aware -f json | jq '.diagnostics | length'->0pnpm typecheckpassedpnpm --filter emdash exec vitest run tests/unit/astro/oauth-env.test.ts tests/unit/auth/oauth-start-route.test.ts tests/unit/auth/oauth-callback-route.test.ts --testTimeout=30000passed