Ejemplo
jose 6.2.9: Setting maxTokenAge in jwtVerify enforces mandatory presence of the iat claim, rejecting tokens without iat via JWTClaimValidationFailed even if unexpired by exp, and rejects future iat timestamps unless clockTolerance is configured.
Muestra verificada para npm jose 6.2.9: Setting maxTokenAge in jwtVerify enforces mandatory presence of the iat claim, rejecting tokens without iat via…
sha256:c6472d96d7e2e72142939fca93662b5d075d9d1c3adbbc3c931bef9e445d6d93
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 3
- Claves de firma que lo compilaron
- 3
Entorno declarado
node linux x64 node node npm
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-07 |
Caso
HOW- Objetivo
- Setting maxTokenAge in jwtVerify enforces mandatory presence of the iat claim, rejecting tokens without iat via JWTClaimValidationFailed even if unexpired by exp, and rejects future iat timestamps unless clockTolerance is configured.
- Paquetes
- Símbolos
-
- jwtVerify
- Entorno
- node
- Creado
- 2026-08-17T11:14:47Z
Contrato
- jwtVerify with maxTokenAge configured rejects tokens lacking an iat claim with JWTClaimValidationFailed and reason 'missing' rather than falling back to exp validation.
- jwtVerify with maxTokenAge rejects future iat timestamps with JWTClaimValidationFailed and reason 'check_failed' unless clockTolerance absorbs the clock skew.
- jwtVerify with maxTokenAge throws JWTExpired with claim 'iat' when current time exceeds iat plus maxTokenAge, even if the exp claim has not expired.
- jwtVerify accepts valid tokens whose age is within maxTokenAge bounds.
- jwtVerify rejects unsupported duration units such as milliseconds ('500ms') in maxTokenAge with a TypeError.
Archivos
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
Código fuente
# jose `maxTokenAge` Verification and Required Claims
## Prior Solution Search
`search_known_solution` returned no prior samples for `jose` configuration options or `maxTokenAge` claim enforcement.
## Pinned Release
- `jose`: `6.2.9`
## Observed Behavior
When configuring `maxTokenAge` in `jwtVerify(jwt, key, options)`:
1. **Implicit Required Claim Enforcement**:
Setting `maxTokenAge` (e.g. `'1h'`) automatically adds `'iat'` (Issued At) to the list of mandatory claims during claims validation. If a JWT does not contain an `iat` claim—even if it contains a valid future expiration timestamp (`exp`) and a valid cryptographic signature—`jwtVerify` rejects the token by throwing `errors.JWTClaimValidationFailed` with error code `ERR_JWT_CLAIM_VALIDATION_FAILED`, claim `'iat'`, and reason `'missing'`.
2. **Future Timestamp Rejection**:
If a token contains an `iat` timestamp in the future (such as from server clock drift between the issuer and verifier), `jwtVerify` rejects the token with `JWTClaimValidationFailed` and reason `'check_failed'` (`"iat" claim timestamp check failed (it should be in the past)`). To tolerate clock drift, `clockTolerance` must be configured alongside `maxTokenAge`.
3. **Max Age Expiration vs Standard Expiration**:
When the token age (`now - iat`) exceeds `maxTokenAge`, `jwtVerify` throws `errors.JWTExpired` with claim `'iat'` and reason `'check_failed'`, even if the token's standard `exp` claim is still in the future.
4. **Duration Unit Parsing**:
Duration strings accept units of seconds (`s`), minutes (`m`), hours (`h`), days (`d`), weeks (`w`), and years (`y`). Sub-second units like milliseconds (`500ms`) are not supported by the duration parser and reject with `TypeError: Invalid time period format`.
## Failure Mode Under Naive Expectations
A naive expectation is that `maxTokenAge: '1h'` acts as an optional freshness ceiling, evaluating token age when an `iat` claim is present and falling back to standard `exp` validation when `iat` is omitted. Under this expectation, verifying a valid, unexpired token that lacks an `iat` claim fails loudly with `JWTClaimValidationFailed` (`ERR_JWT_CLAIM_VALIDATION_FAILED`, reason `'missing'`).
{"case":{"believed":"Setting maxTokenAge only limits allowable token age when an iat claim is present, falling back to exp expiration checking when iat is omitted.","caseId":"case:sha256:4a5cfa17ce10e6139d24583c3ed7964367bcc180c567c00b2dcb75a7038f0fe1","contract":["jwtVerify with maxTokenAge configured rejects tokens lacking an iat claim with JWTClaimValidationFailed and reason 'missing' rather than falling back to exp validation.","jwtVerify with maxTokenAge rejects future iat timestamps with JWTClaimValidationFailed and reason 'check_failed' unless clockTolerance absorbs the clock skew.","jwtVerify with maxTokenAge throws JWTExpired with claim 'iat' when current time exceeds iat plus maxTokenAge, even if the exp claim has not expired.","jwtVerify accepts valid tokens whose age is within maxTokenAge bounds.","jwtVerify rejects unsupported duration units such as milliseconds ('500ms') in maxTokenAge with a TypeError."],"goal":"Setting maxTokenAge in jwtVerify enforces mandatory presence of the iat claim, rejecting tokens without iat via JWTClaimValidationFailed even if unexpired by exp, and rejects future iat timestamps unless clockTolerance is configured.","kind":"HOW","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"symbols":["jwtVerify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"symbols":["jwtVerify"],"verifierAdapter":"node-typescript@1"}
{
"name": "jose-config-maxtokenage",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jose-config-maxtokenage",
"version": "1.0.0",
"dependencies": {
"jose": "6.2.9"
}
},
"node_modules/jose": {
"version": "6.2.9",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.9.tgz",
"integrity": "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
}
}
}
{
"name": "jose-config-maxtokenage",
"version": "1.0.0",
"type": "module",
"dependencies": {
"jose": "6.2.9"
}
}
import * as jose from 'jose';
import assert from 'node:assert/strict';
async function run() {
const secret = new TextEncoder().encode('secret-key-must-be-at-least-32-bytes-long');
const now = 1700000000;
const fixedDate = new Date(now * 1000);
// 1. Missing 'iat' claim:
// A naive expectation is that maxTokenAge only checks age when 'iat' is present,
// falling back to standard expiration ('exp') checking when 'iat' is omitted.
// In reality, configuring maxTokenAge turns 'iat' into a strictly required claim.
const tokenWithoutIat = await new jose.SignJWT({ sub: 'user_42' })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime(now + 3600)
.sign(secret);
// Without maxTokenAge, verification succeeds
const verifiedWithoutOption = await jose.jwtVerify(tokenWithoutIat, secret, {
currentDate: fixedDate,
});
assert.equal(verifiedWithoutOption.payload.sub, 'user_42');
// With maxTokenAge configured, verification fails because 'iat' is missing
await assert.rejects(
async () => jose.jwtVerify(tokenWithoutIat, secret, {
maxTokenAge: '1h',
currentDate: fixedDate,
}),
(err) => {
assert(err instanceof jose.errors.JWTClaimValidationFailed);
assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
assert.equal(err.claim, 'iat');
assert.equal(err.reason, 'missing');
assert.equal(err.message, 'missing required "iat" claim');
return true;
}
);
// 2. Future 'iat' timestamp (clock skew):
// When 'iat' is in the future, maxTokenAge rejects it as invalid rather than computing negative age.
const tokenFutureIat = await new jose.SignJWT({ sub: 'user_42' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt(now + 30)
.setExpirationTime(now + 3600)
.sign(secret);
await assert.rejects(
async () => jose.jwtVerify(tokenFutureIat, secret, {
maxTokenAge: '1h',
currentDate: fixedDate,
}),
(err) => {
assert(err instanceof jose.errors.JWTClaimValidationFailed);
assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
assert.equal(err.claim, 'iat');
assert.equal(err.reason, 'check_failed');
assert.equal(err.message, '"iat" claim timestamp check failed (it should be in the past)');
return true;
}
);
// Future 'iat' is accepted if clockTolerance is configured to cover the skew
const verifiedWithTolerance = await jose.jwtVerify(tokenFutureIat, secret, {
maxTokenAge: '1h',
currentDate: fixedDate,
clockTolerance: '60s',
});
assert.equal(verifiedWithTolerance.payload.sub, 'user_42');
// 3. Stale token exceeding maxTokenAge but before exp:
// maxTokenAge invalidates the token with JWTExpired targeting 'iat', overriding future exp.
const tokenStaleIat = await new jose.SignJWT({ sub: 'user_42' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt(now - 7200)
.setExpirationTime(now + 3600)
.sign(secret);
await assert.rejects(
async () => jose.jwtVerify(tokenStaleIat, secret, {
maxTokenAge: '1h',
currentDate: fixedDate,
}),
(err) => {
assert(err instanceof jose.errors.JWTExpired);
assert.equal(err.code, 'ERR_JWT_EXPIRED');
assert.equal(err.claim, 'iat');
assert.equal(err.reason, 'check_failed');
assert.equal(err.message, '"iat" claim timestamp check failed (too far in the past)');
return true;
}
);
// 4. Valid token within maxTokenAge bounds:
const tokenValid = await new jose.SignJWT({ sub: 'user_42' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt(now - 1800)
.setExpirationTime(now + 3600)
.sign(secret);
const verifiedValid = await jose.jwtVerify(tokenValid, secret, {
maxTokenAge: '1h',
currentDate: fixedDate,
});
assert.equal(verifiedValid.payload.sub, 'user_42');
// 5. Unsupported duration unit:
// jose supports s, m, h, d, w, y units; sub-second units like milliseconds ('500ms') reject with TypeError.
await assert.rejects(
async () => jose.jwtVerify(tokenValid, secret, {
maxTokenAge: '500ms',
currentDate: fixedDate,
}),
(err) => {
assert(err instanceof TypeError);
assert.equal(err.message, 'Invalid time period format');
return true;
}
);
}
run();