nish/crypto/jwt

JSON Web Tokens in the JWS compact serialization: verify one and check its claims, or sign one. RFC 7519 (JWT), RFC 7515 (JWS), RFC 7518 (the HS, RS and ES algorithms), RFC 8037 (EdDSA) and the RFC 8725 best current practice.

import {
  JWT_ALG_EDDSA,
  JWT_ALG_ES256,
  JWT_ALG_ES384,
  JWT_ALG_HS256,
  JWT_ALG_HS384,
  JWT_ALG_HS512,
  JWT_ALG_RS256,
  JWT_ALG_RS384,
  JWT_ALG_RS512,
  JWT_ERR_ALG,
  JWT_ERR_AUDIENCE,
  JWT_ERR_CLAIMS,
  JWT_ERR_EXPIRED,
  JWT_ERR_FORMAT,
  JWT_ERR_HEADER,
  JWT_ERR_IAT,
  JWT_ERR_ISSUER,
  JWT_ERR_NOT_YET,
  JWT_ERR_SIGNATURE,
  JWT_ERR_SIZE,
  JWT_ERR_SUBJECT,
  JWT_ERR_TYPE,
  JWT_MAX_TOKEN,
  JWT_MAX_TOKEN_LIMIT,
  JWT_OK,
  JwtKey,
  JwtVerifier,
  jwtAlgName,
  jwtEcKey,
  jwtEd25519Key,
  jwtEd25519SigningKey,
  jwtEs256SigningKey,
  jwtHmacKey,
  jwtRsaKey,
  jwtRsaKeyParts,
  jwtSign,
  jwtSignKid,
  jwtSignString,
} from "nish/crypto/jwt";
import { Secret } from "nish:secret";
import { JWT_ALG_HS256, JWT_MAX_TOKEN, JWT_OK, JwtKey, JwtVerifier, jwtHmacKey, jwtSignString } from "nish/crypto/jwt";

// secretKey: at least 32 random bytes, still the caller's to wipe; now: seconds since 1970
const roundTrip = (secretKey: Secret<u8[]>, token: string, now: i64): string | null => {
  const key: JwtKey | null = jwtHmacKey(JWT_ALG_HS256, secretKey); // make once; null for a short key
  if (key === null) {
    return null;
  }
  const v = new JwtVerifier(JWT_MAX_TOKEN); // make once per thread
  v.issuer = "https://issuer.example";
  v.audience = "api";
  v.leeway = toI64(30);
  if (v.verifyString(key, token, now) === JWT_OK) {
    // v.claims[0 .. v.claimsLen) is the payload's JSON; v.exp, v.nbf, v.iat are read
  }
  const minted: string | null = jwtSignString(key, "{\"sub\":\"ana\"}");
  key.wipe();
  return minted;
};
The key decides the algorithm, never the token

A JwtKey is made for one algorithm, and a token verifies only when its header's alg is that algorithm's name, spelled exactly. none names no key, so a token that says it is unsigned is refused like any other mismatch (JWT_ERR_ALG); an HS256 header in front of an RSA key is refused before any MAC is taken, so an RSA public key can never be used as an HMAC secret (RFC 8725 §2.1, §3.1).

The header must hold alg exactly once, as a string; typ and kid at most once, as strings; and no crit and no b64 (RFC 7515 §4.1.11, RFC 7797), since this verifier understands no extension and a header that names one must be refused. Other header members are skipped.

Nothing in the payload is read before the signature holds

The verifier reads the header, decodes the signature and checks it, and only then decodes and parses the claims. The claims are then checked against the clock and the verifier's settings:

  • exp (RFC 7519 §4.1.4): the token is good while now - leeway < exp. A token with no exp is refused unless requireExp is cleared.
  • nbf (§4.1.5): good once nbf <= now + leeway.
  • iat (§4.1.6): refused when it is later than now + leeway.
  • iss, sub (§4.1.1, §4.1.2): when the verifier names one, the token must carry it, spelled exactly.
  • aud (§4.1.3): one string or an array of strings. When the verifier names an audience, one of them must be it. A token that carries aud is refused by a verifier that names none, as §4.1.3 requires.

Each registered claim may appear once; the time claims are integers (seconds since 1970). now is the caller's, so a test passes its own clock.

Bounded once made

A JwtVerifier holds its decode buffers, its tokenizer and its results, sized once from the largest token it takes (JWT_MAX_TOKEN by default, 8 KiB); a longer token is refused before a byte is decoded. An HS token is checked against HmacKey's pads, keyed once when the key was made, through hmacKeyedVerify, and the tag is compared in constant time: an HS verify allocates nothing past its arena block. An RS, ES or EdDSA verify allocates the signed input's copy and whatever the public-key check itself allocates (bignums, points), which the caller's scope releases. One verifier is one thread's: it is not safe to share while a verify runs.

Base64url is strict

Base64url is strict, as nish/crypto/base64url: no padding, no whitespace, no character outside A-Z a-z 0-9 - _, and no stray bits in the last character, so each token has one spelling. The token itself is public, so the decoder here branches freely.

Signing

Signing covers HS256/384/512, ES256 and EdDSA, the algorithms the standard library holds a signer for; jwtSign answers null for an RS or ES384 key, which can verify only. The header written is {"alg":"…","typ":"JWT"}, with a kid when one is given.

Secrets

An HMAC key and a private key are Secret<u8[]> (nish:secret). A JwtKey copies what it is handed and the caller still owns, and wipes, its own; JwtKey.wipe() zeroes the key's copy and its HMAC pads. The threat model and what was checked are in docs/security/crypto-jwt.md.

Private names carry the jwt prefix because a std/ module's private functions share the importing program's flat symbol namespace (docs/wp26-stdlib.md §3e).

Functions

jwtAlgName

The alg header value for alg, "" for no algorithm this module knows.

const jwtAlgName: (alg: i32) => string
algi32required

A JWT_ALG_ constant.

returnsstring

The name RFC 7518 or RFC 8037 spells it with, such as "HS256".

jwtEcKey

An ES256 or ES384 verifying key from its uncompressed point, 04 ‖ x ‖ y (65 or 97 bytes). A point of the wrong length or form answers null; one off the curve makes every verification fail.

const jwtEcKey: (alg: i32, point: u8[]) => JwtKey | null
algi32required

JWT_ALG_ES256 or JWT_ALG_ES384.

pointu8[]required

The public point, copied into the key.

returnsJwtKey | null

A new key that verifies only, or null.

jwtEd25519Key

An EdDSA (Ed25519) verifying key from its 32 bytes (RFC 8037 §2's x); another length answers null.

const jwtEd25519Key: (pub: u8[]) => JwtKey | null
pubu8[]required

The public key, copied into the key.

returnsJwtKey | null

A new key that verifies only, or null.

jwtEd25519SigningKey

An EdDSA key that signs and verifies, from its 32-byte seed (RFC 8037 §2's d). A seed of another length answers null. The key keeps a copy; seed stays the caller's to wipe.

const jwtEd25519SigningKey: (
  seed: Secret<u8[]>,
) => JwtKey | null
seedSecret<u8[]>required

The private seed.

returnsJwtKey | null

A new key that signs and verifies, or null.

jwtEs256SigningKey

An ES256 key that signs and verifies, from its 32-byte private scalar. A scalar p256PublicKey refuses answers null. The key keeps a copy; priv stays the caller's to wipe.

const jwtEs256SigningKey: (
  priv: Secret<u8[]>,
) => JwtKey | null
privSecret<u8[]>required

The private scalar, big-endian.

returnsJwtKey | null

A new key that signs and verifies, or null.

jwtHmacKey

An HS256, HS384 or HS512 key that verifies and signs. RFC 7518 §3.2 asks for a key at least as long as the hash, so a shorter one answers null, as does an alg that is not HS. The pads are keyed once, here; key stays the caller's to wipe.

const jwtHmacKey: (
  alg: i32,
  key: Secret<u8[]>,
) => JwtKey | null
algi32required

JWT_ALG_HS256, JWT_ALG_HS384 or JWT_ALG_HS512.

keySecret<u8[]>required

The shared secret: at least 32, 48 or 64 bytes for the three.

returnsJwtKey | null

A new key that verifies and signs, or null.

jwtRsaKey

An RS256, RS384 or RS512 key from the DER of a PKCS#1 RSAPublicKey (rsaParsePublicKey's input). A key that does not parse, a modulus below 2048 bits (RFC 7518 §3.3) or an alg that is not RS answers null.

const jwtRsaKey: (alg: i32, der: u8[]) => JwtKey | null
algi32required

JWT_ALG_RS256, JWT_ALG_RS384 or JWT_ALG_RS512.

deru8[]required

The public key's DER, nothing before it and nothing after it.

returnsJwtKey | null

A new key that verifies only, or null.

jwtRsaKeyParts

An RS key from its big-endian modulus and exponent, as a JWK's n and e spell them once base64url-decoded (RFC 7518 §6.3.1). The same checks as jwtRsaKey; parts too long for any key this module takes answer null.

const jwtRsaKeyParts: (
  alg: i32,
  n: u8[],
  e: u8[],
) => JwtKey | null
algi32required

JWT_ALG_RS256, JWT_ALG_RS384 or JWT_ALG_RS512.

nu8[]required

The modulus, big-endian; leading zero bytes are dropped.

eu8[]required

The public exponent, big-endian; leading zero bytes are dropped.

returnsJwtKey | null

A new key that verifies only, or null.

jwtSign

jwtSignKid with no kid.

const jwtSign: (key: JwtKey, claims: u8[]) => string | null
keyJwtKeyrequired

The key to sign with.

claimsu8[]required

The payload: one JSON object, in bytes.

returnsstring | null

The token, or null as jwtSignKid answers it.

jwtSignKid

A compact JWS over the JSON object claims, signed with key, with a kid header member when kid is not null. Answers null when key cannot sign (RS, ES384 or a verify-only key), when claims is not one JSON object, or when kid is empty, longer than 256 bytes, or holds a byte that would need a JSON escape. The claims are signed as given: this function neither adds nor checks any claim.

const jwtSignKid: (
  key: JwtKey,
  kid: string | null,
  claims: u8[],
) => string | null
keyJwtKeyrequired

The key to sign with; a wiped one answers null.

kidstring | nullrequired

The key id to name in the header, or null for none.

claimsu8[]required

The payload: one JSON object, in bytes.

returnsstring | null

The token, a new string, or null.

jwtSignString

jwtSign over the bytes of the string claims. Answers null for claims outside ASCII, as verifyString refuses them: escape such text (\u00e9) or pass its UTF-8 bytes to jwtSign.

const jwtSignString: (
  key: JwtKey,
  claims: string,
) => string | null
keyJwtKeyrequired

The key to sign with.

claimsstringrequired

The payload: one JSON object, ASCII.

returnsstring | null

The token, or null as jwtSignKid answers it.

Classes

JwtKey

A key for one algorithm: what verifies its tokens and, for a key that can, signs them. Make one with jwtHmacKey, jwtRsaKey, jwtRsaKeyParts, jwtEcKey, jwtEd25519Key, jwtEs256SigningKey or jwtEd25519SigningKey; wipe() it when it is done with. An HS key holds its HMAC work hashers, so a key is one thread's, like a JwtVerifier: give each worker its own.

class JwtKey
Member
new JwtKey(alg: i32, hmac: HmacKey | null, rsa: RsaPublicKey | null, pub: u8[], priv: Secret<u8[]>, canSign: boolean) A key from its parts, checked for nothing: the jwt…Key functions are the way to make one, and this exists for them and for tests that build a key no function would. hmac, rsa and pub are kept as given; priv is copied, and stays the caller's to wipe.
wipe(): void Zero the key's private copy and its HMAC pads. It neither signs nor verifies after: its zeroed secret is one anyone could hold.

JwtVerifier

Verifies compact JWS tokens and checks their claims, reusing its buffers: make one per thread and call verify per token. The settings are public fields, read on every verify. After JWT_OK, claims[0 .. claimsLen) is the payload's JSON for the caller's own claims, and exp, nbf and iat hold the time claims when hasExp, hasNbf and hasIat say so. claims and sig are the verifier's own buffers, not copies: the next verify overwrites them.

class JwtVerifier
Member
new JwtVerifier(maxToken: i32) A verifier for tokens of up to maxToken bytes; outside [16, JWT_MAX_TOKEN_LIMIT] panics. Every buffer is allocated here, once.
audience: string | null The audience a token's aud must name, or null to refuse a token with any aud.
readonly claims: u8[] The decoded payload of the last token, claimsLen bytes of it valid after JWT_OK.
claimsLen: i32 How many bytes of claims are the payload: its length after JWT_OK, 0 after any refusal.
exp: i64 The last token's exp, in seconds since 1970; meaningful only when hasExp.
hasExp: boolean Whether the last token's payload carried exp. Cleared at the start of each verify and set as the claims are read, so a token refused for its claims may leave it set.
hasIat: boolean Whether the last token's payload carried iat, as hasExp.
hasNbf: boolean Whether the last token's payload carried nbf, as hasExp.
iat: i64 The last token's iat, in seconds since 1970; meaningful only when hasIat.
issuer: string | null The iss a token must carry, or null for any.
leeway: i64 Seconds of clock skew allowed to exp, nbf and iat; held to [0, 2^31 - 1].
readonly maxToken: i32 The largest token taken, in bytes.
nbf: i64 The last token's nbf, in seconds since 1970; meaningful only when hasNbf.
requireExp: boolean Whether a token without exp is refused; on by default.
readonly sig: u8[] The last token's signature, decoded, at the front; JWT_MAX_SIGNATURE bytes long, whatever the signature's own length. It is written only once the header passes, so after a refusal before that it still holds an earlier token's bytes.
subject: string | null The sub a token must carry, or null for any.
typ: string | null The header typ a token must carry (RFC 8725 §3.11), or null for any.
peekKid(src: u8[], off: i32, len: i32, out: u8[]): i32 The header's kid of the token src[off .. off + len), written at out[0 ..): its length, or -1 when the token is malformed, has no kid or its kid does not fit out. This reads the header before any signature is checked, so it only chooses which key to verify with; the kid proves nothing until verify answers JWT_OK under that key.
verify(key: JwtKey, src: u8[], off: i32, len: i32, now: i64): i32 Verifies the token src[off .. off + len) under key and checks its claims at now (seconds since 1970): JWT_OK, or the first JWT_ERR_* that applies, in this order:
- the window (JWT_ERR_SIZE);
- the three parts and the header's base64url (JWT_ERR_FORMAT);
- the header's members in the order written (JWT_ERR_HEADER, JWT_ERR_ALG), then a missing alg and, when the verifier names a typ, a missing or other one;
- signature text too long for any signature (JWT_ERR_SIGNATURE);
- the signature's base64url (JWT_ERR_FORMAT);
- its length, the key's fit and the signature itself (JWT_ERR_SIGNATURE);
- the payload's base64url (JWT_ERR_FORMAT);
- the payload's members in the order written and, while requireExp is set (the default), a missing exp (JWT_ERR_CLAIMS);
- and then exp, nbf, iat, iss, aud and sub, in that order.
verifyString(key: JwtKey, token: string, now: i64): i32 verify on the bytes of token, copied into the verifier's own buffer first; a token longer than maxToken is refused before the copy.

Limits

8,192

JWT_MAX_TOKEN: i32

The longest token a default JwtVerifier takes, in bytes.

1,048,576

JWT_MAX_TOKEN_LIMIT: i32

The longest token any JwtVerifier takes: 1 MiB.

Constants

9

JWT_ALG_EDDSA: i32

Ed25519 (RFC 8037 §3.1).

7

JWT_ALG_ES256: i32

ECDSA on P-256 with SHA-256 (RFC 7518 §3.4).

8

JWT_ALG_ES384: i32

ECDSA on P-384 with SHA-384.

1

JWT_ALG_HS256: i32

HMAC with SHA-256 (RFC 7518 §3.2).

2

JWT_ALG_HS384: i32

HMAC with SHA-384.

3

JWT_ALG_HS512: i32

HMAC with SHA-512.

4

JWT_ALG_RS256: i32

RSASSA-PKCS1-v1_5 with SHA-256 (RFC 7518 §3.3).

5

JWT_ALG_RS384: i32

RSASSA-PKCS1-v1_5 with SHA-384.

6

JWT_ALG_RS512: i32

RSASSA-PKCS1-v1_5 with SHA-512.

-4

JWT_ERR_ALG: i32

The header's alg is missing, is not a string, or is not the key's algorithm (none included).

-11

JWT_ERR_AUDIENCE: i32

aud does not name the verifier's audience, or is present when the verifier names none.

-6

JWT_ERR_CLAIMS: i32

The payload is not a JSON object, repeats or mistypes a registered claim, or lacks exp.

-7

JWT_ERR_EXPIRED: i32

exp has passed.

-2

JWT_ERR_FORMAT: i32

Not three base64url parts joined by two dots.

-3

JWT_ERR_HEADER: i32

The header is not a JSON object, repeats a member, or names crit or b64.

-9

JWT_ERR_IAT: i32

iat is in the future.

-10

JWT_ERR_ISSUER: i32

iss is missing or not the verifier's issuer.

-8

JWT_ERR_NOT_YET: i32

nbf has not come.

-5

JWT_ERR_SIGNATURE: i32

The signature is the wrong length or does not verify.

-1

JWT_ERR_SIZE: i32

The token is longer than the verifier takes, or its window is outside its array.

-12

JWT_ERR_SUBJECT: i32

sub is missing or not the verifier's subject.

-13

JWT_ERR_TYPE: i32

The header's typ is not the verifier's typ.

0

JWT_OK: i32

The token verified and every claim check passed.