Repository navigation
fix(auth,core): accept multiple origins for passkey verification - #800
Conversation
Closes emdash-cms#799 PasskeyConfig.origin (single string) becomes origins (string[]); register and authenticate verify against the list via .includes(). getPasskeyConfig takes an optional allowedOrigins 4th argument; verify routes pass the parsed contents of EMDASH_ALLOWED_ORIGINS. This unblocks deployments where one EmDash instance is reachable under several hostnames sharing a registrable parent (apex + preview/staging), which WebAuthn supports via shared rpId but EmDash previously rejected with a strict origin-equality check.
🦋 Changeset detectedLatest commit: 6fb9df8 The changes in this PR will be included in the next version bump. This PR includes changesets to release 13 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/blocks
@emdash-cms/cloudflare
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@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-forms
@emdash-cms/plugin-webhook-notifier
commit: |
|
/ultrareview |
There was a problem hiding this comment.
Solid bug fix. The core change (single-origin → list-membership) is small, the type rename is clean, and the test coverage at both the auth-package boundary (cross-subdomain reject + accept) and the core helper (canonical-first, dedupe, empty-skip) hits the right invariants. I confirmed the security posture is preserved: rpId is still derived from siteUrl (so the credential is bound to the registrable parent), verifyRelyingPartyIdHash(config.rpId) still runs after the origin check, and clientData.origin is normalized by the browser the same way new URL().origin normalizes the configured list.
Findings, in priority order:
1. Config-vs-env asymmetry (medium). EmDashConfig.siteUrl is a config-level option (validated at startup in integration/index.ts), but there's no parallel EmDashConfig.allowedOrigins. That means Cloudflare Workers users — who can't read process.env and therefore set siteUrl in astro.config.mjs instead — have no path to multi-origin support. The PR's own JSDoc on getEnvAllowedOrigins even acknowledges this gap ("unavailable on Cloudflare Workers"), but doesn't close it.
Recommend adding allowedOrigins?: string[] to EmDashConfig (in packages/core/src/astro/integration/runtime.ts next to siteUrl at line 272), validating it in integration/index.ts next to siteUrl, and merging it with the env value in the 5 verify routes:
getPasskeyConfig(
url, siteName, siteUrl,
[...(emdash?.config?.allowedOrigins ?? []), ...getEnvAllowedOrigins()],
);getPasskeyConfig already dedupes. This is the same model siteUrl already uses, and without it the changeset's claim of "multi-origin support" is partial.
2. Docs claim isn't enforced (low). The new docs section says "Each origin must share the registrable parent domain with siteUrl — this is a WebAuthn requirement, not an EmDash one." That's true at the browser layer (the authenticator only signs assertions for an rpId that's a registrable suffix of the document origin), but it's worth noting that an operator who lists an unrelated origin in EMDASH_ALLOWED_ORIGINS won't get an error from EmDash — they just won't get any working assertions either. Suggestion inline.
3. Cache reset helper is misnamed (nit). _resetEnvSiteUrlCache() now also clears _envAllowedOrigins. The name and JSDoc still suggest single-purpose. Suggestion inline.
4. register.ts origin-check is untested (low). The justification in the PR description is reasonable (the 3-line block is identical to authenticate.ts), but the two implementations have already diverged once — register.ts throws plain Error while authenticate.ts throws PasskeyAuthenticationError with a code. A one-line test would lock in the parity at near-zero cost.
None of these block the fix. (1) is the only one I'd want to see addressed before this is called "complete".
| /** @internal Reset cached env values — test-only. */ | ||
| export function _resetEnvSiteUrlCache(): void { | ||
| _envSiteUrl = null; | ||
| _envAllowedOrigins = null; |
There was a problem hiding this comment.
Function name is now misleading — it resets both caches, not just the site-url one. The JSDoc one line above still says "cached env value" (singular). Either rename or split. If you keep one helper, at least update the doc comment and consider:
| _envAllowedOrigins = null; | |
| /** @internal Reset cached env values — test-only. */ | |
| export function _resetEnvCache(): void { | |
| _envSiteUrl = null; | |
| _envAllowedOrigins = null; | |
| } | |
| // Backward-compat alias for existing tests; remove next pass. | |
| export const _resetEnvSiteUrlCache = _resetEnvCache; |
Not blocking, but the next time another env helper is added the pattern starts looking accidental.
|
|
||
| export function getEnvAllowedOrigins(): string[] { | ||
| if (_envAllowedOrigins !== null) return _envAllowedOrigins; | ||
| const raw = typeof process !== "undefined" ? process.env?.EMDASH_ALLOWED_ORIGINS || "" : ""; |
There was a problem hiding this comment.
Minor: process.env?.EMDASH_ALLOWED_ORIGINS || "" makes the empty string and the unset case indistinguishable, which is fine here, but means you can't tell from _envAllowedOrigins alone whether the user explicitly set EMDASH_ALLOWED_ORIGINS= to override an upstream value. Probably not worth changing — just flagging for the future if config + env are ever merged.
More importantly: this function only works when process.env is available. On Cloudflare Workers it always returns []. Without a corresponding EmDashConfig.allowedOrigins field (see top-level review comment), Workers deployments have no way to opt into multi-origin verification. That's the main gap I'd want closed before this is called complete.
| throw new Error(`Invalid origin: expected ${config.origin}, got ${clientData.origin}`); | ||
| // Verify origin against the accepted list | ||
| if (!config.origins.includes(clientData.origin)) { | ||
| throw new Error(`Invalid origin: ${clientData.origin} not in [${config.origins.join(", ")}]`); |
There was a problem hiding this comment.
This function isn't directly covered by the new tests (the PR description acknowledges this). The two implementations have already diverged once — register.ts throws plain Error while authenticate.ts throws a typed PasskeyAuthenticationError with a code. A one-line test against verifyRegistrationResponse rejecting an off-list origin would lock in the parity at near-zero cost and catch future drift. Not blocking.
| EMDASH_ALLOWED_ORIGINS=https://preview.example.com,https://staging.example.com | ||
| ``` | ||
|
|
||
| Each entry must be a valid `http:` or `https:` URL; entries are reduced to their origin (path/query stripped). Each origin must share the registrable parent domain with `siteUrl` -- this is a WebAuthn requirement, not an EmDash one. |
There was a problem hiding this comment.
Worth being explicit that EmDash does not validate the registrable-parent constraint. The browser enforces it (the authenticator only signs assertions for an rpId that's a registrable suffix of the document origin), but if an operator lists https://unrelated.example in EMDASH_ALLOWED_ORIGINS, EmDash won't error — they just won't get any working assertions from there.
| Each entry must be a valid `http:` or `https:` URL; entries are reduced to their origin (path/query stripped). Each origin must share the registrable parent domain with `siteUrl` -- this is a WebAuthn requirement, not an EmDash one. | |
| Each entry must be a valid `http:` or `https:` URL; entries are reduced to their origin (path/query stripped). Each origin must share the registrable parent domain with `siteUrl` -- this is a WebAuthn requirement enforced by the browser, not by EmDash. Listing an unrelated origin will not produce an error here, but the browser will refuse to sign assertions for it. |
|
Review submitted successfully — #800 (review) Posted review with 4 inline comments. Summary of findings:
Security posture is preserved: rpId is still derived from siteUrl, the rpIdHash check still runs after origin verification, and origin normalization (via |
ascorbic
left a comment
There was a problem hiding this comment.
Thanks! Good addition, I just have a few comments
| * Like `getEnvSiteUrl`, uses `process.env` (Vite leaves it untouched at | ||
| * runtime) and is unavailable on Cloudflare Workers, where `env` bindings | ||
| * provide values instead. |
There was a problem hiding this comment.
process.env is available on Workers, because we have nodejs_compat enabled
There was a problem hiding this comment.
Fixed in V2 (f580326) — dropped the wrong claim from getEnvAllowedOrigins's docstring.
Heads-up: the same incorrect claim still sits in the pre-existing getEnvSiteUrl docstring (public-url.ts lines 22-23). Out of scope for this PR per the no-drive-by rule, but happy to fold that one-line fix in if you'd prefer — let me know.
| */ | ||
| let _envAllowedOrigins: string[] | null = null; | ||
|
|
||
| export function getEnvAllowedOrigins(): string[] { |
There was a problem hiding this comment.
Can we do the same as siteUrl and allow passing the value in config too.
There was a problem hiding this comment.
Done in V2 (f580326). Added EmDashConfig.allowedOrigins?: string[] next to siteUrl in integration/runtime.ts. Config and EMDASH_ALLOWED_ORIGINS are merged at runtime (rather than precedence-style like siteUrl) — the rationale: each entry is an independent permission, so list-union is the natural operation. This lets versioned astro.config.mjs declare stable origins while env adds environment-specific extras (e.g. ephemeral PR-preview URLs).
Plumbing follows your earlier architectural note about env vars being runtime: getConfiguredAllowedOrigins(config) (in the new auth/allowed-origins.ts) merges both sources tagged-by-source, then validateAllowedOrigins(siteUrl, tagged) validates the effective set at the runtime chokepoint. Config-side validation also runs at integration init — but only the shape rules (parseable, http/https, no trailing dots, no empty labels), since siteUrl may come from EMDASH_SITE_URL post-build. When config.siteUrl IS present at init, the full validator runs for fail-fast.
| * @param allowedOrigins Optional list of additional accepted origins for verification. | ||
| * Each must share `rpId` with the canonical origin (WebAuthn requirement). | ||
| * Typical use: apex + preview subdomain on the same registrable domain. | ||
| * @throws If `siteUrl` is non-empty but not parseable by `new URL()`. |
There was a problem hiding this comment.
We need to validate this: require siteUrl to be set, and for all allowedOrigins to be subdomains.
There was a problem hiding this comment.
Done in V2 (f580326). Validation lives in auth/allowed-origins.ts as a shared module with two entry points:
validateOriginShape(tagged)— per-entry rules only (parseable URL, http/https, no trailing-dot hostname, no empty labels). Used by integration init whenconfig.siteUrlis absent (since env can supply it post-build).validateAllowedOrigins(siteUrl, tagged)— full validation, including Rule A (allowedOriginsnon-empty ⇒siteUrlrequired), Rule B (each origin must be the same hostname assiteUrlor a subdomain — leading-dot suffix check, sofakeexample.comandexample.com.evil.comboth reject), and rejecting IP-literalsiteUrlor trailing-dotsiteUrlwhenallowedOriginsis non-empty.
Errors are source-attributed (config.allowedOrigins vs EMDASH_ALLOWED_ORIGINS) so operators see where the offending value came from. Coverage: 27 unit tests in tests/unit/auth/allowed-origins.test.ts — including suffix-attacker (example.com.evil.com), prefix-attacker (fakeexample.com), apex-listed-under-subdomain-siteUrl, IP-literal v4/v6, dedupe across sources, and source-attribution-of-the-offending-entry.
Two related judgment calls I held off on, both worth flagging:
http://rejection for non-localhost origins: the browser refuseshttp://WebAuthn outside localhost anyway, so listing one is dead config. Adding ~5 lines of rejection would catch it at startup. Held off because it goes beyond your ask — happy to add if you want it.- Trailing-dot rejection in
siteUrloutside the multi-origin path: same class of mismatch, but pre-existing concern beyond this PR. Could be a separate one-liner inintegration/index.ts's siteUrl validator.
Addresses review feedback on PR emdash-cms#800: - Add EmDashConfig.allowedOrigins config field as a parallel to siteUrl (maintainer ascorbic: "Can we do the same as siteUrl and allow passing the value in config too"). - Validate the merged effective set (config + EMDASH_ALLOWED_ORIGINS) at the runtime chokepoint in 5 verify routes. Validation throws loud, source-attributed errors covering: Rule A (allowedOrigins requires siteUrl), Rule B (each origin must be the same hostname as siteUrl or a subdomain), and shape rules (parseable URL, http/https only, no trailing-dot hostname, no empty labels). Reject IP-literal siteUrl and trailing-dot siteUrl when allowedOrigins is non-empty (multi-origin rpId requires a real domain). - Validate config.allowedOrigins shape at integration init; defer siteUrl-dependent rules to runtime when config.siteUrl is absent (EMDASH_SITE_URL may supply it post-build per existing siteUrl pattern in integration/index.ts). - Throw loud on invalid EMDASH_ALLOWED_ORIGINS entries instead of silent skip; an allowlist that drops typos masks real config errors. - Rename internal _resetEnvSiteUrlCache to _resetEnvCache (it now resets both site-url and allowed-origins caches). - Fix the docstring on getEnvAllowedOrigins that incorrectly claimed process.env was unavailable on Workers (it is, with nodejs_compat). - Add focused register.test.ts off-list-origin test to lock in origin-check parity with authenticate.ts.
V2 pushed (f580326)Addresses all three of your comments. Summary: Architecture changes
Surface additions
Validation rules (all with source-attributed errors)
Test coverage
Local verification
Replied inline to each of your three comments above with where the change landed and the rationale where I deviated (merge vs precedence for |
|
/bonk fix the formatting issue |
There was a problem hiding this comment.
Thanks for addressing the previous review feedback so thoroughly. The V2 architecture (allowed-origins.ts as a pure validation module, config+env merging, source-attributed errors) is clean and the test coverage is comprehensive.
However, there is one blocking issue that prevents this from compiling:
| */ | ||
| allowedOrigins?: string[]; | ||
| * Headers to trust for client IP resolution when running behind a reverse |
There was a problem hiding this comment.
The /** JSDoc opener for trustedProxyHeaders was accidentally deleted during insertion. The line * Headers to trust... is now outside any comment, which is a syntax error. pnpm typecheck fails with ~13 cascading errors starting here.
| */ | |
| allowedOrigins?: string[]; | |
| * Headers to trust for client IP resolution when running behind a reverse | |
| /** | |
| * Headers to trust for client IP resolution when running behind a reverse |
|
Posted a review on PR #800: #800 (review) Finding: One blocking syntax error in Fix is straightforward: restore |
* perf: cache site:* settings prefix scan across requests Site settings change rarely but were re-fetched on every public page load. A globalThis-scoped holder caches the resolved settings until the next site:* write bumps its version, dropping one prefix-scan query per public route. Cross-isolate staleness is bounded by isolate lifetime. * fix(core): invalidate site-settings cache on partial-write failure OptionsRepository.setMany iterates row-by-row without a transaction. If a write fails mid-loop, earlier rows are committed but invalidateSiteSettingsCache() never ran — leaving the globalThis cache pointing at pre-write data while the DB has post-write data on some rows. Wrapping the call in try/finally guarantees invalidation runs whether the write succeeded or threw. Adversarial-review finding from PR #800-class perf branch. * ci: update query-count snapshots * ci: update query-count snapshots --------- Co-authored-by: emdashbot[bot] <emdashbot[bot]@users.noreply.github.com>
What does this PR do?
Lifts the single-origin restriction on passkey verification so deployments serving the same EmDash instance from multiple hostnames (apex + preview/staging subdomains, all sharing one
rpId) can verify passkeys without re-registering on each origin.The strict equality check
clientData.origin !== config.origininregister.tsandauthenticate.tsis replaced with a list-membership check.PasskeyConfig.origin: stringbecomesorigins: string[]. A newEMDASH_ALLOWED_ORIGINSenv var (comma-separated) lets operators declare the additional accepted origins;siteUrlcontinues to controlrpId.Closes #799
Type of change
Checklist
pnpm typecheckpassespnpm lintpasses (12 pre-existing diagnostics on main, none added by this PR)pnpm testpasses for affected packages (@emdash-cms/auth49/49;emdashcore matches main baseline — no regressions added;@emdash-cms/adminfailure is pre-existing on main and unrelated to passkey auth)pnpm formathas been runpnpm locale:extracthas been run (if applicable)AI-generated code disclosure
Implementation notes
Type change.
packages/auth/src/passkey/types.tsnow declaresPasskeyConfig.origins: string[]instead oforigin: string. Per the project's pre-release rules (no backward-compat, no migration paths), the rename is direct.Verification.
register.tsandauthenticate.tsboth replaceclientData.origin !== config.originwith!config.origins.includes(clientData.origin). Same security posture — origin still has to be in an explicit list — just multi-entry instead of single.Helper.
getPasskeyConfig()inpackages/core/src/auth/passkey-config.tsgains a fourth optional argumentallowedOrigins?: string[]. The canonical origin (fromsiteUrlorurl.origin) goes first; allowed origins follow, deduplicated; empty/falsy entries are dropped.Env var.
getEnvAllowedOrigins()inpackages/core/src/api/public-url.tsmirrors the existinggetEnvSiteUrl()pattern: readsprocess.env.EMDASH_ALLOWED_ORIGINS, parses each comma-separated entry throughnew URL(), normalizes toorigin, drops non-http(s)/unparseable entries, caches.Plumbed only where it's read. Only the 5 verify routes (
setup/admin-verify,auth/passkey/verify,auth/passkey/register/verify,auth/signup/complete,auth/invite/complete) passgetEnvAllowedOrigins()intogetPasskeyConfig. The 4 options-generating routes were left alone — they don't readorigins.Tests. Following "TDD for bugs":
packages/auth/src/passkey/authenticate.test.ts— cross-subdomain reject and accept tests (the reject case fails on the old code; the accept case is the fix's reason for existing).register.tsis not separately tested because its origin-check is the identical 3-line block — the auth tests cover the shared semantics.packages/core/tests/unit/auth/passkey-config.test.ts— 5 new tests covering append, canonical-first when nositeUrl, dedupe of repeated canonical, empty-entry skip, emptyallowedOrigins. Existing assertions migrated fromconfig.origintoconfig.origins[0].packages/core/tests/unit/api/public-url.test.ts— 7 new tests coveringgetEnvAllowedOrigins(): unset, comma-list, whitespace trim, origin normalization, protocol filter, unparseable skip, cache invalidation.Docs.
docs/src/content/docs/reference/configuration.mdxgets a new "Multi-origin passkey verification" subsection under Site URL, plus anEMDASH_ALLOWED_ORIGINSrow in the Environment Variables table.Test output