Skip to content

feat: add effect/jose APIs - #9883

Merged
tim-smart merged 47 commits into
mainfrom
feat/unstable-jose
Oct 30, 2026
Merged

tim-smart merged 47 commits into
mainfrom
feat/unstable-jose

Conversation

@danieljvdm

@danieljvdm danieljvdm commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Add effect/jose to the core package with algorithm-bound keys, compact JWS/JWE, schema-typed signed and encrypted JWTs, and local or scoped remote JWKS resolution. Effectful decryption key resolvers support rotation, extension headers are preserved for custom key selection, and decryption returns the selected key. Modules also have direct entrypoints such as effect/jose/Jwt.

@changeset-bot

changeset-bot Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 459da6b

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

This PR includes changesets to release 33 packages
Name Type
effect Patch
@effect/opentelemetry Patch
@effect/vitest 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/platform-browser Patch
@effect/platform-bun Patch
@effect/platform-deno Patch
@effect/platform-node-shared Patch
@effect/platform-node 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

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

@danieljvdm
danieljvdm added this pull request to stack #9885 October 24, 2026 06:37
@danieljvdm danieljvdm changed the title feat/unstable jose feat(auth): add unstable JOSE APIs Oct 24, 2026
@danieljvdm
danieljvdm marked this pull request as ready for review October 24, 2026 06:38
@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@effect-bot review

@github-actions

github-actions Bot commented Oct 24, 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 39.39 KB 39.39 KB 0.00 KB (0.00%)
basic.ts 7.23 KB 7.23 KB 0.00 KB (0.00%)
batching.ts 11.05 KB 11.05 KB 0.00 KB (0.00%)
brand.ts 6.85 KB 6.85 KB 0.00 KB (0.00%)
cache.ts 11.54 KB 11.54 KB 0.00 KB (0.00%)
config.ts 22.82 KB 22.82 KB 0.00 KB (0.00%)
differ.ts 21.97 KB 21.97 KB 0.00 KB (0.00%)
http-client.ts 26.92 KB 26.92 KB 0.00 KB (0.00%)
http-router.ts 36.89 KB 36.89 KB 0.00 KB (0.00%)
logger.ts 12.01 KB 12.01 KB 0.00 KB (0.00%)
metric.ts 9.47 KB 9.47 KB 0.00 KB (0.00%)
optic.ts 7.07 KB 7.07 KB 0.00 KB (0.00%)
pubsub.ts 16.03 KB 16.03 KB 0.00 KB (0.00%)
queue.ts 12.82 KB 12.82 KB 0.00 KB (0.00%)
schedule.ts 11.80 KB 11.80 KB 0.00 KB (0.00%)
schema-bigdecimal.ts 14.07 KB 14.07 KB 0.00 KB (0.00%)
schema-binary.ts 41.22 KB 41.22 KB 0.00 KB (0.00%)
schema-class.ts 21.71 KB 21.71 KB 0.00 KB (0.00%)
schema-fromJsonSchemaDocument.ts 29.56 KB 29.56 KB 0.00 KB (0.00%)
schema-representation-roundtrip.ts 27.97 KB 27.97 KB 0.00 KB (0.00%)
schema-string-transformation.ts 15.32 KB 15.32 KB 0.00 KB (0.00%)
schema-string.ts 12.31 KB 12.31 KB 0.00 KB (0.00%)
schema-template-literal.ts 16.25 KB 16.25 KB 0.00 KB (0.00%)
schema-toArbitrary.ts 38.91 KB 38.91 KB 0.00 KB (0.00%)
schema-toCodeDocument.ts 26.13 KB 26.13 KB 0.00 KB (0.00%)
schema-toCodecJson.ts 20.88 KB 20.88 KB 0.00 KB (0.00%)
schema-toEquivalence.ts 21.02 KB 21.02 KB 0.00 KB (0.00%)
schema-toFormatter.ts 21.12 KB 21.12 KB 0.00 KB (0.00%)
schema-toJsonSchemaDocument.ts 26.14 KB 26.14 KB 0.00 KB (0.00%)
schema-toRepresentation.ts 21.21 KB 21.21 KB 0.00 KB (0.00%)
schema.ts 20.80 KB 20.80 KB 0.00 KB (0.00%)
stm.ts 14.20 KB 14.20 KB 0.00 KB (0.00%)
stream.ts 10.38 KB 10.38 KB 0.00 KB (0.00%)

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

