Skip to content

feat: add effect/oauth clients - #11247

Open
danieljvdm wants to merge 19 commits into
mainfrom
feat/unstable-oauth
Open

danieljvdm wants to merge 19 commits into
mainfrom
feat/unstable-oauth

Conversation

@danieljvdm

@danieljvdm danieljvdm commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Add unstable effect/oauth modules for OAuth 2.1 and OpenID Connect clients, built on effect/http, effect/crypto, and effect/jose.

  • OAuth.Client is a service for one authorization server and client registration. It has authorize (PKCE S256 and a fresh state), callback (checks state, RFC 9207 iss, and duplicate parameters, then redeems the code), exchangeCode, refresh, clientCredentials, tokenRequest for extension grants, and RFC 7009 revoke.
  • Oidc.Client has the same methods. Its authorize adds openid, a nonce, and an optional max_age, and its callback always verifies the ID token. It also has verifyIdToken, which takes options instead of a transaction so tokens from refresh or mobile SDKs can be verified, and userInfo. Oidc.layer provides the client as OAuth.Client too.
  • ClientAuth has none, secretBasic, secretPost, and jwt (private_key_jwt or client_secret_jwt). A custom method is a plain function.
  • Dpop signs RFC 9449 proof-of-possession headers (make, generate): OAuth.Client and Oidc.Client bind dpop_jkt, attach dpop+jwt proofs, cache DPoP-Nonce headers, and retry a fresh use_dpop_nonce challenge once; signer.authorize signs HttpClientRequest calls to resource servers.
  • Every failure is an OAuthError with a closed reason union.
const OidcLive = Oidc.layer({
  issuer: "https://issuer.example",
  clientId,
  clientAuth: ClientAuth.secretBasic(clientSecret)
})

// Redirect the user to `url` and keep `transaction` until the callback arrives.
const start = Oidc.Client.use((client) => client.authorize({ redirectUri, scopes: ["profile"] }))

const finish = (callbackUrl: string, transaction: OAuth.Transaction) =>
  Oidc.Client.use((client) => client.callback(transaction, callbackUrl))

Notable decisions

  • Discovery runs on first use and is cached. Pass server to skip it, or call OAuth.discover to fetch and adjust metadata yourself. A failed discovery is retried on the next call.
  • Requests go through the caller's HttpClient, so timeouts and retries are configured there. Token and revocation requests never follow redirects. They set the new HttpClient.FollowRedirectsEnabled reference to false, which HttpClient.followRedirects and every built-in transport respect: fetch (including Bun and Deno layer options) sends redirect: "manual", undici turns off redirect interceptors, and XMLHttpRequest, React Native, and XMLHttpRequest-based fetch polyfills such as React Native's built-in fetch cannot turn redirects off, so they fail before sending. On React Native, fetch fails unless an implementation that supports manual redirects, such as expo/fetch, is provided as FetchHttpClient.Fetch, since the global may wrap React Native's built-in fetch.
  • The issuer and every endpoint must be HTTPS URLs, or HTTP on a loopback host. A transaction records the issuer and client ID that created it (and dpopJkt when DPoP is used), and callback rejects it on any other client or key.
  • For several providers, build one client per provider with make, or use a LayerMap. Two layers that provide OAuth.Client would replace each other.
  • effect/jose is only loaded by Oidc, ClientAuth.jwt, and Dpop. Measured with packages/tools/bundle (gzipped), compared with the previous revision of this PR:
Flow Before After
Authorization code + PKCE (OAuth.layer, discovery, secretBasic) 56.68 KB 33.72 KB
OIDC login (Oidc.layer, discovery, ID token verification) 70.72 KB 56.10 KB
  • Out of scope: callback routes, transaction and token storage, sessions, token caching, PAR, and JARM.

Replaces #9884.

Closes EFF-5007

@changeset-bot

changeset-bot Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c446b11

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

This PR includes changesets to release 43 packages
Name Type
effect Patch
@effect/platform-browser Patch
@effect/platform-node Patch
@effect/ui-native Patch
@effect/opentelemetry Patch
@effect/vitest Patch
@effect/ai-amazon-bedrock Patch
@effect/ai-anthropic Patch
@effect/ai-cloudflare Patch
@effect/ai-openai-compat Patch
@effect/ai-openai Patch
@effect/ai-openrouter Patch
@effect/ai-typesafe Patch
@effect/atom-react Patch
@effect/atom-solid Patch
@effect/atom-vue Patch
@effect/chat-discord Patch
@effect/chat-slack Patch
@effect/chat-teams Patch
@effect/chat-telegram Patch
@effect/chat-whatsapp Patch
@effect/platform-bun Patch
@effect/platform-cloudflare Patch
@effect/platform-deno Patch
@effect/platform-node-shared Patch
@effect/sql-clickhouse Patch
@effect/sql-d1 Patch
@effect/sql-libsql Patch
@effect/sql-mssql Patch
@effect/sql-mysql2 Patch
@effect/sql-pg Patch
@effect/sql-pglite Patch
@effect/sql-sqlite-bun Patch
@effect/sql-sqlite-do Patch
@effect/sql-sqlite-node Patch
@effect/sql-sqlite-react-native Patch
@effect/sql-sqlite-wasm Patch
@effect/docgen Patch
@effect/doctest Patch
@effect/graphql-generator Patch
@effect/openapi-generator Patch
@effect/ui-devtools Patch
@effect/ui-opentui 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

@effect-janitor effect-janitor Bot added the 4.0 label Dec 1, 2026
@eugene1g

eugene1g commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Thanks for splitting this out from #9884 and putting so much care into the protocol details. The overall architecture is in really good shape—lazy scoped discovery, a single serializable OAuth.Transaction designed for Jwt.encrypt, private_key_jwt / client_secret_jwt, client_credentials, typ validation, requestedAt-anchored max_age, constant-time secret comparisons, bounded JSON and response reads, Redacted credentials throughout, single-attempt token exchange, and a structured OAuthError reason union are all strong choices.

We run OAuth 2.1 / OIDC relying parties (including FAPI 2.0-style profiles with PAR, JARM, and private_key_jwt), M2M client_credentials + RFC 9068 resource servers, and an OIDC identity broker in production on Effect 4 and effect/jose under strict security and alerting requirements. Reviewing this PR through that lens turned up several concrete bugs and interoperability traps worth addressing here, along with error-classification refinements and a few forward-looking shape adjustments so high-security extensions can land cleanly without breaking changes.


1. Bugs & Interoperability Traps to Fix in This PR

