Skip to content

fix(core): resolve OAuth env safely on Cloudflare - #2339

Closed
richardjoo wants to merge 8 commits into
emdash-cms:mainfrom
richardjoo:replacement/fix-oauth-env-cloudflare
Closed

richardjoo wants to merge 8 commits into
emdash-cms:mainfrom
richardjoo:replacement/fix-oauth-env-cloudflare

Conversation

@richardjoo

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes OAuth provider login on Cloudflare Workers when newer Astro runtimes no longer expose a safe locals.runtime.env path.

This replaces the older approach in #1482 with the current local fix path that:

  • prefers locals.runtime.env when it exists and can be read safely
  • avoids crashing when that getter throws on newer Astro/Cloudflare combinations
  • falls back through virtual:emdash/env, then cloudflare:workers, then import.meta.env
  • adds focused regression tests for the helper and both OAuth routes

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 (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: https://github.com/emdash-cms/emdash/discussions/...

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: OpenCode / GPT-5.4

Screenshots / test output

  • pnpm exec oxlint --type-aware -f json | jq '.diagnostics | length' -> 0
  • pnpm typecheck passed
  • pnpm --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=30000 passed

Copilot AI lite review requested due to automatic review settings August 5, 2026 04:47
@changeset-bot

changeset-bot Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 53c12d1

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

This PR includes changesets to release 17 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/plugin-mcp-smoke 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 Aug 5, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/auth-atproto

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

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

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

emdash

npm i https://pkg.pr.new/emdash@2339

create-emdash

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

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

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

@emdash-cms/plugin-cli

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

@emdash-cms/plugin-types

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

@emdash-cms/registry-client

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

@emdash-cms/registry-lexicons

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

@emdash-cms/registry-verification

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

@emdash-cms/sandbox-workerd

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-field-kit

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: 53c12d1

Copilot AI 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.

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 from locals.runtime.env, virtual:emdash/env, cloudflare:workers, then import.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.

Comment on lines +32 to +37
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));
}

@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 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.ts helper and both OAuth routes.
  • The existing route regression tests (tests/unit/auth/oauth-*.test.ts) and the new helper unit test.
  • The virtual:emdash/env module 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.get avoids 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 reads locals.runtime.env and 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/runtime branches 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 builds virtual:emdash/env will already export undefined, 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-17

    This comment is now misleading. The new resolveOAuthEnv helper deliberately reads Astro.locals.runtime.env via Reflect.get and catches any throwing getter before falling back through virtual:emdash/env, cloudflare:workers, and import.meta.env. The route does touch locals.runtime; it just does so safely. The reference to #1736 also 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-17

    This comment is now misleading. The new resolveOAuthEnv helper deliberately reads Astro.locals.runtime.env via Reflect.get and catches any throwing getter before falling back through virtual:emdash/env, cloudflare:workers, and import.meta.env. The route does touch locals.runtime; it just does so safely. The reference to #1736 also 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-33

    The helper unit test covers the happy path and the injected loadEnv fallback, but it does not pin the actual regression this PR fixes: a throwing getter on locals.runtime.env (or on locals.runtime itself), or the non-object locals/runtime branches. 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,
    		);
    	});
    

@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/needs-review No maintainer or bot review yet labels Aug 5, 2026
@khoinguyenpham04 khoinguyenpham04 added the bot:review Trigger an emdashbot code review on this PR label Aug 5, 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 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.

Comment on lines +32 to +49
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>> {

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.

[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.

Suggested change
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>> {

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Aug 5, 2026
@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond review/needs-rereview New commits since the last review and removed review/needs-rereview New commits since the last review review/awaiting-author Reviewed; waiting on the author to respond labels Aug 5, 2026
@richardjoo
richardjoo force-pushed the replacement/fix-oauth-env-cloudflare branch from a811512 to 61ba7c7 Compare August 6, 2026 00:58
@khoinguyenpham04 khoinguyenpham04 added the bot:review Trigger an emdashbot code review on this PR label Aug 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 #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:1

    Placing a non-route helper inside src/astro/routes means tsdown.config.ts’s route scanner bundles and publicly exports it as emdash/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.ts or a shared src/astro/utils/ path) and import them from the route files.

  • [suggestion] packages/core/src/astro/routes/api/auth/oauth/env.ts:32

    The loadEnv parameter 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 by virtual:emdash/env, so this seam is unnecessary. Simplify the helper and update the tests to mock virtual:emdash/env for 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:1

    This spec is at tests/unit/astro/oauth-env.test.ts while the source it covers is src/astro/routes/api/auth/oauth/env.ts. AGENTS.md asks test files to mirror source structure. Move it to tests/unit/astro/routes/api/auth/oauth/env.test.ts and adjust the import accordingly.

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

    The 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 with error=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 / createAuthorizationUrl so the test isolates the env-reading behavior.

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Aug 7, 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 Aug 7, 2026
@ascorbic

ascorbic commented Aug 8, 2026

Copy link
Copy Markdown
Member

Thanks for this. I think we can skip checking locals.runtime.env, because EmDash doesn't support older Astro versions that provide it. Likewise there's never going to be a scenario where virtual:emdash/env is unavailable but cloudflare:workers is. Simplify it to just use the virtual module

Comment on lines +18 to +30
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;
}
}

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.

This is backwards compat for an Astro version that EmDash doesn't support. It should be removed

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/approved Approved; no new commits since labels Aug 13, 2026
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Aug 14, 2026
@richardjoo

Copy link
Copy Markdown
Contributor Author

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 ca660c6c on July 20. That merged change added virtual:emdash/env, switched both the OAuth start and callback routes away from locals.runtime.env, added the Cloudflare regression coverage, and was released in emdash@0.33.0.

The review feedback on this PR was addressed: the unsupported locals.runtime.env compatibility path and direct cloudflare:workers fallback were removed, the branch was refreshed against current main, and the complete current CI suite passes. However, once the upstream implementation from #1845 is used as the merge base, this PR no longer carries the stated user-visible fix. Its remaining production diff primarily extracts the already-shipped inline virtual-env lookup into a helper, while its changeset would announce the same OAuth fix for a second release.

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.

@richardjoo richardjoo closed this Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core review/needs-rereview New commits since the last review size/M

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