/effect-bot

@danieljvdm danieljvdm changed the title feat(auth): add unstable JOSE APIs feat: add effect/jose APIs Oct 24, 2026
@fubhy

fubhy commented Oct 24, 2026

Copy link
Copy Markdown
Member

@effect-bot

@eugene1g

Copy link
Copy Markdown
Contributor

Thanks for this. We maintain a substantial in-house OAuth 2 / OpenID Connect stack built on Effect and on jose (panva). It includes an OIDC provider that issues ID tokens, signed authorization responses (JARM) and RFC 9068 access tokens, plus relying-party and resource-server libraries. We're following this PR closely as a likely path off jose.

1. Bug: Jwks.layerRemote refuses to refetch an expired key set during the cooldown

refresh applies cooldown to every fetch. After a successful fetch, once timeToLive has passed, the next lookup goes through refresh(now). If the last fetch is more recent than cooldown, it returns undefined, and the lookup fails with KeySetUnavailable("The key set is cooling down after a failed fetch"), although no fetch failed. With timeToLive < cooldown, every verification fails from the moment the set expires until cooldown has passed since the last fetch, and this repeats every cycle. The defaults (10 minutes / 30 seconds) never hit it, but the options accept that combination without an error.

Panva applies the cooldown only when reloading for an unknown key. Once cacheMaxAge passes, it reloads without condition. In jose@6.2.13's dist/webapi/jwks/remote.js:

(!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
// ...
if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))
  return await reload(), local(protectedHeader, token);

The fix below does the same for expiry and unknown keys. It also keeps this PR's cooldown after a failed fetch, which panva does not have:

       let lastAttempt = -Infinity
+      let lastFailed = false
@@
-            if (now - lastAttempt < cooldown) return Effect.succeed(undefined)
+            // The cooldown bounds unknown-kid probes and retries after a failure. An
+            // expired set that was fetched successfully is refetched at once.
+            if ((stale !== undefined || lastFailed) && now - lastAttempt < cooldown) return Effect.succeed(undefined)
@@
                   pending = undefined
+                  lastFailed = Exit.isFailure(exit)
                   if (Exit.isSuccess(exit)) cache = exit.value

Regression test for test/jose/Jwks.test.ts. On 56f1503 it fails with the "cooling down" error; with the fix it passes:

it.effect("refetches an expired key set at once when timeToLive is shorter than cooldown", () =>
  Effect.gen(function*() {
    let requests = 0
    let status = 500
    const context = yield* Layer.build(
      Jwks.layerRemote({ url, timeToLive: "10 seconds", cooldown: "30 seconds" }).pipe(
        Layer.provide(serve(() =>
          Effect.sync(() => {
            requests++
            return new Response(JSON.stringify({ keys: [ec] }), { status })
          })
        ))
      )
    )
    const keys = Context.get(context, Jwks.Jwks)

    // A failed fetch still cools down.
    assertReason(yield* keys.resolve({ algorithm: "ES256", kid: "ec" }).pipe(Effect.flip), "KeySetUnavailable")
    status = 200
    yield* TestClock.adjust("5 seconds")
    assertReason(yield* keys.resolve({ algorithm: "ES256", kid: "ec" }).pipe(Effect.flip), "KeySetUnavailable")
    assert.strictEqual(requests, 1)
    yield* TestClock.adjust("30 seconds")
    yield* keys.resolve({ algorithm: "ES256", kid: "ec" })
    assert.strictEqual(requests, 2)

    // A set that expired after a successful fetch is refetched without waiting for the cooldown.
    yield* TestClock.adjust("15 seconds")
    assert.strictEqual((yield* keys.resolve({ algorithm: "ES256", kid: "ec" })).kid, "ec")
    assert.strictEqual(requests, 3)

    // Unknown kids still refetch at most once per cooldown.
    assertReason(yield* keys.resolve({ algorithm: "ES256", kid: "unknown" }).pipe(Effect.flip), "KeyNotFound")
    assert.strictEqual(requests, 3)
  }))

