Skip to content
SourceRegistryPublic

About

A lightweight, zero-dependency TypeScript library for creating, verifying and decoding JSON Web Tokens (JWT).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🔐 @sourceregistry/node-jwt

npm version JSR License CI Codecov

A minimal, secure, and production-ready JWT (JSON Web Token) library for Node.js with zero dependencies. Supports all standard signing algorithms (HMAC, RSA, ECDSA, EdDSA, RSASSA-PSS), automatic algorithm detection, first-class JWK/JWKS (verify straight against a local or remote key set), and full claim validation.

✨ Why another JWT library? Most JWT libraries are bloated, have security pitfalls, or lack proper TypeScript support. This library is:

  • Tiny
  • Secure by default
  • TypeScript-first with full JSDoc
  • Zero external dependencies
  • 100% test coverage (Trying😉)
  • Dual API: Sync and Promise-based
  • Automatic algorithm detection based on key type
  • Full JWK/JWKS support: pass a JWK, a JWKS or a remote JWKS resolver directly to verify(); publish your own JWKS with one call
  • Spec compliant: RFC 7515, 7517, 7518, 7519, 7638, 8037, 8725, 8812 and 9864 (see Spec compliance)

📦 Installation

npm install @sourceregistry/node-jwt

Requires Node.js ≥ 16


🚀 Quick Start

Sync API (default)

import { randomBytes } from 'crypto';
import { sign, verify, decode } from '@sourceregistry/node-jwt';

// HS256 needs a secret of at least 32 bytes (RFC 7518 §3.2)
const secret = randomBytes(32);

// Sign (algorithm auto-detected)
const token = sign(
  { sub: '1234567890', name: 'John Doe', iat: Math.floor(Date.now() / 1000) },
  secret
);

// Verify
const result = verify(token, secret, { algorithms: ['HS256'], issuer: 'https://example.com' });
if (result.valid) {
  console.log('Payload:', result.payload);
} else {
  console.error('JWT Error:', result.error.code, result.error.reason);
}

// Decode (unsafe)
const { header, payload, signature } = decode(token);

Promise API (/promises)

import { sign, verify, JWTError } from '@sourceregistry/node-jwt/promises';

const token = await sign({ sub: '1234567890', iat: Math.floor(Date.now() / 1000) }, secret);

try {
  const { payload } = await verify(token, secret, {
    issuer: 'https://example.com',
    audience: 'my-app',
    algorithms: ['HS256']
  });
  console.log('Payload:', payload);
} catch (error) {
  if (error instanceof JWTError) console.error('JWT Error:', error.code, error.reason);
}

🧩 JWK / JWKS

No glue code needed: every place that takes a key also takes a JWK, and verify() takes a whole JWKS.

Verify against a remote JWKS (OIDC / OAuth providers)

import { JWKS } from '@sourceregistry/node-jwt';
import { verify } from '@sourceregistry/node-jwt/promises';

// Create once and reuse: keys are cached, refreshed after `ttl`
// and re-fetched (rate limited) when a token carries an unknown `kid`.
const issuerKeys = await JWKS.fromWeb('https://issuer.example'); // -> /.well-known/jwks.json

const { payload } = await verify(token, issuerKeys, {
  algorithms: ['RS256'],
  issuer: 'https://issuer.example',
  audience: 'my-api'
});

Verify against a local JWK or JWKS

import { verify } from '@sourceregistry/node-jwt';

verify(token, jwk, { algorithms: ['ES256'] });             // a single JWK
verify(token, { keys: [/* ... */] }, { algorithms: ['ES256'] }); // a JWKS: selected by kid + alg
verify(token, (header) => keyFor(header.kid));             // or resolve the key yourself

Key selection follows RFC 7517 and RFC 8725: a key is only used when its kid matches (if the token has one), use is sig (or absent), key_ops includes verify (or is absent), its alg equals the token's alg (or is absent) and its kty / crv fit the algorithm. Remote key sets never supply symmetric keys and are only used as public keys.

Sign with a JWK and publish your JWKS

import { generateKeyPairSync } from 'crypto';
import { JWK, JWKS, sign } from '@sourceregistry/node-jwt';