1.1 OAuth.make captures the entire construction-time context (including Clock and Tracer) and overwrites caller context on exchange / revoke

  • Locations: packages/effect/src/oauth/OAuth.ts (L630, L852, L903)
  • Problem: OAuth.make captures const authContext = yield* Effect.context<R | RR>() and later applies .pipe(Effect.provideContext(authContext)) around ClientAuth.withPreparedRequest(...). In Effect 4, Effect.context() returns the full context map—including runtime references like Clock, Tracer, current span, and Scope—and Effect.provideContext merges it on top of the caller's context, overwriting those references.
  • Why this bites in practice: ClientAuth.privateKeyJwt and ClientAuth.secretJwt read Clock.currentTimeMillis (ClientAuth.ts:322) to stamp iat and exp. If the client layer is constructed under one Clock and invoked under another (a very common pattern in tests mixing TestClock and live clocks, or anywhere Effect.withClock / request-scoped tracing spans / custom loggers are used), client assertions get stamped with the construction-time clock and request tracing detaches. We hit this exact bug internally with effect/jose.
  • Suggested fix: Merge authContext as a fallback so the caller's runtime references (Clock, Tracer, etc.) win while still supplying the captured auth services:
    Effect.updateContext((current) => Context.merge(authContext, current))
    (or capture only the explicit non-reference services needed).

1.2 issuerIdentification defaults to "unsupported" instead of "optional" when discovery omits authorization_response_iss_parameter_supported

  • Locations: packages/effect/src/oauth/OAuth.ts (L728-L740, L1835-L1841)
  • Problem: When metadata.authorization_response_iss_parameter_supported is absent or false, prepareAuthorization sets transaction.issuerIdentification = "unsupported". In validateCallback, "unsupported" rejects any callback carrying an iss parameter, even when iss === expectedIssuer (CallbackRejected({ reason: "unexpectedParameter" })).
  • Why this bites in practice:
    • RFC 9207 §2.4 allows an authorization server to include iss even if discovery omits the optional metadata flag, and IdPs rolling out RFC 9207 can begin sending iss before a long-lived discovery cache refreshes.
    • Anyone using Discovery.makeLocal({ issuer, authorization_endpoint, token_endpoint }) against Google, Okta, Keycloak, Auth0, or any other RFC 9207-compliant IdP without explicitly setting authorization_response_iss_parameter_supported: true will have every callback rejected as unexpectedParameter.
    • When RFC 9207 is not advertised, the safe and interoperable behavior is: accept an absent iss, and if iss is present, verify it matches expectedIssuer exactly.
  • Suggested fix: Default to "optional" when metadata.authorization_response_iss_parameter_supported !== true.

1.3 Oidc.makeVerifierRemote silently drops jwks.filter

  • Location: packages/effect/src/oauth/Oidc.ts (L1270-L1302)
  • Problem: makeVerifierRemote / layerVerifierRemote accept jwks?: Omit<Jwks.RemoteOptions, "url">, which includes Jwks.RemoteOptions["filter"]. TypeScript accepts jwks: { filter: ... } cleanly, but validateRemoteJwksOptions only copies timeToLive, cooldown, timeout, maxResponseBytes, and maxKeys and silently drops filter.
  • Why this bites in practice: Real-world JWKS endpoints occasionally include malformed or non-standard entries (e.g. entries missing kty), where passing filter to Jwks.makeRemote is the documented escape hatch so one bad entry doesn't break the whole key set.
  • Suggested fix: Validate options.filter (Predicate.isFunction) and forward it to Jwks.makeRemote.

1.4 Expired transactions fail as CallbackRejected({ reason: "invalidTransport" })

  • Locations: packages/effect/src/oauth/OAuth.ts (L1810-L1820), packages/effect/src/oauth/OAuthError.ts (L189-L199)
  • Problem: validateCallback maps an expired transaction (nowMillis > expiresAtMillis + clockToleranceMillis) to CallbackRejected({ reason: "invalidTransport" })—the exact same reason used for wrong responseMode, URL fragments, wrong Content-Type, or oversized form_post bodies.
  • Why this bites in practice: A user leaving a login tab open past 10 minutes is a routine UX event ("Your sign-in timed out, please start again"), whereas invalidTransport indicates a broken integration or an attack. Applications need to tell these apart without re-checking transaction.expiresAt manually before calling validateCallback.
  • Suggested fix: Add "expired" to CallbackRejected["reason"] and return callbackRejected("expired") on line 1814.

1.5 Transport.request and Oidc.makeVerifierRemote clobber caller-provided FetchHttpClient.RequestInit

  • Locations: packages/effect/src/oauth/internal/transport.ts (L137-L142), packages/effect/src/oauth/Oidc.ts (L1347-L1355)
  • Problem: Providing FetchHttpClient.RequestInit with a literal { redirect: "manual", credentials: "omit", cache: "no-store" } completely replaces any RequestInit the application configured on its runtime/layer.
  • Why this bites in practice: On Node (undici dispatcher), Bun (tls), and Deno, callers commonly configure mTLS client certificates or corporate proxy agents via FetchHttpClient.RequestInit. Clobbering it breaks mTLS transports—ironically including the allowUnauthenticatedClientCredentials mTLS flow documented in Grant.ts:815-816.
  • Suggested fix: Read Effect.serviceOption(FetchHttpClient.RequestInit) (captured alongside FetchHttpClient.Fetch in Transport.capture as well as in request) and spread it before overriding redirect: "manual", credentials: "omit", and cache: "no-store".

1.6 prompt: "login" does not enforce auth_time freshness (max_age=0), "prompt" is missing from V.reserved, and prompt only accepts a single value

  • Locations: packages/effect/src/oauth/OAuth.ts (L149, L389-L406, L786-L802), packages/effect/src/oauth/internal/validation.ts (L342-L374)
  • Problem:
    1. Freshness bypass without PAR: If an application calls Oidc.authorize({ redirectUri, prompt: "login" }) to force re-authentication for a sensitive action, transaction.maxAge remains undefined. Because the authorization URL travels through the browser (no PAR), a user or attacker can simply strip prompt=login from the redirect URL, skip re-authentication, and complete the login with an old IdP session—Oidc.Verifier will accept the ID token without checking auth_time. In high-security setups, prompt=login must also send max_age=0 and record maxAge: 0 on the transaction so callback verification enforces a fresh auth_time anchored to requestedAt.
    2. Missing from V.reserved: V.reserved blocks max_age and login_hint, but omits prompt, so parameters: { prompt: "..." } bypasses PromptSchema.
    3. Multi-value prompt: OIDC Core §3.1.2.1 defines prompt as a space-delimited list (e.g., "login consent"), whereas PromptSchema currently restricts it to a single literal.
  • Suggested fix: Add "prompt" to V.reserved; consider accepting a list/array of prompt tokens (rejecting "none" combined with other values per OIDC Core §3.1.2.1); and when "login" is requested in OIDC flows, enforce maxAge: 0 (or take the stricter of 0 and any supplied maxAge) so freshness cannot be stripped from the front channel.