With the change, test/jose passes, tsc -b passes for packages/effect and tsconfig.tests.json, and oxlint and dprint check are clean on both files.

2. Gap: Jwe.decrypt takes only one key, so the encryption key cannot be rotated

Jws.verifyWithKeySet can pick a key from a key set, but Jwe.decrypt accepts only a single SecretKey<"dir">. Rotating a dir key means decrypting with whichever key the token's kid names, so callers must parse the protected header themselves before they can choose a key. Panva's compactDecrypt and jwtDecrypt take a key or a getKey(protectedHeader, token) resolver, and return the resolved key in the result.

Suggestion: an overload decrypt(token, (header: ProtectedHeader) => Effect<SecretKey<"dir">, E, R>), with the header decoded and checked against the schema before the resolver runs.

3. Gap: no encrypted JWT

Jwe encrypts and decrypts bytes, while claim validation exists only in Jwt.verify. Encrypted JWTs carrying iss, aud, exp, iat and typ are common for sealed cookies, login state and session tokens. Today each caller has to reimplement checkClaims, including the typ check that RFC 8725 §3.11 recommends. Panva has EncryptJWT and jwtDecrypt, and jwtDecrypt takes the same claim options as jwtVerify.

Suggestion: Jwt.encrypt(schema, claims, key, header?) and Jwt.decrypt(schema, token, keyOrResolver, options) that reuse readPolicy and checkClaims, or else export the claim validation so callers can build them.

4. Gap: the remote key set can only be provided as a layer with a fixed URL

The only constructor is layerRemote({ url }). An OIDC relying party normally learns jwks_uri from discovery at runtime, often for several issuers, so it cannot know the URL when the layer is built. #9884 shows this: its Oidc.ts calls Layer.build(Jwks.layerRemote({ url: jwksUri, ... })) internally to get a Jwks service for the discovered jwks_uri. Panva's createRemoteJWKSet(url, options) is an ordinary value that can be created anywhere.

Suggestion: export makeRemote(options): Effect<Jwks["Service"], JoseError, HttpClient | Scope> and define layerRemote with it.

Smaller point

  • Jws.verify and Jwt.verify require Mac | Signature even when the key is a PublicKey. Deriving the requirement from the key type, or offering a public-key overload, would keep Mac out of verify-only setups.

Happy to help test or contribute further as this moves forward.

@eugene1g

Copy link
Copy Markdown
Contributor

Thanks for the quick turnaround. We checked 5cf106c against our points:

  • Jwks cooldown: fixed. Our regression test passes, and the updated cooldown docs now describe the behaviour correctly.
  • Jwks.makeRemote: this covers our case. We built separate services for URLs discovered at runtime within one scope; each one fetched its own URL, and lookups failed with KeySetUnavailable once the scope closed.
  • Key-derived requirements: Jws.KeyRequirements<K> does what we wanted. Verifying with only a public key now needs only Signature.

The jose tests and tsc -b tsconfig.tests.json pass on our side.

Two points from our earlier comment are still open, and they're what keep us on panva for encrypted state:

  1. A key resolver for Jwe.decrypt. Rotating a dir key means choosing the key by the token's kid. Panva's compactDecrypt and jwtDecrypt accept a getKey(protectedHeader, token) resolver for this.
  2. Encrypted JWTs with claim checks. Today callers must reimplement checkClaims (including the typ check from RFC 8725 §3.11) on top of Jwe. Panva has EncryptJWT and jwtDecrypt, and jwtDecrypt takes the same claim options as jwtVerify.

Are these in scope for this PR, or better as a follow-up?

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

@eugene1g Thanks for all the detailed feedback, adding all of this stuff.

@eugene1g

Copy link
Copy Markdown
Contributor