const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
const signingKey = JWK.export(privateKey, { kid: '2026-01', alg: 'ES256', use: 'sig' });

// kid and alg are taken from the JWK
const token = sign({ sub: 'user-1' }, signingKey);

// Serve this at /.well-known/jwks.json: private members are stripped,
// a missing kid becomes the RFC 7638 thumbprint and use defaults to "sig".
const jwks = JWKS.create([signingKey]);

Helpers

Function Description
JWK.export(key, params?) / exportJWK KeyObject → JWK, optionally with kid / alg / use / key_ops
JWK.import(jwk) / importJWK JWK → KeyObject. Validates x5c / x5t / x5t#S256 against the key
JWK.toPublic(keyOrJwk, params?) / toPublicJWK Public-only JWK (rejects symmetric keys)
JWK.thumbprint(jwk, hash?) / getJWKThumbprint RFC 7638 thumbprint (sha256 default, sha384, sha512)
JWK.computeX5T(jwk, hash?) / computeX5T x5t (SHA-1) or x5t#S256 from x5c
JWK.isUsableFor(jwk, alg, op?) / isJWKUsableFor Whether use / key_ops / alg / kty allow the operation
JWKS.create(keys) / createJWKS Build a publishable public JWKS
JWKS.select(jwks, { alg, kid? }) / selectJWKs Keys that can verify a given alg / kid
JWKS.normalize(jwks) / normalizeJWKS Drop unsupported keys (RFC 7517 §5), fill in kid / x5t
JWKS.toKeyObject(jwks, kid?) KeyObject for a kid (or the only key)
JWKS.fromWeb(url, options?) / fromWeb Cached remote JWKS resolver

JWKS.fromWeb() options

  • fetch — custom fetch implementation (for runtimes/framework adapters)
  • ttl — cache TTL in ms (default 5 minutes; 0 disables automatic refresh, call refresh() instead)
  • maxStaleMs — how long to keep serving cached keys after ttl when refreshing fails (default 5 minutes; 0 fails closed)
  • timeoutMs — timeout for fetching and parsing the JWKS response in ms (default 5 seconds)
  • cooldownMs — minimum time between re-fetches caused by an unknown kid (default 30 seconds)
  • endpointOverride — custom endpoint (absolute or relative to url)
  • overrideEndpointCheck — skip automatic /.well-known/jwks.json append
  • allowInsecureHttp — allow http: on non-loopback hosts. Otherwise endpoints must use https: (localhost, 127.0.0.1 and [::1] are allowed for development)
  • cache — custom cache backend with { get(key), set(key, value) }; persist the fetchedAt timestamp included in values passed to set. Entries without a valid timestamp are fetched again when ttl > 0.

Resolver methods:

  • resolve({ alg, kid }) — public keys that can verify a token (used by the promise verify())
  • key(kid) — normalized key (or undefined) extended with toKeyObject()
  • list() — all normalized keys
  • find(query) / findFirst(query) — keys whose members equal query
  • refresh() — forces reload and returns the resolver instance
  • export() — the current cached JWKS snapshot, or undefined after its maximum stale age

Keys with a kty the library does not understand (for example post-quantum AKP keys) or with missing members are ignored instead of failing the whole set, as required by RFC 7517 §5.


🔑 Supported Algorithms

Algorithm Type Key
HS256 / HS384 / HS512 HMAC secret ≥ 32 / 48 / 64 bytes
RS256 / RS384 / RS512 RSASSA-PKCS1-v1_5 RSA ≥ 2048 bits
PS256 / PS384 / PS512 RSASSA-PSS RSA or RSA-PSS ≥ 2048 bits
ES256 / ES384 / ES512 ECDSA P-256 / P-384 / P-521
ES256K ECDSA (RFC 8812) secp256k1
EdDSA EdDSA (RFC 8037) Ed25519 or Ed448
Ed25519 / Ed448 EdDSA (RFC 9864) Ed25519 / Ed448

Keys may be PEM, DER, JWK, or Node.js KeyObject.

🧠 Algorithm autodetection

When alg is omitted, sign() uses the JWK's alg if present, otherwise it picks one from the key:

Key Algorithm
Symmetric (string / Buffer) HS256
RSA RS256
RSA-PSS PS256 / PS384 / PS512 (from the key's hash)
EC P-256 / P-384 / P-521 ES256 / ES384 / ES512
EC secp256k1 ES256K
Ed25519 / Ed448 EdDSA

Unsupported keys (other EC curves, RSA-PSS with SHA-1, DSA, ...) throw.


🛡️ Security

  • Algorithm/key binding: each algorithm only accepts its key type and curve; HMAC never accepts asymmetric keys (RFC 8725 §2.1)
  • Minimum key sizes enforced on sign and verify: HMAC secret ≥ hash size, RSA ≥ 2048 bits (RFC 7518 §3.2, §3.3)
  • alg: none and unknown algorithms are always rejected; algorithms allowlist supported
  • JWKS key selection honors kid, use, key_ops, alg, kty and crv
  • Remote JWKS: https: required, insecure redirects rejected, symmetric and private key material never used
  • ECDSA signatures must be exactly r || s (RFC 7518 §3.4); DER is only accepted when explicitly requested
  • Strict, canonical base64url and UTF-8 decoding: every token has exactly one valid serialization
  • Rejects unsupported critical headers (crit)
  • Time claim validation (exp, nbf, iat) with clock skew, maxTokenAge, requiredClaims
  • x5c certificates must contain the JWK's key; x5t / x5t#S256 must match
  • Timing-safe HMAC comparison
  • sign() / verify() use private copies of the signature primitives, so mutating the exported SignatureAlgorithm map cannot weaken them

✅ Production checklist

const result = verify(token, publicKeyOrJwks, {
  algorithms: ['RS256'],           // pin expected algorithm(s)
  issuer: 'https://issuer.example',
  audience: 'my-service',
  requiredClaims: ['exp'],         // reject tokens without an expiry
  clockSkew: 30,                   // seconds
  maxTokenAge: 3600                // seconds
});
  • Pin algorithms in every verify call (RFC 8725 §3.1).
  • Always validate issuer and audience for external tokens. RFC 7519 §4.1.3 requires a recipient to reject a token whose aud does not identify it, so configure audience whenever tokens carry one.
  • Keep tokenTypes narrowly scoped when accepting specialized JWT profiles (default ['JWT']).
  • Use short token lifetimes and require exp with requiredClaims.
  • Rotate keys regularly; JWKS.fromWeb() picks up new kids automatically.
  • Monitor verification failures (INVALID_SIGNATURE, KEY_ALGORITHM_MISMATCH, KEY_NOT_FOUND, INVALID_CLAIM).

📐 Spec compliance

Spec Coverage
RFC 7515 (JWS) Compact serialization, canonical base64url, UTF-8 JSON header, crit rejection, case-insensitive typ with implicit application/
RFC 7517 (JWK) use / key_ops / alg enforcement, x5c / x5t / x5t#S256 validation, unknown keys ignored in sets
RFC 7518 (JWA) All JWS signature algorithms, minimum key sizes, PSS salt = hash length, r ‖ s ECDSA signatures
RFC 7519 (JWT) Claims object, registered claim types, exp / nbf / iat, iss / sub / aud / jti, cty for nested JWTs
RFC 7638 JWK thumbprints (SHA-256 / 384 / 512)
RFC 8037 EdDSA with Ed25519 and Ed448
RFC 8725 (JWT BCP) Algorithm allowlists, key/algorithm binding, explicit typing via tokenTypes
RFC 8812 ES256K
RFC 9864 Fully-specified Ed25519 / Ed448 algorithms

🔏 ECDSA signature format

JWS requires ECDSA signatures as the raw r || s concatenation ("JOSE" format, RFC 7518 §3.4), while Node.js/OpenSSL natively use ASN.1 DER. sign() and verify() use JOSE by default.

For legacy systems that produce non-standard DER-encoded JWTs, opt in explicitly:

sign(payload, ecPrivateKey, { signatureFormat: 'der' });
verify(token, ecPublicKey, { signatureFormat: 'der' });

💡 VAPID/Web Push uses ES256 with the default JOSE format.


📚 API Reference

sign(payload, key, options?)

  • key — secret, PEM/DER, KeyObject or JWK (private or oct)
  • alg — defaults to the JWK's alg, otherwise auto-detected
  • kid — defaults to the JWK's kid
  • typ — token type (default "JWT")
  • cty — content type, e.g. "JWT" for nested tokens
  • signatureFormat — ECDSA only: "jose" (default) or "der"

The payload must be a JSON object; registered claims (iss, sub, aud, exp, nbf, iat, jti, sid) are type-checked.

verify(token, key, options?)

key may be a secret, PEM/DER, KeyObject, JWK, JWKS or (header) => key. The promise version additionally accepts a JWKS.fromWeb() resolver and async functions, and rejects with a JWTError.

Options:

  • algorithms — allowlist (non-empty)
  • tokenTypes — allowed typ values (default ['JWT']; a missing typ is valid). Compared case-insensitively, application/ optional. For example, OpenID Connect Back-Channel Logout tokens use tokenTypes: ['logout+jwt'].
  • issuer, subject, audience, jwtId — expected claim values
  • requiredClaims — claims that must be present
  • clockSkew — seconds of tolerance for exp, nbf, iat and maxTokenAge
  • maxTokenAge — maximum age in seconds (requires iat)
  • ignoreExpiration — skip the exp check
  • signatureFormat — ECDSA only: "jose" (default) or "der"

Error codes:

  • INVALID_OPTIONS, INVALID_TOKEN, INVALID_CLAIM
  • INVALID_ALGORITHM, ALGORITHM_NOT_ALLOWED, INVALID_TYPE, UNSUPPORTED_CRITICAL_HEADER
  • KEY_NOT_FOUND, KEY_ALGORITHM_MISMATCH, INVALID_SIGNATURE
  • TOKEN_EXPIRED, TOKEN_NOT_ACTIVE, TOKEN_FUTURE_ISSUED, TOKEN_TOO_OLD
  • MISSING_CLAIM, MISSING_IAT, MISSING_ISSUER / INVALID_ISSUER, MISSING_SUBJECT / INVALID_SUBJECT, MISSING_AUDIENCE / INVALID_AUDIENCE, MISSING_JTI / INVALID_JTI

decode(token)

Decode a JWT without verification (unsafe).


⚠️ Upgrading from 1.x

These changes make the library spec compliant and may reject tokens or keys that were accepted before:

  • HMAC secrets must be at least as long as the hash output: 32 bytes for HS256, 48 for HS384, 64 for HS512 (RFC 7518 §3.2).
  • RSA keys must be at least 2048 bits (RFC 7518 §3.3).
  • ECDSA verification no longer falls back to DER signatures. Pass signatureFormat: 'der' for legacy tokens.
  • Non-canonical base64url and invalid UTF-8 in tokens are rejected (INVALID_TOKEN).
  • sign() rejects non-object payloads and registered claims with the wrong type.
  • JWKS.fromWeb() requires https: (except loopback) unless allowInsecureHttp: true, and throws on invalid endpoint URLs.
  • SignatureAlgorithm.ES* primitives produce and expect JOSE (r || s) signatures.
  • The promise verify() rejects with a JWTError (an Error with the same code and reason properties as before).
  • SupportedAlgorithms is a frozen array and also contains Ed25519 and Ed448.
  • maxTokenAge now honors clockSkew.

📦 Exports

Import Description
@sourceregistry/node-jwt Sync API
@sourceregistry/node-jwt/promises Promise API

🧪 Testing

  • High branch coverage
  • All algorithms + autodetection paths
  • All failure modes
  • Sync + Promise APIs
  • Full JWK/JWKS coverage (import/export, x5c/x5t, thumbprint, kid selection, remote rotation)
  • RFC test vectors (RFC 7515 A.1, RFC 7638 §3.1, RFC 8037 A.3)
npm test
npm run test:coverage

🙌 Contributing

PRs welcome! Please add tests and maintain full coverage.

🔐 Security issues? Report responsibly: a.p.a.slaa@projectsource.nl

🔗 GitHub: https://github.com/SourceRegistry/node-jwt 📦 npm: https://www.npmjs.com/package/@sourceregistry/node-jwt

About

A lightweight, zero-dependency TypeScript library for creating, verifying and decoding JSON Web Tokens (JWT).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages