@effected/jwt

中文文档
0.10.0发布于 2026/11/10MITTypeScriptES Module构建来源已验证近 30 天下载 1万

JWS, JWT, JWK and JWKS sign and verify over WebCrypto for Effect v4, safe for Workers.

原始使用文档
文档目录10 节
  1. Why @effected/jwt
  2. Install
  3. What to provide
  4. Sign a JWT
  5. Verify against an issuer's published keys
  6. Verify with a key you hold
  7. Algorithms
  8. Errors
  9. Testing
  10. License

@effected/jwt

npm License: MIT Node.js %3E%3D24.11.0

Sign and verify JWTs for Effect v4, and resolve verification keys from an issuer's published key set. A thin layer over core effect/jose, which runs every signature, key import and claim check, so it works anywhere WebCrypto does: Node, Bun, Deno, browsers and Cloudflare Workers, with no node: import.

Pre-1.0.0. This package is part of the @effected/* kit, built on stable Effect v4 and still in 0.x development. To keep your effect and @effect/* versions on the line the kit is built and tested against, install @effected/pnpm-plugin-effected.

Stability: unstable. This package's API surface is not yet considered complete and may change across 0.x releases. Pin an exact version. Full policy: release strategy.

Why @effected/jwt

Core effect/jose already signs and verifies JWS and JWT, imports JWKs and fetches a key set. Use it directly when you verify against a key you already hold, or against one fixed HTTPS JWKS URL (Jwks.layerRemote), sign with a PKCS#8 key, or need HMAC or JWE.

Reach for this package when you need what core leaves to you:

  • Keys found by OIDC discovery. JwksResolver finds each issuer's key set from <issuer>/.well-known/openid-configuration, checks the discovery document names that issuer exactly, serves many issuers from one service, and refetches once when a token names a rotated kid.
  • A cache you choose. The fetched key sets live in a JwksStore: in process with JwksStore.layerMemory, or in Workers KV so every isolate shares one fetch.
  • The PEMs people actually have. JwtKey.fromPkcs8Pem takes PKCS#8 and PKCS#1 (BEGIN RSA PRIVATE KEY, the format github.com hands out for App keys), including a key whose newlines arrive escaped as \n in a one-line environment variable.
  • Safer defaults. Jwt.verify allows 60 seconds of clock skew, requires exp unless you opt out, and refuses a token issued in the future. Core's defaults are zero skew and an optional exp.
  • One error to route on. Every failure is a JwtError with a flat reason string.
  • A test issuer. TestIssuer signs tokens that verify through the real resolver, with no network.

Keys are core's own types, so a key from JwtKey also works with core Jws and Jwt directly.

Install

npm install @effected/jwt effect
pnpm add @effected/jwt effect

On Node, requires Node.js >=24.11.0; it also runs on any other WebCrypto runtime, Cloudflare Workers included. effect v4 is the only peer. All @effected/* packages are ESM-only.

What to provide

Signing and verifying run on core services, which you provide once at your program's edge:

OperationRequires
Jws.sign, Jws.verify, Jwt.sign, Jwt.verify, JwtKey.generate, TestIssuerSignature.Signature
JwksResolver.layer, JwksResolver.layerWithHttpClient.HttpClient and JwksStore
Jwt.verify keyed by JwksResolver.forIssuerSignature.Signature and JwksResolver

JwtKey.fromPkcs8Pem, JwtKey.fromJwk and Jws.decodeUnverified need nothing.

ServiceAny WebCrypto runtime (Workers included)Node
Signature.SignatureSignature.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)) from effect/cryptoNodeCrypto.layerSignature from @effect/platform-node
HttpClient.HttpClientFetchHttpClient.layer from effect/httpNodeHttpClient.layerUndici from @effect/platform-node, or FetchHttpClient.layer
JwksStoreJwksStore.layerMemory, or your own KV-backed layerJwksStore.layerMemory
import { JwksResolver, JwksStore } from "@effected/jwt";
import { Layer } from "effect";
import { SecureRandom, Signature } from "effect/crypto";
import { FetchHttpClient } from "effect/http";

const CryptoLive = Signature.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto));

const JwtLive = Layer.merge(
  JwksResolver.layer.pipe(Layer.provide(Layer.merge(FetchHttpClient.layer, JwksStore.layerMemory))),
  CryptoLive,
);

Sign a JWT

A GitHub App JWT from the PKCS#1 key github.com issues. The header is {"alg":"RS256","typ":"JWT"}: alg always comes from the key.

import { Jwt, JwtKey } from "@effected/jwt";
import { Effect, Redacted } from "effect";

const signAppJwt = (pem: Redacted.Redacted<string>, appId: string, nowSeconds: number) =>
  Effect.gen(function* () {
    const key = yield* JwtKey.fromPkcs8Pem(pem, { alg: "RS256" });
    return yield* Jwt.sign({ iat: nowSeconds - 60, exp: nowSeconds + 540, iss: appId }, key);
  });

Verify against an issuer's published keys

Pass the issuer you expect to forIssuer, never one read from the token: the issuer decides which keys are trusted. Always pass audience for a shared issuer, whose one key set signs tokens for every relying party.

import { JwksResolver, Jwt } from "@effected/jwt";
import { Schema } from "effect";

const Claims = Schema.Struct({ sub: Schema.String });

const verify = (token: string) =>
  Jwt.verify(token, {
    key: JwksResolver.forIssuer("https://issuer.example"),
    claims: Claims,
    issuer: "https://issuer.example",
    audience: "my-service",
  });
// Effect<{ readonly sub: string }, JwtError, JwksResolver | Signature>

The checks run in this order: the signature, then exp present, iss, aud, exp not passed, nbf reached, your claims schema, and finally iat not in the future. clockTolerance and requireExpiry adjust the defaults.

Verify with a key you hold

key is a VerificationKey, or a function from the token's header to one.

import { Jwk, Jwt, JwtKey } from "@effected/jwt";
import { Effect, Schema } from "effect";

const verifyWith = (jwk: Jwk, token: string) =>
  Effect.gen(function* () {
    const key = yield* JwtKey.fromJwk(jwk);
    return yield* Jwt.verify(token, { key, claims: Schema.Struct({ sub: Schema.String }) });
  });

Jws is the same signature layer without claim rules (Jws.sign, Jws.verify), and Jws.decodeUnverified reads a token's header and payload as a synchronous Result, for routing on kid or iss before choosing a key. Never trust what it returns.

Algorithms

Every asymmetric algorithm core implements: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512 and EdDSA (Ed25519). The algorithm comes from the key, never the token's header, and RSA keys under 2048 bits are refused. HMAC is refused, because a key published in a key set must never be used as a shared secret; for HMAC use core's Jwk.importSecret with core Jwt. alg: "none" is never accepted.

Errors

Every failure is a JwtError. Route on reason, never on message or detail; when core produced the failure, its JoseError is the cause.

reasonMeaning
malformedNot a compact JWS: wrong segment count, non-canonical base64url, a header that is not a JOSE header, alg: "none" or an unknown algorithm, a crit or b64 member, or a payload that is not JSON.
unsupportedAlgorithmThe token or JWK names an HMAC (or other non-asymmetric) algorithm. No key is resolved.
algorithmMismatchThe token's alg is not the key's algorithm, or a JWK's alg differs from the one required.
badSignatureThe signature does not verify.
unknownKidNo key in the set matches the token's algorithm and kid, or several do.
expiredexp has passed, beyond the tolerance.
notYetValidnbf is in the future, or iat is, beyond the tolerance.
wrongIssueriss is missing or not an accepted issuer.
wrongAudienceaud is missing or contains no accepted audience.
claimsA registered claim has the wrong type, exp is missing, the payload is not a JSON object, your claims schema refused it, or the clock tolerance is invalid.
keyKey material did not import: a malformed or unsupported PEM, an RSA key under 2048 bits, a JWK whose type, curve, use or key_ops cannot verify.
jwksFetchThe key set could not be discovered or fetched: unreachable, slow, oversized, not https:, redirected off https:, a discovery document naming another issuer, or a set with no supported keys.

A token string is not an identity: ECDSA signatures are malleable, so one signed payload can have two valid token strings. Detect replay and revoke on verified claims (jti, or iss with sub and iat), never on the token text.

Testing

@effected/jwt/testing exports TestIssuer: a generated key pair, a signer that stamps iss, iat and a ten-minute exp, and resolverLayer, the real JwksResolver over an in-memory HttpClient serving the issuer's discovery document and key set.

import { JwksResolver, Jwt } from "@effected/jwt";
import { TestIssuer } from "@effected/jwt/testing";
import { Effect, Schema } from "effect";

const program = Effect.gen(function* () {
  const issuer = yield* TestIssuer.make({ issuer: "https://issuer.test" });
  const token = yield* issuer.sign({ aud: "my-app", sub: "user-1" });
  return yield* Jwt.verify(token, {
    key: JwksResolver.forIssuer("https://issuer.test"),
    claims: Schema.Struct({ sub: Schema.String }),
    issuer: "https://issuer.test",
    audience: "my-app",
  }).pipe(Effect.provide(issuer.resolverLayer));
});
// provide CryptoLive: TestIssuer and Jwt.verify both need Signature

Provide resolverLayer once around a whole test when it relies on caching or a rotation. TestIssuer.rotate(issuer, kid) adds a key under a new kid; the resolver still refetches at most once per 30 seconds, so advance the TestClock before verifying with the new key. With @effect/vitest, provide Signature per test (layer(CryptoLive, { buildPerTest: true })): a layer built once for a whole block shares one TestClock across its tests.

License

MIT

版本与发布记录

@effected/jwt 共发布 13 个版本,首次发布于 2026/10/10;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.10.0latest2026/11/103 天前
0.9.12026/11/094 天前
0.9.02026/11/0310 天前
0.8.02026/11/0112 天前
0.7.02026/10/2915 天前
0.6.02026/10/2420 天前

关于 @effected/jwt 的常见问题

@effected/jwt 是什么?

JWS, JWT, JWK and JWKS sign and verify over WebCrypto for Effect v4, safe for Workers.

如何安装 @effected/jwt?

在项目目录运行 npm install @effected/jwt,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:effect(~4.1.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@effected/jwt 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@effected/jwt 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@effected/jwt 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=24.11.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@effected/jwt 可以商用吗?

@effected/jwt 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@effected/jwt 的下载量有多少?

根据 npm 官方下载统计,@effected/jwt 在 2026/10/13 – 2026/11/11 这 30 天内被下载 10,200 次,日均约 340 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@effected/jwt 还在维护吗?

最新版本 0.10.0 发布于 2026/11/10(3 天前);至今共发布 13 个版本,其中过去 12 个月发布了 13 个;首次发布于 2026/10/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。