Thanks @danieljvdm, 6928948 covers everything I raised. I checked Jwe.decrypt with a kid-based keyring resolver (an unknown kid returns the resolver's own error), and Jwt.decrypt with typ, iss and exp checks.

One optional idea, for consistency with Jws.verifyWithKeySet: Jwe.decrypt and Jwt.decrypt could return the key the resolver chose, as panva's ResolvedKey does.

Nothing else here! I have lots of feedback for the other OAuth PRs if they are expected to go ahead (after a clean rebase)

@danieljvdm

Copy link
Copy Markdown
Collaborator Author

Thanks @danieljvdm, 6928948 covers everything I raised. I checked Jwe.decrypt with a kid-based keyring resolver (an unknown kid returns the resolver's own error), and Jwt.decrypt with typ, iss and exp checks.

One optional idea, for consistency with Jws.verifyWithKeySet: Jwe.decrypt and Jwt.decrypt could return the key the resolver chose, as panva's ResolvedKey does.

Nothing else here! I have lots of feedback for the other OAuth PRs if they are expected to go ahead (after a clean rebase)

Yeah oauth is definitely on the backburner for now, I need to do a lot more work on it but will ping you when I think it's ready for your feedback. Once again, appreciate it!

@eugene1g

Copy link
Copy Markdown
Contributor

@danieljvdm One more pass against the rebased head (3994ca7) - mostly Quality of Life stuff, with a note on what jose does in each case since they're done a great job thinking about this problem.

From my bots to yours:

1. Expose (and allow setting) header parameters outside the typed set

decodeHeader decodes through Jws.ProtectedHeader / Jwe.ProtectedHeader, and Schema.Struct drops anything it doesn't name, so jwk, jku, x5u, x5c, crit, … are gone by the time a caller or a Jwks resolver sees the header. encodeHeader likewise only writes kid/typ/cty. Two concrete things that become impossible: DPoP (RFC 9449 requires a jwk header), and a resource server that wants to reject tokens carrying jku/x5u/jwk - it can't see the header fields to reject them.

For comparison, jose keeps the whole parsed object: JWSHeaderParameters has jku/jwk/x5u/x5c/x5t/crit plus [propName: string]: unknown, protectedHeader in every result is the full object, the resolver gets it (getKey(protectedHeader, token)), and setProtectedHeader accepts arbitrary params when signing. EmbeddedJWK is a built-in resolver over the jwk header, which is how DPoP works there. crit is validated (validateCrit): unrecognised critical params are rejected, b64 is the one recognised JWS extension, callers can opt in to more.

Suggestion: carry the authenticated header through (Schema.StructWithRest with Record(String, Json), or a raw header field alongside the typed one) and accept extra params in sign/encrypt. Even without crit support, rejecting unknown crit entries would be worth doing so callers aren't silently accepting tokens with critical extensions.

2. verifyWithKeySet should check the resolved key's algorithm against the header

Jws.verifyWithKeySet checks header alg against algorithms, resolves a key, then verifies with key.algorithm — it never checks key.algorithm === alg. The built-in makeLocal/makeRemote import keys for the selected algorithm so they're safe; a custom Jwks that ignores selection.algorithm is not. A probe from a second-opinion review pass confirmed it: RS256 key + alg: PS256 header + algorithms: ["PS256"] is accepted via verifyWithKeySet while plain Jws.verify rejects it. Not a forgery (the header is in the signing input), but the allowlist stops meaning what callers think it means, and Jwt.verifyWithKeySet inherits it.

For comparison, jose treats the header alg as authoritative and then runs the resolved key through prepareKey(entry, key, 'verify'): checkCryptoKey checks algorithm.name, hash, namedCurve and length against the header alg, and jwkMatchesOp checks the JWK's alg/use/key_ops. A resolver returning an RSASSA key for a PS256 header fails with a "key is unusable" TypeError regardless of what the resolver did.

One line fixes it:

const key = yield* jwks.resolve({ algorithm: alg, kid: header.kid })
if (key.algorithm !== alg) return yield* algorithmNotAllowed(alg)

3. Return the resolved key from Jwe.decrypt / Jwt.decrypt

Jws.verifyWithKeySet returns & { key: PublicKey }, but Jwe.Decrypted / Jwt.Decrypted don't. The use case is keyring rotation: decrypt with whichever key matched, then re-seal with the current key if it wasn't the current one — you need to know which key was used.

For comparison, every resolver-based jose API (compactVerify, jwtVerify, compactDecrypt, jwtDecrypt and the flattened variants) returns & ResolvedKey<KeyType>, with key present exactly when a resolver was used.

4. A bound on token length before decoding

decode splits, base64-decodes and JSON.parses whatever it's handed. JWKS already has maxResponseBytes (131072) and maxKeys (64); a maxTokenLength option (or at least a doc note telling callers to bound it at the edge) would make the two sides consistent. We cap at 16 KiB for bearer tokens and 8 KiB for client-auth assertions.

To be fair to the comparison: jose has no token-length bound either, and it doesn't bound remote JWKS response size at all (only timeoutDuration/cooldownDuration/cacheMaxAge), so effect/jose is already stricter there. This is hardening we apply ourselves rather than something jose does.

5. Is the algorithm profile intentionally minimal for the first cut?

Jwk.ts supports HS256/RS256/PS256/ES256/EdDSA for JWS and dir+A256GCM for JWE. effect/crypto already has P-384/P-521, SHA-384/512 and RSA-PSS salt handling, so RS/PS/ES 384/512 look like they'd be mostly table entries. In practice upstream IdPs we federate with publish RS384/RS512/ES384 keys in their JWKS, and a set that can't import those keys can't verify those tokens.

For comparison, jose JWS: HS256/384/512, RS256/384/512, PS256/384/512, ES256/384/512, EdDSA (and Ed25519, ML-DSA-44/65/87). JWE key management: dir, RSA-OAEP(-256/384/512), ECDH-ES(+A128/192/256KW), A128/192/256KW, A128/192/256GCMKW, PBES2-*; content encryption: A128/192/256GCM and A128CBC-HS256/A192CBC-HS384/A256CBC-HS512. Fine if this is deliberately a follow-up — I'd just call it out in the module docs.

Nits

  • generateKeyPair stamps alg and kid onto the exported JWK but not use. jose's exportJWK goes the other way and strips alg, use, key_ops and ext entirely (except for AKP) and leaves it to the caller — either is defensible, but half-stamping is the odd one out; adding use: "sig"/"enc" would let makeLocal do the use check it already does.
  • There's exportPrivate but no exportPublic; jose's exportJWK takes either half of a CryptoKey pair.
  • Jws.sign/Jws.verify reach for as any to satisfy the KeyRequirements<K> overload — probably a small conditional-type tweak away from not needing it.

@jpowersdev

Copy link
Copy Markdown
Contributor

Hi @danieljvdm, thanks for putting this together, and for how quickly you've worked through eugene's feedback. Before the effect/crypto rework started, I'd been building a JOSE implementation for Effect in my own fork on top of the old Crypto service. Alongside it I wrote a separate conformance suite that tests it against jose and the RFC 7520 examples on Node, Deno, Bun and browsers (jpowersdev/effect-jose-conformance). That work was overtaken by the rework and this PR, but the test cases still apply, so I ran the ones that fit this PR's algorithms against 3994ca7. It handles nearly all of them: malformed headers, none/unknown alg, crit/b64, non-canonical base64url, keys whose curve or metadata don't match, short HMAC keys, oversized or redirected remote key sets, and malformed JWE headers all fail as they should. A few things came out of it that might help:

1. verifyWithKeySet and keys resolved for a different algorithm

This confirms eugene's point 2: it still reproduces at 3994ca7. A custom Jwks that ignores selection.algorithm and returns an RS256 key makes Jws.verifyWithKeySet(token, { algorithms: ["PS256"] }) accept a token whose header says PS256 but which carries an RS256 signature. Jwt.verifyWithKeySet inherits it. Here's a regression test that fails today and passes with the one-line check eugene suggested:

// src/jose/Jws.ts, verifyWithKeySet
const key = yield* jwks.resolve({ algorithm: alg, kid })
if (key.algorithm !== alg) return yield* algorithmNotAllowed
// test/jose/Jws.test.ts (needs `Signature` from "effect/crypto")
it.effect("rejects a resolved key whose algorithm differs from the token's", () =>
  Effect.gen(function*() {
    const privateKey = yield* Jwk.importPrivate(Redacted.make(rfc7515.rs256.jwk), "RS256")
    const publicKey = yield* Jwk.importPublic(rs256PublicJwk, "RS256")
    // A valid RS256 signature over a header that claims PS256.
    const signingInput = `${jose.base64url.encode(utf8("{\"alg\":\"PS256\"}"))}.${jose.base64url.encode(utf8("{}"))}`
    const signature = yield* Signature.Signature.use((signer) => signer.sign(privateKey.key, utf8(signingInput)))
    const token = `${signingInput}.${jose.base64url.encode(signature)}`

    // A custom key set that ignores the selected algorithm.
    const keySet = Layer.succeed(Jwks.Jwks, Jwks.Jwks.of({ resolve: () => Effect.succeed(publicKey) }))
    assertReason(
      yield* Jws.verifyWithKeySet(token, { algorithms: ["PS256"] }).pipe(Effect.provide(keySet), Effect.flip),
      "AlgorithmNotAllowed"
    )
  }).pipe(Effect.provide(layer)))

2. An exact HS256 signing test from RFC 7520

The RFC 7515 A.1 token can only be verified, not reproduced, because its header contains a line break. RFC 7520 §4.4 uses a compact {"alg","kid"} header, so it gives an exact HS256 signing test and also checks that kid comes from the key and is written after alg. It passes on the current head:

// RFC 7520, Section 4.4. Unlike RFC 7515 A.1, the header serializes as
// `{"alg":...,"kid":...}`, so the token can be reproduced exactly.
const rfc7520 = {
  jwk: {
    kty: "oct",
    kid: "018c0ae5-4d9b-471b-bfd6-eef314bc7037",
    use: "sig",
    alg: "HS256",
    k: "hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg"
  } satisfies Jwk.SecretJwk,
  payload:
    "SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4",
  token: "eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9" +
    ".SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4" +
    ".s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0"
}

it.effect("reproduces the RFC 7520 Section 4.4 HS256 signature with the key's kid", () =>
  Effect.gen(function*() {
    const key = yield* Jwk.importSecret(Redacted.make(rfc7520.jwk), "HS256")
    const token = yield* Jws.sign(base64url(rfc7520.payload), key)
    assert.strictEqual(Redacted.value(token), rfc7520.token)

    const verified = yield* Jws.verify(rfc7520.token, key)
    assert.deepStrictEqual(verified.protectedHeader, { alg: "HS256", kid: rfc7520.jwk.kid })
  }).pipe(Effect.provide(layer)))

The §4.1 RS256 example reproduces exactly too, but it overlaps with the RFC 7515 A.2 test you already have.

3. Small things

  • Token length: +1 to eugene's point 4. A 1 MB compact token is fully decoded before it fails on the signature. A maxTokenLength with a generous default (we used 64 KiB) would match the existing maxResponseBytes/maxKeys limits on the remote key set.
  • JWK member validation: importSecret checks k strictly with decodeSegment, but RSA/EC/OKP members go straight to the backend. Node's WebCrypto accepts padded or space-containing values, and n: "***" imports as a 0-bit modulus and fails with "RSA keys must have at least 2048 bits". Running the same strict base64url check on asymmetric members would give one behaviour across runtimes and a clearer error. Low priority.

4. A naming thought (not a strong opinion)

Jwk and Jwks are one letter apart but do different jobs (importing single keys vs. the key-set service), which seems easy to mix up in imports and autocomplete. Did you consider JsonWebKey / JsonWebKeySet (and JsonWebSignature, JsonWebEncryption, JsonWebToken)? My fork used the full names and I liked how they read with the rest of Effect's module names. I know Effect also uses short forms like Aead, Csv and Url, and JsonWebKey overlaps with the DOM type of the same name, so I'm happy to defer to you.

5. Offer

If it would help, I can point the conformance suite at this branch so the PR also gets tested on Deno, Bun and browsers alongside Node. I'm happy to send any of the above as a PR against feat/unstable-jose instead, if you'd prefer that to copying code from a comment.

danieljvdm and others added 12 commits October 29, 2026 13:44
Retarget the changeset to a patch, mark the new APIs @SInCE 4.1.1, and
match the KeyFormat.JsonWebKey hunk to #10116 so the two PRs apply cleanly
in either order.
Keep one representative per new path: canonical base64url members, SPKI and
PKCS#8 in DER and PEM, generated secrets, thumbprints per key type, header
extensions, and JWS interop for every algorithm. Drop member-by-member and
per-format matrices and type assertions that repeat the same signatures.
…lgorithm guard

The protected header is now built in one step with the same key order and
values. verifyWithKeySet rejects non-asymmetric algorithms through
Schema.is(AsymmetricAlgorithm) instead of listing the HMAC algorithms, and
the thumbprint docs note that secret-key thumbprints are sensitive.
Comment thread packages/effect/src/jose/Jwe.ts Outdated
* @category models
* @since 4.1.1
*/
export type KeyResolver<E = never, R = 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.

Remove this type

Comment thread packages/effect/src/jose/Jws.ts Resolved
Comment thread packages/effect/src/jose/Jwt.ts Resolved
exportSpki and exportPkcs8 carried three overloads plus an implementation
signature apiece. A single signature generic over the format gives the same
results for DER, PEM, and a format union, as the type tests pin. No behavior
change.
…ced use

Jws.sign and Jws.verify get explicit overload-style type annotations in
place of the overloaded generator declarations. The Jwe.KeyResolver alias is
removed and the resolver function type is written inline on Jwe.decrypt and
Jwt.decrypt. Jwt.sign, Jwt.encrypt, Jwk.generateSecret, Jwk.exportPublic and
Jwk.exportPrivate are plain Effect.flatMap/map compositions instead of
fnUntraced generators. No behavior change.

Tests still reference Jwe.KeyResolver and need a follow-up edit.
Comment thread packages/effect/src/jose/Jwk.ts Outdated
})
): Effect.Effect<Redacted.Redacted<SecretJwk>, never, SecureRandom.SecureRandom> =>
Effect.map(
Effect.flatMap(SecureRandom.SecureRandom, (random) => random.randomBytes(secretKeyLength(algorithm))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can use SecureRandom.SecureRandom.use. There might be other candidates

Comment thread packages/effect/src/jose/Jws.ts Outdated
): Effect.fn.Return<Redacted.Redacted<string>, JoseError.JoseError, KeyRequirements<K>>
function* signGenerator(
export const sign: {
<K extends SigningKey, H extends object & { readonly [P in keyof H]: Schema.Json | undefined } = Header>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only has one overload, so doesn't need the { ... }. Check for other candidates

…ional

An options type with an optional "pem" format may omit the property, in
which case exportSpki and exportPkcs8 produce DER. The result type must say
so. Fails against the current generic signatures, which infer a PEM-only
result.
…t service calls

exportSpki and exportPkcs8 return to three overloads, so an optional PEM
format yields a DER-or-PEM union instead of promising PEM. Jws.sign and
Jws.verify use a plain function-type annotation. Single-use service access
goes through Service.use in Jwk, Jwe, and Jws. No behavior change.
Comment thread packages/effect/src/jose/Jwe.ts Resolved
…ction

Jwks candidate selection ran Schema.is(PublicJwk) on every key in the set
for every lookup. Filtering on kty, crv, kid, alg and use first means the
schema check only runs on keys that can match. A cached RS256
verifyWithKeySet against a 64-key set drops from ~226µs to ~92µs median,
the same as a single-key set. Adds that case to the JOSE benchmark.
Jwks computes the selectable public keys once per local key set and per
fetched remote snapshot, so lookups no longer re-run the PublicJwk schema.
The JWS and JWE header decoders and the JWT claims decoder are built once at
module level. The Jws docs point to the node:crypto Mac layers for HMAC.
@eugene1g

Copy link
Copy Markdown
Contributor

Huge thanks @danieljvdm for building this, and @tim-smart for the thorough review rounds. It's really great to have JOSE in core now.

I did some benchmarking against jose as a sanity check, and the results look good. effect/jose is comparable to or faster than jose on the hot paths:

  • 🟢 HMAC is much faster with NodeCrypto: HS256 JWS/JWT and JWK thumbprints are 4.5–8.4× faster.
  • ⚪ Asymmetric signing and verification, JWE and JWKS lookup are at parity: 0.8–1.2× of jose, because both libraries end up in crypto.subtle.
  • 🟡 The non-crypto paths are slower by design: decodeUnverified, importPublic and generateKeyPair are 1.6–4× slower because they do Schema validation and JWK re-export. These are per-key costs, not per-request ones.
Setup
  • Exact merged build from pkg.pr.new, compared with jose 6.2.14
  • Before timing, every case was cross-verified: tokens signed by Effect verify in jose and vice versa, thumbprints are byte-equal, and claims match
  • Node 26.12, 4 vCPU Xeon, 3 s per task with a 500 ms warmup

Results (ops/sec, higher is better)

Operation jose 6.2.14 effect (WebCrypto) effect (NodeCrypto) Web vs jose Node vs jose
HMAC
Jws.sign HS256 9,342 10,721 78,624 1.15× 🟢 8.42×
Jws.verify HS256 9,165 9,847 51,540 1.07× 🟢 5.62×
Jwt.sign HS256 (schema claims) 8,435 9,366 51,009 1.11× 🟢 6.05×
Jwt.verify HS256 (schema + policy) 7,918 7,254 35,586 0.92× 🟢 4.49×
Jwk.thumbprint ES256 12,517 10,594 99,353 0.85× 🟢 7.94×
Asymmetric
Jws.sign RS256 2,115 1,836 1,856 0.87× 0.88×
Jws.verify RS256 8,453 6,980 7,115 0.83× 0.84×
Jws.sign PS256 1,658 1,951 1,737 1.18× 1.05×
Jws.verify PS256 7,755 7,096 7,224 0.91× 0.93×
Jws.sign ES256 7,359 7,539 7,319 1.02× 0.99×
Jws.verify ES256 5,468 4,999 5,024 0.91× 0.92×
Jws.sign EdDSA 7,976 6,496 6,395 0.81× 0.80×
Jws.verify EdDSA 4,620 4,083 4,053 0.88× 0.88×
Jwt.sign PS256 (schema claims) 1,782 1,920 1,555 1.08× 0.87×
Jwt.verify PS256 (schema + policy) 7,953 6,434 6,641 0.81× 0.83×
Jwt.verify ES256 (schema + policy) 5,249 4,641 4,750 0.88× 0.90×
Jws.verifyWithKeySet RS256 (local JWKS, 4 keys) 8,438 7,106 7,269 0.84× 0.86×
JWE
Jwe.encrypt dir/A256GCM 8,184 9,168 9,197 1.12× 1.12×
Jwe.decrypt dir/A256GCM 8,672 8,490 8,667 0.98× 1.00×
Non-crypto / key management
Jwt.decodeUnverified 205,890 70,343 69,978 🟡 0.34× 🟡 0.34×
Jwk.importPublic RS256 29,867 9,946 9,325 🟡 0.33× 🟡 0.31×
Jwk.importPublic ES256 20,780 12,746 12,412 🟡 0.61× 🟡 0.60×
Jwk.generateKeyPair ES256 7,940 2,023 1,977 🟡 0.25× 🟡 0.25×
Jwk.generateSecret HS256 ⚠️ 12,498 204,330 195,116 16.4× 15.6×

⚠️ generateSecret isn't an apples-to-apples comparison. Effect returns random bytes as a JWK, while jose builds a CryptoKey.

What the numbers mean

🟢 HMAC and thumbprints: a clear win with NodeCrypto. NodeCrypto.layerMac and layerDigest call createHmac and createHash synchronously, so they skip the threadpool round trip that jose makes on every crypto.subtle call. With the WebCrypto layer, the numbers are about the same as jose.

⚪ Asymmetric signing and verification, JWE and JWKS: at parity. Both libraries spend their time in crypto.subtle. The fiber and Schema overhead in Effect adds a few µs to operations that take 100–600 µs, so performance doesn't favor either library.

🟡 Non-crypto paths: slower, by design. decodeUnverified, importPublic and generateKeyPair do Schema validation, a JWK export round trip, or both, which jose skips. Its generateKeyPair returns CryptoKeys without exporting them, and its importJWK neither validates members nor re-exports. You pay these costs per key or at startup, not on every request.

@guillempuche

Copy link
Copy Markdown

Good job guys!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants