JWT¶
The built-in JWT verifier: an algorithm allowlist that defeats confusion attacks, claim validation, identity mapping, issuing tokens with signJwt, and the error codes a rejection produces.
@typeix/resty-security ships a JWT verifier with no dependencies — node:crypto only. It is deliberately small: verify a compact JWS, validate the claims you asked for, map the payload to an Identity.
import {JwtVerifier} from "@typeix/resty-security";
const verifier = new JwtVerifier({
algorithms: ["HS256"],
secret: process.env.JWT_SECRET,
issuer: "https://auth.example.com",
audience: "api"
});
const identity = await verifier.resolve(token); // Identity or null
resolve answers null for any failure — bad signature, expired, wrong audience. Use verify when the caller needs to know why:
try {
const {header, claims} = await verifier.verify(token);
} catch (error) {
if (error instanceof JwtError) {
error.code; // "signature" | "expired" | "algorithm" | …
}
}
Options¶
Every field is opt-in: what is not configured is not enforced.
| Option | Type | Default | Description |
|---|---|---|---|
algorithms | string[] | required | accepted algorithms; the header alg must be one of them |
secret | string \| Buffer | – | HMAC secret for HS* |
publicKey | string \| Buffer | – | PEM public key for RS* |
issuer | string | – | expected iss |
audience | string \| string[] | – | expected aud, matches any of the list |
clockTolerance | number | 0 | allowed skew in seconds for exp and nbf |
minValidity | number | 0 | reject a token that expires in fewer than this many seconds |
now | () => number | – | current time in seconds, injectable for tests |
grantsClaim | string | grants | claim holding the grants |
attributesClaim | string | attributes | claim holding the attributes |
rolePrefix | string | – | prefix added to a grant that does not already carry it |
mapClaims | (claims, header) => Identity | – | build the identity yourself; wins over the mapping |
Supported algorithms are HS256, HS384, HS512, RS256, RS384, RS512. Anything else — including none, ES*, PS* and EdDSA — is refused at construction, so a misconfiguration cannot become a request-time surprise.
The allowlist is the point¶
algorithms is required, and the header alg is only ever checked against that list — never used to pick a verification path. That is what defeats algorithm confusion: a service configured for RS256 must not accept an HS256 token that an attacker HMAC-signed using the public key it already has.
| Attack | Result |
|---|---|
alg: none, with or without a signature | rejected at construction (none is not a supported algorithm) |
HS256 token signed with the RSA public key, against RS256 config | algorithm |
RS256 token whose header alg was edited to HS256 | algorithm |
| a token signed with another secret | signature |
| an expired token | expired |
These are covered by the package test suite with forged tokens, not with self-signed happy paths.
Claim validation¶
| Claim | Checked when | Failure code |
|---|---|---|
exp | always, when present | expired (or expiring under minValidity) |
nbf | always, when present | not-before |
iss | issuer is set | issuer |
aud | audience is set | audience |
sub | always | claims when missing |
clockTolerance widens exp and nbf in both directions, which matters when several hosts issue and verify:
const verifier = new JwtVerifier({
algorithms: ["HS256"],
secret: SECRET,
clockTolerance: 30 // accept a token for 30 s after it expires, and 30 s early
});
minValidity is the opposite: it rejects a token that will expire soon, which is useful on long-running operations that would otherwise fail halfway through.
const verifier = new JwtVerifier({
algorithms: ["HS256"],
secret: SECRET,
minValidity: 60 // a token with less than a minute left is rejected now
});
Mapping the payload to an identity¶
| Claim | Identity field | Notes |
|---|---|---|
sub | name | required; a missing subject is a claims failure |
grants (configurable) | grants | a string array; non-string entries are dropped |
attributes (configurable) | attributes | must be a plain object |
iat | issuedAt | seconds → milliseconds |
exp | expiresAt | seconds → milliseconds |
{
"sub": "ada",
"iss": "https://auth.example.com",
"aud": "api",
"exp": 1893456000,
"grants": ["ROLE_EDITOR", "article:write"],
"attributes": {"tenant": "acme"}
}
With that token, identified() is true, inGrant('EDITOR') matches, may('article:write') matches, and identity.tenant == 'acme' matches.
When the token shape is not yours to choose, mapClaims overrides the mapping entirely:
const verifier = new JwtVerifier({
algorithms: ["RS256"],
publicKey: PUBLIC_KEY,
mapClaims: async (claims, header) => identityOf({
name: claims.email,
grants: claims.permissions ?? [],
attributes: {tenant: claims.org}
})
});
Wiring it into the application¶
JwtTokenChecker plugs a verifier into a DefaultAuthenticator. A rejected token answers null, so a bad token ends up as a 401 from the chain — never an exception, never a 500.
@SecurityConfiguration({
authenticator: (authenticator: DefaultAuthenticator) => authenticator
.add(new JwtTokenChecker(new JwtVerifier({
algorithms: ["HS256"],
secret: process.env.JWT_SECRET,
issuer: "https://auth.example.com",
audience: "api"
}))),
guards: guards => guards.anyRequest("identified()")
})
@RootModule({shared_providers: [DefaultAuthenticator], controllers: [ArticlesController]})
class Application {}
Combined with password login, order decides precedence between the two token sources, but not between login and token — they are different kinds:
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
.add(new JwtTokenChecker(verifier)) // kind "token"
.add(new LoginChecker(store, new ScryptPasswordHasher())) // kind "login"
Issuing tokens¶
signJwt exists so issuing and verifying agree on the exact encoding, and so tests never build a token by hand — a hand-built token would verify the implementation against itself.
import {signJwt} from "@typeix/resty-security";
const token = signJwt({
sub: "ada",
iss: "https://auth.example.com",
aud: "api",
grants: ["ROLE_EDITOR"]
}, {
algorithm: "HS256",
secret: process.env.JWT_SECRET,
expiresIn: 3600, // sets exp, seconds from now
issuedAt: 0, // sets iat
header: {kid: "2026-01"}
});
| Option | Default | Description |
|---|---|---|
algorithm | HS256 | HS* or RS* |
secret | – | required for HS* |
privateKey | – | required for RS* |
expiresIn | – | seconds from now; sets exp only when the claim is absent |
issuedAt | – | seconds from now; sets iat only when the claim is absent |
header | – | extra header fields, e.g. kid |
none is never produced, and an unsupported algorithm throws jwt: cannot sign with "…".
Verification in tests¶
now makes the clock deterministic, which is how expiry is tested without waiting:
let clock = 1_700_000_000;
const verifier = new JwtVerifier({
algorithms: ["HS256"],
secret: SECRET,
now: () => clock
});
const token = signJwt({sub: "ada", exp: clock + 10}, {secret: SECRET});
await verifier.resolve(token); // identity
clock += 11;
await verifier.resolve(token); // null, expired
Error codes¶
| Code | Meaning |
|---|---|
config | the verifier was constructed with an unusable policy (missing allowlist, missing key, unsupported algorithm) |
malformed | not three dot-separated parts, invalid base64url, invalid JSON, or a part that is not an object |
algorithm | the header alg is not in algorithms |
signature | the signature does not match |
claims | a claim has the wrong type, or sub is missing |
expired | exp is in the past |
expiring | minValidity is set and the token expires too soon |
not-before | nbf is in the future |
issuer | iss does not match |
audience | aud does not match |
Next¶
- Credentials — the other checkers
- Authenticator — registering the checker
- Testing — asserting a rejection end to end