Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
cc50abe
feat: add effect/oauth APIs
danieljvdm Dec 1, 2026
d4bc5ce
test: use the jose key type in OIDC signing fixtures
danieljvdm Dec 1, 2026
a8988a2
refactor(oauth): address review feedback for protocol, composability,…
danieljvdm Dec 1, 2026
6f2ee5d
fix(oauth): preserve Discovery.Metadata alias in makeLocal declaration
danieljvdm Dec 1, 2026
3e1ad79
fix(oauth): preserve caller context, optional iss default, prompt val…
danieljvdm Dec 1, 2026
8d98a13
feat(oauth): add verifyTransaction, PAR/JARM metadata, and error reas…
danieljvdm Dec 1, 2026
0cf019a
refactor(oauth): service-based OAuth and Oidc clients
effect-bot Dec 1, 2026
bee7ad2
fix(oauth): bind transactions to the client, require HTTPS endpoints,…
effect-bot Dec 1, 2026
03a92af
fix(http): enforce FollowRedirectsEnabled in every transport
effect-bot Dec 1, 2026
855cd09
refactor(oauth): simplify shared client setup
effect-bot Dec 1, 2026
d9af359
fix(oauth): address conformance review findings
effect-bot Dec 1, 2026
810056d
fix(http): only trust an explicit Fetch on React Native when redirect…
effect-bot Dec 1, 2026
5f93bee
test(oauth): drop redundant redirect and discovery assertions
effect-bot Dec 1, 2026
70dfcb7
docs(oauth): clarify client contracts and transport requirements
effect-bot Dec 1, 2026
848fd25
docs(oauth): follow JSDoc section conventions
effect-bot Dec 1, 2026
3b4d093
feat(oauth): add client-side RFC 9449 DPoP support
danieljvdm Dec 2, 2026
47ada42
fix(http): narrow navigator.product access for Deno typecheck
danieljvdm Dec 2, 2026
ca76cda
Merge remote-tracking branch 'origin/main' into feat/unstable-oauth
danieljvdm Dec 2, 2026
c446b11
fix(oauth): address review feedback on callbacks, OIDC, and DPoP
danieljvdm Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/http-follow-redirects-enabled.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"effect": patch
"@effect/platform-browser": patch
"@effect/platform-node": patch
"@effect/ui-native": patch
---

Add `HttpClient.FollowRedirectsEnabled` to disable redirects per request; transports that cannot disable redirects fail before sending. On React Native, explicitly provide a fetch implementation that supports `redirect: "manual"` through `FetchHttpClient.Fetch`.
5 changes: 5 additions & 0 deletions .changeset/unstable-oauth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Add unstable `effect/oauth` modules with OAuth 2.1 and OpenID Connect client services for PKCE authorization, callbacks, token requests, revocation, ID token verification, UserInfo, and DPoP.
47 changes: 47 additions & 0 deletions packages/effect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,50 @@ const program = Effect.gen(function*() {
For encrypted JWTs, use `Jwt.encrypt` and `Jwt.decrypt`. Both `Jwe.decrypt` and `Jwt.decrypt` accept effectful key resolvers for key rotation; resolver headers are unauthenticated and must be used only to select a key.

See [third-party notices](THIRD_PARTY_NOTICES.md) for test attribution.

## OAuth and OpenID Connect

`effect/oauth` provides unstable OAuth 2.1 and OpenID Connect clients, built on `effect/http`, `effect/crypto`, and `effect/jose`. `OAuth.Client` builds authorization requests with PKCE, checks callbacks, and sends token and revocation requests. `Oidc.Client` adds ID token verification and UserInfo. `ClientAuth` authenticates the client, `Dpop` signs RFC 9449 sender-constrained token proofs, and every failure is an `OAuthError`.

Applications own callback routes, transaction and token storage, and sessions. Server metadata is discovered from the `issuer` on first use, or passed as `server`. For several providers, build one client per provider with `OAuth.make` or `Oidc.make`.

```ts
import { Layer, Redacted } from "effect"
import { Digest, SecureRandom, Signature } from "effect/crypto"
import { FetchHttpClient } from "effect/http"
import { ClientAuth, type OAuth, Oidc } from "effect/oauth"

const OidcLive = Oidc.layer({
issuer: "https://issuer.example",
clientId: "client-id",
clientAuth: ClientAuth.secretBasic(Redacted.make("client-secret"))
}).pipe(
Layer.provide(
Layer.mergeAll(FetchHttpClient.layer, Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
Layer.provideMerge(SecureRandom.layerWebCrypto)
)
)
)

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

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

Token, refresh, and revocation requests never follow redirects, so they need an `HttpClient` that can turn redirects off. This includes public clients using `ClientAuth.none`, because the code exchange sends the PKCE verifier. Fetch, undici, and `node:http` can. `BrowserHttpClient.layerXMLHttpRequest`, `NativeHttpClient.layer`, and React Native's built-in fetch cannot, so these requests fail before sending. Building the authorization URL does not require disabling redirects.

On React Native, requests with redirects disabled reject the global fetch, which may wrap the built-in implementation. Provide a fetch that supports `redirect: "manual"`, such as `expo/fetch`, explicitly. Use this `HttpLive` layer in place of `FetchHttpClient.layer` in the example above:

```ts
import { Layer } from "effect"
import { FetchHttpClient } from "effect/http"
import { fetch } from "expo/fetch"

const HttpLive = FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch as typeof globalThis.fetch))
)
```
4 changes: 4 additions & 0 deletions packages/effect/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"./http-api": "./src/http-api/index.ts",
"./jose": "./src/jose/index.ts",
"./net": "./src/net/index.ts",
"./oauth": "./src/oauth/index.ts",
"./observability": "./src/observability/index.ts",
"./persistence": "./src/persistence/index.ts",
"./process": "./src/process/index.ts",
Expand Down Expand Up @@ -90,6 +91,7 @@
"./http/MultipartParser/internal/*": null,
"./http-api/internal/*": null,
"./jose/internal/*": null,
"./oauth/internal/*": null,
"./observability/internal/*": null,
"./protobuf/internal/*": null,
"./rpc/internal/*": null,
Expand Down Expand Up @@ -141,6 +143,7 @@
"./http-api": "./dist/http-api/index.js",
"./jose": "./dist/jose/index.js",
"./net": "./dist/net/index.js",
"./oauth": "./dist/oauth/index.js",
"./observability": "./dist/observability/index.js",
"./persistence": "./dist/persistence/index.js",
"./process": "./dist/process/index.js",
Expand Down Expand Up @@ -179,6 +182,7 @@
"./http/MultipartParser/internal/*": null,
"./http-api/internal/*": null,
"./jose/internal/*": null,
"./oauth/internal/*": null,
"./observability/internal/*": null,
"./protobuf/internal/*": null,
"./rpc/internal/*": null,
Expand Down
32 changes: 32 additions & 0 deletions packages/effect/src/http/FetchHttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ import * as HttpClientResponse from "./HttpClientResponse.ts"
* Defaults to `globalThis.fetch`. When not explicitly provided in context,
* `FetchHttpClient` uses the current `globalThis.fetch` on each request.
*
* **Gotchas**
*
* On React Native, a request with `HttpClient.FollowRedirectsEnabled` set to
* `false` fails unless `Fetch` is provided explicitly, because the global
* fetch may be React Native's built-in one, which ignores
* `redirect: "manual"`. Provide one that supports it, such as `expo/fetch`.
*
* @stability unstable
* @category services
* @since 4.0.0
Expand Down Expand Up @@ -106,6 +113,22 @@ const detectStreamBodySupport = () => {
}
}

// The `whatwg-fetch` polyfill, React Native's built-in fetch, is built on
// XMLHttpRequest and ignores `redirect: "manual"`. Wrappers can hide its
// `polyfill` flag, so on React Native only an explicit `Fetch` is trusted.
const manualRedirectUnsupported = (fetch: typeof globalThis.fetch | undefined): string | undefined => {
const impl = fetch ?? globalThis.fetch
if (typeof impl !== "function") return "fetch is not available"
if (
(impl as any).polyfill === true ||
(fetch === undefined &&
typeof navigator !== "undefined" &&
(navigator as { readonly product?: unknown }).product === "ReactNative")
) {
return "This fetch cannot send a request without following redirects; provide one that supports redirect: \"manual\" with FetchHttpClient.Fetch"
}
}

const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fiber) => {
if (request.headers.upgrade !== undefined) {
return Effect.fail(
Expand All @@ -118,6 +141,14 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe
)
}
const fetch = Context.getOrUndefined(fiber.context, Fetch)
if (!fiber.getRef(HttpClient.FollowRedirectsEnabled)) {
const description = manualRedirectUnsupported(fetch)
if (description !== undefined) {
return Effect.fail(
new HttpClientError.HttpClientError({ reason: new HttpClientError.TransportError({ request, description }) })
)
}
}
const options: globalThis.RequestInit = Context.getOrUndefined(fiber.context, RequestInit) ?? {}
let headers = options.headers
? Headers.merge(Headers.fromInput(options.headers as Headers.Input), request.headers)
Expand All @@ -139,6 +170,7 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe
duplex: typeof ReadableStream !== "undefined" && body instanceof ReadableStream ? "half" : undefined,
signal: uploadController ? AbortSignal.any([signal, uploadController.signal]) : signal
}
if (!fiber.getRef(HttpClient.FollowRedirectsEnabled)) init.redirect = "manual"
return fetch ? fetch(url, init) : globalThis.fetch(url, init)
},
catch: (cause) =>
Expand Down
33 changes: 32 additions & 1 deletion packages/effect/src/http/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2119,6 +2119,33 @@ export const withScope = <E, R>(
): HttpClient.With<E, R | Scope.Scope> =>
transformResponse(self, Effect.provideServiceEffect(RequestScope, Effect.scope))

/**
* Controls whether a request may follow redirects. Defaults to `true`.
*
* **When to use**
*
* Use to prevent redirecting a request that carries credentials by setting it
* to `false`.
*
* **Details**
*
* When it is `false`, {@link followRedirects} returns the redirect response,
* fetch-based clients override `RequestInit.redirect` with `"manual"`, and
* the undici client turns off redirect interceptors.
* Clients that cannot turn redirects off, such as `XMLHttpRequest` and fetch
* polyfills built on it, fail with a `TransportError` before sending the
* request. On React Native, fetch-based clients also fail unless
* `FetchHttpClient.Fetch` explicitly supplies an implementation that supports
* `redirect: "manual"`, such as `expo/fetch`.
*
* @stability unstable
* @category redirects
* @since 4.2.0
*/
export const FollowRedirectsEnabled = Context.Reference<boolean>("effect/http/HttpClient/FollowRedirectsEnabled", {
defaultValue: constTrue
})

/**
* Enables following HTTP redirects up to a specified number of times.
*
Expand All @@ -2127,6 +2154,8 @@ export const withScope = <E, R>(
* Follows `3xx` responses that include a `Location` header, up to
* `maxRedirects` (default `10`) times. When the limit is reached or the
* `Location` header is not a valid URL, the last redirect response is returned.
* Setting {@link FollowRedirectsEnabled} to `false` returns the first response
* without following redirects.
*
* **Gotchas**
*
Expand Down Expand Up @@ -2225,7 +2254,9 @@ export const followRedirects: {
}
)
})
return loop(request, 0)
return Effect.withFiber((fiber) =>
fiber.getRef(FollowRedirectsEnabled) ? loop(request, 0) : self.postprocess(request)
)
},
self.preprocess
))
Expand Down
155 changes: 155 additions & 0 deletions packages/effect/src/oauth/ClientAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/**
* Client authentication for requests to the token and revocation endpoints.
*
* A {@link ClientAuth} is a function from the request to the headers and form
* parameters that authenticate the client. Write one to support a method that
* is not built in.
*
* @stability unstable
* @since 4.2.0
*/
import * as Clock from "../Clock.ts"
import * as SecureRandom from "../crypto/SecureRandom.ts"
import * as Duration from "../Duration.ts"
import * as Effect from "../Effect.ts"
import * as Base64 from "../encoding/Base64.ts"
import * as Base64Url from "../encoding/Base64Url.ts"
import { unwrap } from "../http/internal/urlParams.ts"
import type * as Jwk from "../jose/Jwk.ts"
import type * as Jws from "../jose/Jws.ts"
import * as Jwt from "../jose/Jwt.ts"
import * as Redacted from "../Redacted.ts"
import * as OAuthError from "./OAuthError.ts"

/**
* The request a client authentication method is applied to.
*
* @stability unstable
* @category models
* @since 4.2.0
*/
export interface Request {
readonly clientId: string
readonly issuer: string
readonly endpoint: string
}

/**
* Headers and form parameters added to the request.
*
* @stability unstable
* @category models
* @since 4.2.0
*/
export interface Credentials {
readonly headers?: Readonly<Record<string, string>> | undefined
readonly params?: Readonly<Record<string, string | Redacted.Redacted<string>>> | undefined
}

/**
* A client authentication method.
*
* **Example** (Sending a custom header)
*
* ```ts
* import { Effect } from "effect"
* import type { ClientAuth } from "effect/oauth"
*
* const apiKey = (key: string): ClientAuth.ClientAuth => (request) =>
* Effect.succeed({ headers: { "x-api-key": key }, params: { client_id: request.clientId } })
* ```
*
* @stability unstable
* @category models
* @since 4.2.0
*/
export type ClientAuth<R = never> = (request: Request) => Effect.Effect<Credentials, OAuthError.OAuthError, R>

// RFC 6749 section 2.3.1: form-encode each part before joining them.
const formEncode = (value: string): string => new URLSearchParams([["", value]]).toString().slice(1)

/**
* Sends only `client_id`, for public clients.
*
* @stability unstable
* @category constructors
* @since 4.2.0
*/
export const none: ClientAuth = (request) => Effect.succeed({ params: { client_id: request.clientId } })

/**
* `client_secret_basic`: sends the client ID and secret in an HTTP Basic
* `Authorization` header.
*
* @stability unstable
* @category constructors
* @since 4.2.0
*/
export const secretBasic = (secret: string | Redacted.Redacted<string>): ClientAuth => (request) =>
Effect.sync(() => ({
headers: {
authorization: `Basic ${Base64.encode(`${formEncode(request.clientId)}:${formEncode(unwrap(secret))}`)}`
}
}))

/**
* `client_secret_post`: sends the client ID and secret as form parameters.
*
* @stability unstable
* @category constructors
* @since 4.2.0
*/
export const secretPost = (secret: string | Redacted.Redacted<string>): ClientAuth => (request) =>
Effect.succeed({
params: { client_id: request.clientId, client_secret: Redacted.isRedacted(secret) ? secret : Redacted.make(secret) }
})

/**
* Signs a JWT client assertion: `private_key_jwt` with a private key, or
* `client_secret_jwt` with an HMAC key.
*
* **Details**
*
* The assertion's `iss` and `sub` are the client ID and its `aud` defaults
* to the issuer. It expires after `lifetime`, 60 seconds by default, and
* carries a random `jti`.
*
* @stability unstable
* @category constructors
* @since 4.2.0
*/
export const jwt = <K extends Jwk.SigningKey>(key: K, options?: {
readonly audience?: string | undefined
readonly lifetime?: Duration.Input | undefined
readonly header?: Jws.Header | undefined
}): ClientAuth<Jws.KeyRequirements<K> | SecureRandom.SecureRandom> =>
(request) =>
Effect.gen(function*() {
const jti = Base64Url.encode(yield* SecureRandom.SecureRandom.use((random) => random.randomBytes(16)))
const now = yield* Clock.currentTimeMillis
const iat = Math.floor(now / 1000)
const assertion = yield* Jwt.sign(
Jwt.RegisteredClaims,
{
iss: request.clientId,
sub: request.clientId,
aud: options?.audience ?? request.issuer,
jti,
iat,
exp: iat + Math.ceil(Duration.toSeconds(options?.lifetime ?? "60 seconds"))
},
key,
options?.header
)
return {
params: {
client_id: request.clientId,
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: assertion
}
}
}).pipe(Effect.mapError((cause) =>
new OAuthError.OAuthError({
reason: new OAuthError.ClientAuthFailed({ description: "Could not sign the client assertion", cause })
})
))
Loading