1.7 Oidc.authorize defaulting requireAdvertisedPkce to true, and jwks_uri used as an implicit token_endpoint_auth_methods_supported trigger

  • Locations: packages/effect/src/oauth/Oidc.ts (L1696), packages/effect/src/oauth/OAuth.ts (L833-L838, L881-L888)
  • Problem:
    • OAuth.authorize defaults requireAdvertisedPkce to false (still rejecting if code_challenge_methods_supported is present and lacks "S256"), whereas Oidc.authorize defaults it to true. That breaks Discovery.makeLocal unless the caller remembers to include code_challenge_methods_supported: ["S256"], and breaks real OIDC providers that support S256 PKCE while omitting code_challenge_methods_supported from discovery (this has historically tripped people up with Entra and several enterprise IdPs).
    • OAuth.ts:833-834 and L881-L882 use metadata.jwks_uri === undefined ? undefined : ["client_secret_basic"] when token_endpoint_auth_methods_supported is omitted. Using jwks_uri as a proxy for OIDC vs OAuth is undocumented and surprising: a caller using Discovery.makeLocal({ issuer, authorization_endpoint, token_endpoint, jwks_uri }) with ClientAuth.privateKeyJwt, ClientAuth.secretPost, or ClientAuth.none gets InvalidArgument("Client authentication method is not supported by metadata") even though they explicitly configured their own local metadata and client auth method.
  • Suggested fix: Consider defaulting requireAdvertisedPkce consistently to false (keep it as an opt-in strict check, while always rejecting an explicit list that omits "S256"), and clarify or make explicit how omitted token_endpoint_auth_methods_supported behaves (especially for makeLocal vs remote discovery).

1.8 README example silently accepts a missing id_token

  • Location: packages/effect/README.md (L40)
  • Problem: After Oidc.authorize(...), the example writes:
    const identity = tokens.idToken === undefined ? undefined : yield* verifier.verify(...)
    For an OIDC login (openid scope), an absent id_token is a protocol failure, not an optional outcome. People copy README snippets verbatim, so the example should fail explicitly when tokens.idToken === undefined (or use a transaction-bound helper—see §3.3 below).

2. Error Classification & Operational Observability Refinements

In production, the main reason we want a rich, closed error union is incident routing: we want to alert/page on broken client configuration or IdP misconfiguration/outages, and never alert on errors an anonymous attacker can trigger by forging callbacks or tokens. PR #11247 already gets most of this right (AuthorizationDenied separated from EndpointError, EndpointError carrying status + normalized code, TransportFailed separated from InvalidResponse), but three boundaries are still blurred:

2.1 Remote discovery/capability mismatches currently report InvalidArgument (or late TokenVerificationFailed)

  • Locations: OAuth.ts (L526, L717, L720, L837, L885), Oidc.ts (L1185-L1187, L1398, L1974), OAuthError.ts (L55-L56)
  • Problem: InvalidArgument is documented as "a caller-supplied argument, option, or local configuration value rejected before any remote request is dispatched." However, after resolving remote Discovery metadata:
    • Missing authorization_endpoint, revocation_endpoint, userinfo_endpoint, or jwks_uri fails with InvalidArgument.
    • A remote server not advertising S256 PKCE or the client's clientAuthName fails with InvalidArgument.
    • In Oidc.ts:1179-1188, if a caller pins algorithms: ["PS256"] and remote discovery does not advertise "PS256", effectiveAlgorithmsFor silently yields [] and fails later when a token arrives as TokenVerificationFailed({ reason: "algorithm" })—which looks like an attacker sending a bad alg header rather than a discovery/configuration mismatch. Also, when id_token_signing_alg_values_supported is omitted, effectiveAlgorithmsFor allows all 10 asymmetric algorithms rather than defaulting to ["RS256"] per OIDC Core / Discovery conventions (or failing if an explicit pin isn't advertised).
  • Suggested direction: Route remote metadata missing-endpoint and unsupported-capability failures to DiscoveryFailed (or a dedicated capability-mismatch reason) rather than InvalidArgument or TokenVerificationFailed("algorithm"). That keeps InvalidArgument strictly for caller bugs and makes IdP metadata drift immediately distinguishable in logs and alerts.

2.2 TokenVerificationFailed({ reason: "key" }) conflates unknown kid with IdP JWKS faults

  • Location: packages/effect/src/oauth/Oidc.ts (L695-L700)
  • Problem: mapJwsError collapses KeyNotFound, AmbiguousKey, InvalidKey, and CryptoFailed into TokenVerificationFailed({ reason: "key" }).
  • Why this matters operationally:
    • KeyNotFound can be triggered by any forged token carrying a random kid (normal rejection, do not alert).
    • AmbiguousKey (IdP published duplicate keys for the same kid) and InvalidKey (IdP published an unusable/weak key) are issuer misconfigurations / outages that will fail logins until fixed.
    • CryptoFailed is a local runtime/crypto fault.
  • Suggested direction: Either give KeyNotFound its own TokenVerificationFailed reason distinct from key-set/crypto faults, or map AmbiguousKey / InvalidKey (from a remote JWKS) to TransportFailed({ endpoint: "jwks" }) / a distinct issuer-key reason so callers can route alerts cleanly without inspecting error.cause.

2.3 HTTP loopback inconsistency in Oidc.makeVerifierRemote

  • Location: packages/effect/src/oauth/Oidc.ts (L1396-L1400)
  • Problem: Discovery, OAuth.Client, and Oidc.fetchUserInfo all went out of their way to support HTTP loopback (http://localhost, http://127.0.0.1, http://[::1]) when the configured issuer is itself HTTP loopback. Oidc.makeVerifierRemote, however, unconditionally requires V.isHttpsUrl(jwksUri) (matching Jwks.makeRemote's HTTPS-only check). As a result, a full OIDC login against a local HTTP loopback dev server (Keycloak, Dex, Hydra, or local mock IdP) succeeds through discovery, authorize, and token exchange, then fails at ID-token verification.
  • Suggested direction: Either support loopback jwks_uri when metadata.issuer is HTTP loopback (which may need an opt-in on Jwks.makeRemote) or explicitly document in Discovery / Oidc.makeVerifierRemote that local HTTP issuers require layerVerifier + a local Jwks rather than layerVerifierRemote.

2.4 Small ClientAuth interoperability details

  • Locations: packages/effect/src/oauth/ClientAuth.ts (L245-L273, L768-L789)
  • Notes:
    • privateKeyJwt and secretJwt default typ to "client-authentication+jwt" (RFC 10070) and allow overriding to e.g. header: { typ: "JWT" }, which is great. However, there is currently no way to omit typ if an older enterprise IdP rejects unexpected typ values (undefined fails snapshotPlainJson and "" is rejected). Allowing typ: null (or an explicit option) to omit typ would close that interop gap cleanly.
    • secretJwt given a raw string | Redacted<string> re-imports the HMAC key via Jwk.importSecret on every request, and fails only at request time if a provider's client secret is shorter than effect/jose's HMAC key-length floor. Worth documenting (or importing once / exposing the requirement clearly).

3. Shaping the Public Contracts Now for High-Security Extensions

Even keeping the scope of this PR focused on the core OAuth 2.1 / OIDC primitives, a few small schema/API adjustments now will make it much easier to add FAPI 2.0 / enterprise features later without breaking changes:

3.1 Pushed Authorization Requests (PAR — RFC 9126)

PAR is table stakes for confidential high-security clients (FAPI 2.0, enterprise IdPs like Okta, identity brokers): the browser only ever sees client_id and a single-use request_uri, preventing front-channel tampering with nonce, max_age, scope, or response_mode.

  • What to shape in this PR:
    • Add optional pushed_authorization_request_endpoint (validated as V.ProtocolEndpoint and included in endpointsOf so HTTPS/loopback rules apply!) and require_pushed_authorization_requests: Schema.optionalKey(Schema.Boolean) to Discovery.Metadata (Discovery.ts:68-94, L194-L207).
    • Consider adding "par" to the OAuthError endpoint unions (TransportFailed, InvalidResponse, EndpointError) now, or keeping in mind that extending them later is a union-widening change for exhaustive matchers.
    • Even before PAR execution is implemented, if a server explicitly advertises require_pushed_authorization_requests: true, prepareAuthorization should probably fail (with DiscoveryFailed / unsupported capability) rather than silently generating a plain /authorize URL that either gets rejected or silently downgrades.
  • Design lesson for the PAR implementation: Never silently fall back from a failed PAR request to a plain authorization URL, and allow callers to validate/persist transaction storage (e.g., cookie size budgets) before sending the PAR request so unstoreable logins don't waste PAR calls.

3.2 JARM (JWT-Secured Authorization Response Mode — response_mode=jwt / query.jwt) & Transaction Policy Snapshotting

For FAPI 2.0 / strict profiles, signed authorization responses (?response=<JWS>) bind iss, aud, exp, state, and code/error cryptographically before the token endpoint is ever called.

  • What to shape in this PR:
    • Add optional response_modes_supported and authorization_signing_alg_values_supported to Discovery.Metadata.
    • Keep in mind that OAuth.Transaction is the right place to snapshot per-login negotiated security policy (such as responseMode, which you already snapshot, and eventually accepted authorization/ID-token signing algorithms). In multi-replica deployments where a rollout or discovery refresh changes metadata mid-login, completing against the authenticated transaction snapshot prevents both spurious failures and silent downgrades.
    • Note that callbackParamsFromQuery currently hard-forbids "response" (OAuth.ts:1058), which is completely right for plain query callbacks—JARM would naturally live as its own verified decoder (e.g. Oidc.callbackParamsFromJwtResponse / verifyAuthorizationResponse) that checks signature, iss, aud, exp, and state before returning CallbackResult, while plain callbacks continue rejecting "response".

3.3 Transaction-bound ID-token verification (Oidc.verifyTransaction / { transaction } option)

  • Grant.fromTransaction(code, transaction) is a great ergonomic + security win: it eliminates manual parameter forwarding and binds issuer and clientId so a transaction from one client/issuer cannot be redeemed on another.
  • Right now, ID-token verification still requires the caller to manually forward four fields from transaction and tokens:
    verifier.verify(tokens.idToken, {
      nonce: transaction.nonce,
      maxAge: transaction.maxAge,
      requestedAt: transaction.requestedAt,
      accessToken: tokens.accessToken
    })
    Forgetting requestedAt breaks maxAge: 0; forgetting nonce or maxAge silently weakens verification; and checking tokens.idToken === undefined is left to the caller.
  • Offering a companion helper (e.g. Oidc.verifyTransaction(tokens, transaction) or accepting transaction in VerifyOptions) that requires tokens.idToken, forwards nonce, maxAge, requestedAt, and accessToken, and cross-checks transaction.issuer / transaction.clientId against the verifier would make the happy path both shorter and much harder to misuse.

4. Documentation & Follow-Up PRs We'd Be Happy to Help With

4.1 Short production notes in README.md / module JSDoc

Two real-world pitfalls are worth a few sentences of guidance right beside the current README example:

  1. Sealing OAuth.Transaction with Jwt.encrypt: OAuth.ts notes that Transaction is designed to be sealed directly with Jwt.encrypt. It's worth pointing out that OAuth.Transaction intentionally does not include JWT registered claims (iss, aud, exp, iat) or a typ header—callers sealing it into cookies should wrap it with iss, aud (bound to client ID + exact callback URL), exp, iat, and a dedicated typ so a transaction JWE can't be confused with any other encrypted token, use per-login __Host- cookies keyed by state so parallel browser tabs work, and clear cookies + set Cache-Control: no-store / Referrer-Policy: no-referrer on both success and failure responses.
  2. Handling browser disconnects during code exchange: The README rightly says "Token requests are sent once: an uncertain outcome is reported and never retried." In Effect HTTP servers, a browser disconnecting mid-callback interrupts the route fiber, which aborts client.exchange even though the IdP may have already consumed the single-use authorization code. A short note showing how to wrap "redeem + persist session/result" in Effect.uninterruptible (still bounded by the client's timeout and cancelled on server shutdown) helps applications avoid losing spent codes.

4.2 Follow-up PRs after #11247 lands

Once these core protocol modules merge, we'd be glad to contribute follow-up PRs drawing from our production implementations:

  1. PAR (RFC 9126) + JARM (response_mode=jwt / query.jwt) support (including strict capability-pinning options so discovery changes cannot silently downgrade PAR, JARM, or signing algorithms).
  2. M2M Resource Server & Token Cache:
    • An RFC 9068 JWT Access Token (typ: "at+jwt") verifier over Discovery + Jwks.makeRemote (rejecting token-supplied key headers jku/x5u/jwk, enforcing sub/client_id/lifetime/scope checks, Authorization: Bearer parsing, and RFC 6750 WWW-Authenticate response challenges—reusing much of the machinery already here).
    • A cached client_credentials token manager built on OAuth.Client + Grant.clientCredentials + Effect.Cache (canonicalized (resource, scopes) cache key, single-flight coalescing, early renewal margin, never caching failures, and verifying that granted scopes cover all requested scopes).

Happy to help with any of the fixes above or put up PRs for the follow-ups once this lands!

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Bundle Size Analysis

Generated from PR build output; treat the content below as untrusted.

File Name Current Size Previous Size Difference
arbitrary-combinators.ts 40.37 KB 40.37 KB 0.00 KB (0.00%)
basic.ts 6.57 KB 6.57 KB 0.00 KB (0.00%)
batching.ts 11.76 KB 11.76 KB 0.00 KB (0.00%)
brand.ts 7.08 KB 7.08 KB 0.00 KB (0.00%)
cache.ts 12.02 KB 12.02 KB 0.00 KB (0.00%)
config.ts 23.74 KB 23.74 KB 0.00 KB (0.00%)
differ.ts 22.66 KB 22.66 KB 0.00 KB (0.00%)
http-client.ts 28.80 KB 28.60 KB +0.20 KB (+0.69%)
http-router.ts 39.33 KB 39.33 KB 0.00 KB (0.00%)
logger.ts 12.19 KB 12.19 KB 0.00 KB (0.00%)
metric.ts 10.02 KB 10.02 KB 0.00 KB (0.00%)
optic.ts 7.32 KB 7.32 KB 0.00 KB (0.00%)
pubsub.ts 16.77 KB 16.77 KB 0.00 KB (0.00%)
queue.ts 13.58 KB 13.58 KB 0.00 KB (0.00%)
schedule.ts 12.34 KB 12.34 KB 0.00 KB (0.00%)
schema-bigdecimal.ts 14.40 KB 14.40 KB 0.00 KB (0.00%)
schema-binary.ts 43.27 KB 43.27 KB 0.00 KB (0.00%)
schema-class.ts 22.41 KB 22.41 KB 0.00 KB (0.00%)
schema-codegen.ts 33.75 KB 33.75 KB 0.00 KB (0.00%)
schema-fromJsonSchemaDocument.ts 30.86 KB 30.86 KB 0.00 KB (0.00%)
schema-representation-roundtrip.ts 28.60 KB 28.60 KB 0.00 KB (0.00%)
schema-string-transformation.ts 16.14 KB 16.14 KB 0.00 KB (0.00%)
schema-string.ts 12.67 KB 12.67 KB 0.00 KB (0.00%)
schema-template-literal.ts 16.76 KB 16.76 KB 0.00 KB (0.00%)
schema-toArbitrary.ts 39.91 KB 39.91 KB 0.00 KB (0.00%)
schema-toCodecJson.ts 21.55 KB 21.55 KB 0.00 KB (0.00%)
schema-toEquivalence.ts 21.72 KB 21.72 KB 0.00 KB (0.00%)
schema-toFormatter.ts 21.81 KB 21.81 KB 0.00 KB (0.00%)
schema-toJsonSchemaDocument.ts 26.85 KB 26.85 KB 0.00 KB (0.00%)
schema-toRepresentation.ts 21.87 KB 21.87 KB 0.00 KB (0.00%)
schema.ts 21.51 KB 21.51 KB 0.00 KB (0.00%)
stm.ts 14.81 KB 14.81 KB 0.00 KB (0.00%)
stream.ts 10.62 KB 10.62 KB 0.00 KB (0.00%)
supervisor.ts 11.98 KB 11.98 KB 0.00 KB (0.00%)

UI Bundle Size

Vite 8.3.8/Rolldown, production, default Oxc minification, es2023, ES modules, gzip level 9 per chunk. effect 4.1.7, Node v26.12.1. Effect-only client: 27308 B gzip (Δ 0 B vs base).

App Chunks Raw bytes Gzip bytes Added gzip B Δ raw bytes Δ gzip bytes
counter 1 181958 62689 35381 0 0
features 1 191649 66190 38882 0 0
menu 1 296097 100713 73405 0 0

@Benjamin-htr

Benjamin-htr commented Dec 1, 2026 •

Copy link
Copy Markdown

Hey @danieljvdm. Thx for working on this ! Are there any plans to add client-side support for DPoP (RFC 9449)?
This would make it possible to use it with OAuth servers that require DPoP proofs at the token endpoint

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@eugene1g thanks for the comprehensive review! I will look into all your feedback shortly

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@Benjamin-htr will look into it!

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@eugene1g went through the full list. A few of these landed in a8988a2 (1.3 jwks.filter, 1.4 expired callback reason, 1.5 RequestInit merging, removing the jwks_uri auth-method heuristic in 1.7, 2.3 loopback JWKS, and header: { typ: undefined } in 2.4), and I'm pulling in the remaining fixes and shaping changes now.

Wanted to flag the few places where I'm planning to take a slightly different tack in case I'm missing an angle:

  • 1.6 (prompt: "login" implying max_age=0): Agreed on adding "prompt" (and "login_hint") to authorizationReservedParams and rejecting invalid combinations like "none login". On silently forcing max_age=0 and transaction.maxAge = 0 whenever prompt includes "login", I'm hesitant to do that by default because Google's OIDC endpoint omits auth_time unless Session Age Claims (Google Security Bundle + Production verification status) are enabled in Cloud Console. Auto-setting maxAge: 0 would break prompt: "login" out of the box on standard/dev Google projects with TokenVerificationFailed("maxAge") (openid-client and oauth4webapi keep them separate for the same reason). Planning to keep prompt and maxAge orthogonal and call out in the JSDoc on prompt / Oidc.authorize that callers needing cryptographic re-auth proof without PAR should pass { prompt: "login", maxAge: 0 }.
  • 2.1 (defaulting omitted id_token_signing_alg_values_supported to ["RS256"]): Agreed on routing missing metadata endpoints, unsupported PKCE, and empty effectiveAlgorithmsFor overlap to DiscoveryFailed. For the omitted id_token_signing_alg_values_supported case, narrowing to ["RS256"] would make Discovery.makeLocal fail against ES256 or EdDSA JWKS unless callers also remember to list id_token_signing_alg_values_supported (similar to the makeLocal footguns in 1.2 and 1.7). Since Jwks in effect/jose already enforces key-family (kty), curve (crv), and JWK alg matching, keeping defaultAsymmetricAlgorithms when metadata omits the field avoids cross-family confusion while keeping makeLocal ergonomic.
  • 2.2 (AmbiguousKey alerting classification): Agreed on splitting "keyNotFound" out from "key", with one subtlety: in Jwks.ts (selection.kid === undefined || key.kid === selection.kid), any unauthenticated token that omits kid against a healthy IdP with 2+ active rotation keys for the same algorithm triggers JoseError.AmbiguousKey. Mapping all AmbiguousKey errors to TransportFailed or an alertable issuer fault would let an anonymous caller trigger alerts at will. Planning to map KeyNotFound and un-keyed AmbiguousKey (header.kid === undefined) to TokenVerificationFailed({ reason: "keyNotFound" }), leaving "key" for InvalidKey, CryptoFailed, and duplicate-kid AmbiguousKey (header.kid !== undefined).
  • 2.4 (ClientAuth.secretJwt secret import): Jwk.importSecret calls Mac.key, which depends on the Mac service in context, so importing once up front would either make secretJwt effectful (unlike secretBasic / secretPost) or cache a Mac.Key across Mac layers. Since secretJwt already accepts a pre-imported Jwk.SecretKey for callers who want eager startup validation and a single import, I'll keep the constructor pure and document the 32/48/64-byte UTF-8 minimum and Jwk.importSecret path on secretJwt.

Let me know if any of those don't hold up for your setup!

@eugene1g

eugene1g commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

@danieljvdm Reviewed 3e1ad795 and 8d98a134 (along with the earlier a8988a21 refactor)—this is looking really solid, and all four of your calls hold up well for our setup.

No blockers from my side - this is great for us. Happy to help with follow-up PRs (PAR/JARM, RFC 9068 resource server / client_credentials token cache) once this merges!

Non-blocking notes for future evolution

Nothing below needs to touch this PR, just a few lessons from running multi-tenant OIDC federation / an identity broker in production as effect/oauth evolves:

Small RP follow-ups:

  • Exact callback URL check: callbackParamsFromQuery / callbackParamsFromFormPost currently discard the incoming URL's origin and pathname, so validateCallback doesn't verify the callback arrived at transaction.redirectUri. For IdPs without RFC 9207 iss (issuerIdentification: "optional"), RFC 9700 mix-up defense relies on distinct per-issuer callback paths—either checking origin + pathname === transaction.redirectUri when decoded from a full URL, or calling it out in validateCallback docs, is a nice safety net for multi-provider apps with parameterized callback routes.
  • Optional caller-supplied state on OAuth.authorize / Oidc.authorize: Multi-tenant gateways and edge-routed apps often embed a routing prefix or attempt handle in state (<prefix><handle>.<secret>). Supporting optional state alongside Oidc.authorize's optional nonce avoids having to drop down to prepareAuthorization + manual PKCE/nonce generation.
  • StandardClaims & Discovery.Metadata interop polish: Real-world enterprise IdPs occasionally emit null for absent optional claims (e.g. "picture": null, "email": null), which currently fails Oidc.StandardClaims decoding, and MFA-aware apps often look for bounded OIDC Core §2 acr / amr claims alongside authTime. On Discovery.Metadata, token_endpoint_auth_signing_alg_values_supported (RFC 8414 §2) is a natural companion to the PAR/JARM fields already added.
  • Dynamic / multi-tenant IdP usage: The stateless functions and make* constructors added in a8988a21 fit dynamic-tenant / broker architectures really well (caching { Discovery, Client, Verifier } in a bounded ScopedCache keyed by immutable IdP config snapshots rather than static startup layers). That pattern—plus fencing duplicate/retried callbacks behind a lease or state machine so double-clicks and lost redirects don't fail a spent code—would make great docs/examples down the road.

@eugene1g

eugene1g commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

One more question for right after this lands: would you be interested in doing PAR (RFC 9126) + JARM (jwt / query.jwt) as a follow-up PR (or collaborating on one)?

Why PAR + JARM matters

With what's already in #11247—private_key_jwt (RFC 10070), S256 PKCE, nonce, requestedAt-anchored max_age, and exact issuer/audience verification—effect/oauth is already most of the way to the FAPI 2.0 bar (the highest-security OAuth 2.1 / OIDC profile in use today for banking, enterprise identity brokers, and regulated workloads). PAR and JARM are the two remaining relying-party pieces that lock down the front channel on both sides of the browser hop:

  • PAR (RFC 9126 — mandatory in FAPI 2.0 Security Profile): Without PAR, authorization parameters travel unauthenticated through the browser URL, so an attacker (or user) can initiate arbitrary flows or tamper with scope, nonce, max_age, prompt, acr_values, or response_mode on the way to /authorize. With PAR, the confidential client authenticates directly over the back channel (using the same ClientAuth method as /token), and the browser only ever carries client_id and a short-lived, single-use request_uri. That gives request integrity, parameter confidentiality, and client authentication before the browser even reaches /authorize.
  • JARM (JWT-Secured Authorization Response Mode — FAPI 2.0 Message Signing): Plain query/form callbacks return code, error, state, and iss unsigned. JARM signs the entire authorization response (iss, aud, exp, state, code or error) as a JWS under the authorization server's JWKS, giving cryptographic response integrity, issuer/audience binding (even stronger than RFC 9207 iss), and non-repudiation before the token endpoint is ever touched.

Combined with private_key_jwt + S256 PKCE + nonce (and DPoP if that lands later per @Benjamin-htr's note), that gives Effect native support for the strongest standard OAuth/OIDC client posture—and it's the one piece we'd need before strict PAR/JARM-enforcing deployments can move completely off openid-client.


Proposed shape (building directly on #11247)

Since #11247 already added the Discovery.Metadata fields (pushed_authorization_request_endpoint, require_pushed_authorization_requests, response_modes_supported, authorization_signing_alg_values_supported), a follow-up could layer cleanly on top:

1. PAR (RFC 9126)

  • OAuthError: Add "par" to TransportFailed, InvalidResponse, and EndpointError endpoint unions.
  • Stateless primitive: OAuth.pushAuthorizationRequest({ parEndpoint, authorizationEndpoint, clientId, clientAuth, issuer, ...authParams }):
    • Reuses ClientAuth.withPreparedRequest and the same bounded form-encoding + single-attempt transport rules as /token (no retries, no redirects, 201 with { request_uri, expires_in }).
    • Builds the minimal browser redirect url carrying only client_id and request_uri, returning { url, requestUri, expiresIn }.
  • OAuth.Client integration (prepareAuthorization / authorize / Oidc.authorize):
    • Add an option such as pushedAuthorization?: "auto" | "required" | "disabled":
      • Always enforce metadata.require_pushed_authorization_requests === true (refusing "disabled" and failing with DiscoveryFailed if pushed_authorization_request_endpoint is missing).
      • No silent fallback: once PAR is selected (either explicitly or via "auto" when advertised), a failed PAR request fails the authorization rather than silently downgrading to a front-channel URL.
    • Two-phase ergonomics for encrypted-cookie apps: Applications sealing OAuth.Transaction into cookies need to check the cookie size budget before sending a PAR request (otherwise an unstoreable cookie burns a PAR request). Keeping OAuth.pushAuthorizationRequest usable directly (or letting callers prepare the transaction first and push it) handles this cleanly.

2. JARM (jwt / query.jwt, optionally form_post.jwt)

  • ResponseMode & Transaction policy snapshot:
    • Extend OAuth.ResponseMode with "jwt" | "query.jwt" (and optionally "form_post.jwt"), supporting either capability-based selection ("jwt" when advertised, else "query.jwt", else "query") or an explicit pin (failing with DiscoveryFailed if the provider doesn't advertise it).
    • Once a transaction records a JARM responseMode, plain ?code= / ?error= callbacks must be rejected (no unsigned downgrade).
    • Optionally snapshot accepted signing algorithms on OAuth.Transaction (or rely on pinned verifier algorithms) so a restart or discovery metadata change mid-login can't break or quietly downgrade in-flight transactions.
  • Bounded unverified locator + verified JARM decoder:
    • Keep OAuth.callbackParamsFromQuery rejecting "response" for plain query callbacks.
    • Add a bounded (~16 KiB) unverified state-locator helper (e.g. Oidc.unverifiedJwtResponseState) for apps storing per-login cookies keyed by state so parallel browser tabs work—clearly documented as an untrusted lookup key only (never verified state, and malformed tokens never clear unrelated pending logins).
    • Add Oidc.verifyAuthorizationResponse / Verifier.verifyAuthorizationResponse (plus a Jwks-backed stateless variant) that verifies the compact JWS against asymmetric algorithms only (no none/HMAC, intersected with authorization_signing_alg_values_supported), checks iss, aud (clientId), exp, transaction expiry, and constant-time state equality—returning the same CallbackResult / AuthorizationDenied / EndpointError union as OAuth.validateCallback so downstream code stays identical. (In JARM, iss is verified cryptographically inside the JWT regardless of RFC 9207's authorization_response_iss_parameter_supported flag.)

Would love to hear if that direction fits how you're thinking about effect/oauth post-#11247—happy to help review, spec out edge cases, or put up a PR once this is merged!

Replace Discovery, Grant, Pkce and the stateless operations with two
services. OAuth.Client covers authorization with PKCE, callbacks, token
requests and revocation, with lazy cached discovery. Oidc.Client adds ID
token verification and UserInfo, keeping effect/jose out of plain OAuth
bundles. Tests are reduced to the protocol contracts.
@effect-bot effect-bot changed the title feat: add effect/oauth APIs feat: add effect/oauth clients Dec 1, 2026
… harden ID token checks

- Transactions record the issuer and client ID; callback rejects others.
- Issuer and endpoints must be HTTPS (or loopback HTTP), checked for static
  and discovered metadata.
- Add HttpClient.FollowRedirectsEnabled; token and revocation requests
  turn off followRedirects.
- Reject untrusted ID token audiences, multi-audience tokens without azp,
  and future iat/auth_time.
- Malformed callback URLs fail with CallbackRejected.
Fetch sends redirect: "manual" after merging RequestInit, so Bun and Deno
layer options cannot override it. Undici sets maxRedirections: 0 to turn
off redirect interceptors. XMLHttpRequest and React Native cannot turn
redirects off, so they fail before sending. OAuth now only sets the
reference.
@eugene1g

eugene1g commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

I ran the OpenID Foundation Basic RP suite v5.3.5 against 8d98a134 and openid-client 6.9.1. All three configurations finished with 13 passed, 1 skipped, 0 failed, but they skipped different tests:

  • effect/oauth and openid-client with enableNonRepudiationChecks behaved the same on all 14 tests. Both rejected unsigned ID tokens (an allowed skip), and both rejected an invalid RS256 signature before calling UserInfo.
  • Stock openid-client accepted the unsigned ID token and continued to UserInfo in the invalid-signature test. The suite marks the latter as an allowed skip: Basic RP permits relying on TLS for an ID token received directly from the token endpoint.

That’s good evidence for the standard code flow. I also found four cases the suite doesn’t cover.

  1. verifyTransaction should check which client started this login. Suppose a verifier accepts client IDs A and B. A login starts for A, but the ID token names only B as its audience. Today both checks pass independently: A is allowed, and B is allowed. With a matching nonce, verifyTransaction can therefore accept a token issued to the wrong client. For this helper, I’d require aud to include transaction.clientId and, if azp is present, require it to match too. Standalone verify can still accept either client. Transaction check · Audience check

  2. A client can keep using the clock it was built with. I built a client with a test clock fixed at November 2023, then used it for a token exchange under the default live clock. The signed assertion was dated November 2023. Passing the live clock explicitly gave the correct date. The existing test covers an explicit override; the missing case is a caller that doesn’t set Clock at all. Context merge

  3. Reject code_verifier in extra authorization parameters. The generated PKCE flow correctly puts only the challenge in the browser URL. But if an application accidentally includes code_verifier in parameters, the URL builder copies it into that URL too. The verifier belongs only in the token request. Adding it to the reserved parameter list would turn that mistake into an InvalidArgument instead.

  4. Both URL builders should honor mandatory PAR. I configured an issuer with require_pushed_authorization_requests: true and gave both builders the same ordinary authorization request. client.prepareAuthorization refused it; client.authorizationUrl returned a direct /authorize URL with no request_uri. That’s a URL the issuer has already said it won’t accept. I’d apply the existing check to the other builder too. No PAR implementation is needed for that fix.

Oidc.make now hands its transformed HttpClient to OAuth.make, so
transformClient runs once. Both layerConfig functions share one
config reader and the public OAuth.ConfigOptions type. Issuer matching,
success-only caching and UTF-8 encoding live in internal helpers, and
the Redacted unwrap reuses the http internal one.
- FetchHttpClient fails before sending through an XMLHttpRequest-based
  fetch polyfill (React Native's built-in fetch) when redirects are off.
- Oidc callback and refresh require ID tokens issued to the client ID.
- Client assertions use the caller's clock.
- authorize rejects reserved parameters and servers that require PAR.
- Document which transports can send token requests.
…s are off

A wrapper such as expo-router's can hide the whatwg-fetch polyfill flag,
so on React Native the global fetch fails before sending unless
FetchHttpClient.Fetch is provided. A missing fetch is a TransportError.
@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@Benjamin-htr just pushed client-side RFC 9449 DPoP support in 3b4d093!

You can create a signer with Dpop.generate("ES256") (or Dpop.make(privateKey)) and pass dpop on OAuth.make / Oidc.make or per call:

  • authorize sends dpop_jkt and binds it onto the Transaction (checked on callback)
  • token requests attach single-use dpop+jwt proofs, cache DPoP-Nonce headers, and retry a fresh use_dpop_nonce challenge once
  • Oidc.Client.userInfo and signer.authorize(request, accessToken) attach Authorization: DPoP <token> and an ath-bound proof for resource servers

Let me know if you run into anything testing it against your server!

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@eugene1g awesome that you ran the OpenID Basic RP conformance suite against it, thank you!

All four of those cases are now covered on the branch (d9af359 + 3b4d093):

  1. Oidc.Client.callback and refresh require aud to include the client ID (and azp to match when present), while verifyIdToken still accepts any configured audience in audiences.
  2. OAuth.make and Dpop.make explicitly re-bind Clock via Context.get(context, Clock.Clock) so callers on the default live clock don't inherit a TestClock from construction.
  3. code_verifier (and dpop_jkt) are rejected as reserved authorization parameters.
  4. Authorization URL building is consolidated into client.authorize, which enforces require_pushed_authorization_requests.

Also +1 on PAR + JARM as a follow-up once this lands, happy to collaborate on that!

@jpowersdev jpowersdev 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.

Left some notes inline. The first three look like real bugs to me, the rest are smaller things and a couple of questions.

Comment thread packages/effect/src/oauth/OAuth.ts Outdated
const { access_token, token_type, expires_in, refresh_token, id_token, scope, ...extra } = body
const expiresIn = typeof expires_in === "string" ? Number(expires_in) : expires_in
if (
typeof access_token !== "string" || typeof token_type !== "string" || !optionalString(refresh_token) ||

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.

A token response with JSON null for an optional member is rejected as invalid. refresh_token, id_token and scope only accept undefined or a string, expires_in only a number or numeric string, and error: null is treated as an error response.

Some providers do send nulls, e.g. {"access_token":"a","token_type":"Bearer","refresh_token":null,"expires_in":null}. That fails with "The token response is invalid" after the authorization code has already been redeemed, so the user can't retry.

Treating null as absent for these members, and for the optional endpoints in invalidEndpoint, would cover it.

callback: Effect.fnUntraced(function*(transaction, params, callbackOptions) {
const tokens = yield* oauth.callback(transaction, params, callbackOptions)
if (tokens.idToken === undefined) return yield* verificationFailed("The token response has no ID token")
const claims = yield* verify(tokens.idToken, {

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.

callback passes transaction.nonce straight to verify, and verify only compares the nonce when one is given. Since Transaction.nonce is an optional key, a transaction without it skips the check silently.

That can happen with a transaction created by a plain OAuth.make client for the same issuer and client ID, or one whose nonce was lost in storage. The code is redeemed and an ID token with any nonce, or none, is accepted.

Maybe Oidc.callback could reject a transaction with no nonce (transactionMismatch?) before redeeming the code.

Comment thread packages/effect/src/oauth/Dpop.ts Outdated
const digest = Context.get(cryptoContext, Digest.Digest)
const random = Context.get(cryptoContext, SecureRandom.SecureRandom)

const exported = yield* Jwk.exportPrivate(privateKey).pipe(

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.

make gets the public JWK by calling Jwk.exportPrivate on the private key, so it can't work with a non-extractable key. That's the usual way to hold a DPoP key in a browser (a CryptoKey kept in IndexedDB), and it fails here with "Could not export DPoP public key parameters".

Could make accept the public key or JWK as an option, and only fall back to exporting the private key when it isn't given?

Comment thread packages/effect/src/oauth/OAuth.ts Outdated
const callbackParams = (input: CallbackInput): ReadonlyArray<readonly [string, string]> | undefined => {
if (typeof input === "string") {
try {
input = new URL(input, "http://localhost")

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.

Nit: every string is resolved with new URL(input, "http://localhost"), so a raw query string or form_post body like code=abc&state=xyz becomes a path with no search params. The caller gets stateMismatch even though the state matches, and the invalidUrl branch looks unreachable.

Either parse a string with no ? that isn't a URL as URL-encoded parameters, or document that strings must be URLs and reject the rest with invalidUrl.

Effect.flatMap(oauth.server, (server) =>
server.jwks_uri === undefined
? requestFailed("discovery", "The authorization server has no jwks_uri")
: Jwks.makeRemote({ url: server.jwks_uri }).pipe(

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.

Nit: the plain httpClient is passed to Jwks.makeRemote, without FollowRedirectsEnabled set to false as the token requests have. With FetchHttpClient.layer, a 302 from jwks_uri is followed to the other host before makeRemote rejects the response by URL.

Should the key set fetch run with redirects disabled too? If following is intended here, a short comment saying why would help.

Comment thread packages/effect/src/oauth/Oidc.ts Outdated
const request = signer === undefined
? HttpClientRequest.bearerToken(baseRequest, accessToken)
: yield* signer.authorize(baseRequest, accessToken, { nonce })
const response = yield* httpClient.execute(request).pipe(Effect.mapError(httpFailure("userinfo")))

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.

Nit: userInfo calls httpClient.execute(request) without the redirect-disabling wrapper that post uses, so this request still follows redirects while carrying the access token. A 307 gets the request re-sent: same-origin with the Authorization header, cross-origin still with the DPoP proof.

Is that intended? If not, disabling redirects as the token endpoint does would match.

const credentials = yield* clientAuth({ clientId, issuer: metadata.issuer, endpoint: url }).pipe(
// The caller's clock applies even when it is the default, which has no
// entry to override the captured one.
Effect.updateContext((context: Context.Context<never>) =>

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.

Nit: authContext captures the whole context, including Tracer.ParentSpan. The caller's context wins on merge, but when the caller has no parent span the captured one is used. So if the layer is built inside a span and client.refresh later runs on a fiber with no parent, the ClientAuth.jwt signing spans attach to the long-finished layer-build span.

Dpop.make already omits ParentSpan for this reason; the same here would fix it.

Comment thread packages/effect/src/oauth/Oidc.ts Outdated
}).pipe(
Effect.provideService(Jwks.Jwks, jwks),
Effect.provideService(Signature.Signature, signature),
Effect.catch((cause) => verificationFailed("The ID token is invalid", cause))

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.

Nit: verify maps every failure of Jwt.verifyWithKeySet to VerificationFailed "The ID token is invalid", including the key set fetch failing. A 503 from jwks_uri during callback then looks like a forged or bad token rather than a transient outage worth retrying.

Could key-set-unavailable failures map to RequestFailed, as the jwks_uri setup failure already does, with VerificationFailed kept for problems with the token itself?

@eugene1g

eugene1g commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Thanks for fixing the four cases from my earlier comment. Two things stood out in the refactor:

  1. Keep client credentials out of the authorization URL. The reserved parameter list now blocks code_verifier, but no longer blocks client_secret, client_assertion, or client_assertion_type. The client doesn’t add credentials itself, but if a caller includes them in authorize({ parameters }), they end up in the browser URL. Could we restore those three entries before merge?
  2. Let a client require its registered ID-token signing algorithm. The verifier checks signatures, but a client registered for PS256 can’t require PS256. If the issuer also signs with RS256, a valid RS256 signature meets the library’s policy but not that client’s registration. An optional pin shared by callback, refresh, and verifyIdToken would cover that without changing the default.

I also agree with four points @jpowersdev raised inline. I’d prioritize the first two:

  • Missing nonce: Oidc.authorize always creates a nonce. If the stored transaction has none, Oidc.callback should reject it before redeeming the code, rather than silently skipping the nonce check. Standalone verifyIdToken can still make nonce checking optional.
  • JWKS outages: “The issuer’s key endpoint returned 503” and “the token has a bad signature” need different handling. Could KeySetUnavailable surface as RequestFailed, while a bad signature stays VerificationFailed? That lets applications alert on an issuer outage without paging on every invalid token.
  • Non-extractable DPoP keys: A browser can sign with a non-extractable private key, but Dpop.make currently needs to export it just to obtain the public JWK. Letting callers supply the matching public key alongside the private signing key would avoid requiring private-key export.
  • Callback input: A raw form_post body is currently read as a URL path, so the caller gets stateMismatch even when the state is correct. I’d document that string inputs are callback URLs and show how to pass form bodies as URLSearchParams. That gives callers an unambiguous path without making the parser guess.

@eugene1g

eugene1g commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Thanks for the fixes. Two small follow-ups on the latest commit:

  1. Normalize null endpoints before returning discovery metadata. I tried OAuth.discover with "userinfo_endpoint": null. Discovery succeeded, but the result still contained null, even though AuthorizationServer.userinfo_endpoint is typed as string | undefined. The parser returns the original document, so a caller checking !== undefined can still get null. Could we omit null optional endpoints from the result and assert that in the discovery test?

  2. Copy the algorithm list when building the client. Oidc.make copies audiences but keeps algorithms by reference. If the caller later edits its array for a second client, the first client’s verification policy changes too. A shallow copy would keep each client’s pin stable.

This branch has not been deployed

No deployments
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.

5 participants