Пример
jose 6.2.18
Проверенный пример — npm jose 6.2.18. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: SignJWT and jwtVerify sign and verify an HS256…
sha256:37b7e95dafe5051ddaf64bec86cfaebdfed35848f6fc100e942e5e74c30b6f1b
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-11-28 |
Кейс
HOW- Цель
- verify pkg:npm/jose@6.2.18
- Пакеты
- Окружение
- node 22.23.2
- Создан
- 2026-11-28T03:35:18Z
Контракт
- SignJWT and jwtVerify sign and verify an HS256 compact 3-part JWT with a generated CryptoKey secret and return { payload, protectedHeader }
- decodeProtectedHeader and decodeJwt inspect the protected header and claims of a compact JWT without verifying its signature
- generateKeyPair('ES256'), exportJWK, and createLocalJWKSet resolve a verification key offline by kid and return { payload, protectedHeader, key }
- createLocalJWKSet rejects a token whose kid does not match any key with errors.JWKSNoMatchingKey and code ERR_JWKS_NO_MATCHING_KEY
- jwtVerify rejects an expired token with errors.JWTExpired (not instanceof JWTClaimValidationFailed), code ERR_JWT_EXPIRED, claim 'exp', reason 'check_failed', and attached payload, while clockTolerance allows the token
- jwtVerify rejects an issuer mismatch with errors.JWTClaimValidationFailed, code ERR_JWT_CLAIM_VALIDATION_FAILED, claim 'iss', and reason 'check_failed'
- jwtVerify rejects a token verified with the wrong symmetric key with errors.JWSSignatureVerificationFailed and code ERR_JWS_SIGNATURE_VERIFICATION_FAILED
- jwtVerify rejects an algorithm excluded by options.algorithms with errors.JOSEAlgNotAllowed and code ERR_JOSE_ALG_NOT_ALLOWED
- EncryptJWT and jwtDecrypt round-trip a 5-part compact JWE JWT using dir + A256GCM and reject decryption with a wrong key via errors.JWEDecryptionFailed and code ERR_JWE_DECRYPTION_FAILED
Файлы
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Исходный код
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify pkg:npm/jose@6.2.18
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jose@6.2.18
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:8258765b0a481caca2bd3541c036d7105a8ec6907cd67c20de24112db66b90a9","constraints":{"executionContext":"node"},"contract":["SignJWT and jwtVerify sign and verify an HS256 compact 3-part JWT with a generated CryptoKey secret and return { payload, protectedHeader }","decodeProtectedHeader and decodeJwt inspect the protected header and claims of a compact JWT without verifying its signature","generateKeyPair('ES256'), exportJWK, and createLocalJWKSet resolve a verification key offline by kid and return { payload, protectedHeader, key }","createLocalJWKSet rejects a token whose kid does not match any key with errors.JWKSNoMatchingKey and code ERR_JWKS_NO_MATCHING_KEY","jwtVerify rejects an expired token with errors.JWTExpired (not instanceof JWTClaimValidationFailed), code ERR_JWT_EXPIRED, claim 'exp', reason 'check_failed', and attached payload, while clockTolerance allows the token","jwtVerify rejects an issuer mismatch with errors.JWTClaimValidationFailed, code ERR_JWT_CLAIM_VALIDATION_FAILED, claim 'iss', and reason 'check_failed'","jwtVerify rejects a token verified with the wrong symmetric key with errors.JWSSignatureVerificationFailed and code ERR_JWS_SIGNATURE_VERIFICATION_FAILED","jwtVerify rejects an algorithm excluded by options.algorithms with errors.JOSEAlgNotAllowed and code ERR_JOSE_ALG_NOT_ALLOWED","EncryptJWT and jwtDecrypt round-trip a 5-part compact JWE JWT using dir + A256GCM and reject decryption with a wrong key via errors.JWEDecryptionFailed and code ERR_JWE_DECRYPTION_FAILED"],"goal":"verify pkg:npm/jose@6.2.18","kind":"HOW","packages":["pkg:npm/jose@6.2.18"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jose@6.2.18"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.18","verifierAdapter":"node-typescript@1"}
{
"name": "jose-verify-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jose-verify-sample",
"version": "1.0.0",
"dependencies": {
"jose": "6.2.18"
}
},
"node_modules/jose": {
"version": "6.2.18",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz",
"integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
}
}
}
{
"name": "jose-verify-sample",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"jose": "6.2.18"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/jose@6.2.18",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.18"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
import {
EncryptJWT,
SignJWT,
createLocalJWKSet,
exportJWK,
jwtDecrypt,
jwtVerify,
} from 'jose';
export async function issueSignedJwt(claims, key, options) {
const {
alg,
kid,
issuer,
audience,
subject,
issuedAt,
expirationTime,
notBefore,
} = options;
const header = kid ? { alg, kid } : { alg };
const builder = new SignJWT(claims).setProtectedHeader(header);
if (issuer !== undefined) builder.setIssuer(issuer);
if (audience !== undefined) builder.setAudience(audience);
if (subject !== undefined) builder.setSubject(subject);
if (issuedAt !== undefined) builder.setIssuedAt(issuedAt);
if (expirationTime !== undefined) builder.setExpirationTime(expirationTime);
if (notBefore !== undefined) builder.setNotBefore(notBefore);
return builder.sign(key);
}
export async function verifySignedJwt(token, keyOrResolver, options) {
return jwtVerify(token, keyOrResolver, options);
}
export async function buildLocalJwks(entries) {
const keys = await Promise.all(
entries.map(async ({ publicKey, kid, alg }) => {
const jwk = await exportJWK(publicKey);
return { ...jwk, kid, alg, use: 'sig' };
}),
);
return createLocalJWKSet({ keys });
}
export async function encryptClaims(claims, key, options) {
const { alg, enc, issuer, audience, issuedAt, expirationTime } = options;
const builder = new EncryptJWT(claims).setProtectedHeader({ alg, enc });
if (issuer !== undefined) builder.setIssuer(issuer);
if (audience !== undefined) builder.setAudience(audience);
if (issuedAt !== undefined) builder.setIssuedAt(issuedAt);
if (expirationTime !== undefined) builder.setExpirationTime(expirationTime);
return builder.encrypt(key);
}
export async function decryptClaims(token, key, options) {
return jwtDecrypt(token, key, options);
}
import assert from 'node:assert/strict';
import {
decodeJwt,
decodeProtectedHeader,
errors,
generateKeyPair,
generateSecret,
} from 'jose';
import {
buildLocalJwks,
decryptClaims,
encryptClaims,
issueSignedJwt,
verifySignedJwt,
} from '../src/index.mjs';
const BASE_TIME = 1_700_000_000;
const NOW = new Date(BASE_TIME * 1000);
const ISSUER = 'urn:example:issuer';
const AUDIENCE = 'urn:example:audience';
// 1. Symmetric HS256 signing and verification
const hsKey = await generateSecret('HS256');
const hsToken = await issueSignedJwt({ role: 'reader' }, hsKey, {
alg: 'HS256',
issuer: ISSUER,
audience: AUDIENCE,
subject: 'user-1',
issuedAt: BASE_TIME,
expirationTime: BASE_TIME + 300,
});
assert.equal(hsToken.split('.').length, 3);
const hsVerified = await verifySignedJwt(hsToken, hsKey, {
issuer: ISSUER,
audience: AUDIENCE,
currentDate: NOW,
});
assert.equal(hsVerified.protectedHeader.alg, 'HS256');
assert.equal(hsVerified.payload.sub, 'user-1');
assert.equal(hsVerified.payload.role, 'reader');
// 2. Unverified header and claims decoding
assert.equal(decodeProtectedHeader(hsToken).alg, 'HS256');
assert.equal(decodeJwt(hsToken).role, 'reader');
// 3. Asymmetric ES256 signing + offline local JWKS resolution by kid
const { privateKey: esPrivateKey, publicKey: esPublicKey } = await generateKeyPair('ES256');
const localJwks = await buildLocalJwks([
{ publicKey: esPublicKey, kid: 'signing-key-1', alg: 'ES256' },
]);
const esToken = await issueSignedJwt({ scope: 'items:read' }, esPrivateKey, {
alg: 'ES256',
kid: 'signing-key-1',
issuer: ISSUER,
audience: AUDIENCE,
issuedAt: BASE_TIME,
expirationTime: BASE_TIME + 300,
});
const jwksVerified = await verifySignedJwt(esToken, localJwks, {
issuer: ISSUER,
audience: AUDIENCE,
algorithms: ['ES256'],
currentDate: NOW,
});
assert.equal(jwksVerified.protectedHeader.kid, 'signing-key-1');
assert.equal(jwksVerified.payload.scope, 'items:read');
assert.ok(jwksVerified.key);
// 4. Unknown kid fails with JWKSNoMatchingKey
const unknownKidToken = await issueSignedJwt({ scope: 'items:read' }, esPrivateKey, {
alg: 'ES256',
kid: 'missing-key',
issuer: ISSUER,
issuedAt: BASE_TIME,
expirationTime: BASE_TIME + 300,
});
await assert.rejects(
() => verifySignedJwt(unknownKidToken, localJwks, { currentDate: NOW }),
(err) => err instanceof errors.JWKSNoMatchingKey && err.code === 'ERR_JWKS_NO_MATCHING_KEY',
);
// 5. Expired token fails with JWTExpired (sibling of JWTClaimValidationFailed), clockTolerance allows it
const expiredToken = await issueSignedJwt({ step: 'expired' }, hsKey, {
alg: 'HS256',
issuer: ISSUER,
issuedAt: BASE_TIME - 120,
expirationTime: BASE_TIME - 10,
});
await assert.rejects(
() => verifySignedJwt(expiredToken, hsKey, { issuer: ISSUER, currentDate: NOW }),
(err) =>
err instanceof errors.JWTExpired &&
!(err instanceof errors.JWTClaimValidationFailed) &&
err.code === 'ERR_JWT_EXPIRED' &&
err.claim === 'exp' &&
err.reason === 'check_failed' &&
err.payload.step === 'expired',
);
const tolerated = await verifySignedJwt(expiredToken, hsKey, {
issuer: ISSUER,
currentDate: NOW,
clockTolerance: 15,
});
assert.equal(tolerated.payload.step, 'expired');
// 6. Issuer mismatch fails with JWTClaimValidationFailed
await assert.rejects(
() => verifySignedJwt(hsToken, hsKey, { issuer: 'urn:example:other', currentDate: NOW }),
(err) =>
err instanceof errors.JWTClaimValidationFailed &&
err.code === 'ERR_JWT_CLAIM_VALIDATION_FAILED' &&
err.claim === 'iss' &&
err.reason === 'check_failed',
);
// 7. Wrong verification key fails with JWSSignatureVerificationFailed
const otherHsKey = await generateSecret('HS256');
await assert.rejects(
() => verifySignedJwt(hsToken, otherHsKey, { currentDate: NOW }),
(err) =>
err instanceof errors.JWSSignatureVerificationFailed &&
err.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED',
);
// 8. Disallowed algorithm fails with JOSEAlgNotAllowed
await assert.rejects(
() => verifySignedJwt(esToken, esPublicKey, { algorithms: ['RS256'], currentDate: NOW }),
(err) => err instanceof errors.JOSEAlgNotAllowed && err.code === 'ERR_JOSE_ALG_NOT_ALLOWED',
);
// 9. Compact JWE JWT encryption and decryption round-trip + wrong-key rejection
const encKey = await generateSecret('A256GCM');
const wrongEncKey = await generateSecret('A256GCM');
const jweToken = await encryptClaims({ opaqueField: 'value-42' }, encKey, {
alg: 'dir',
enc: 'A256GCM',
issuer: ISSUER,
audience: AUDIENCE,
issuedAt: BASE_TIME,
expirationTime: BASE_TIME + 300,
});
assert.equal(jweToken.split('.').length, 5);
const decrypted = await decryptClaims(jweToken, encKey, {
issuer: ISSUER,
audience: AUDIENCE,
currentDate: NOW,
});
assert.equal(decrypted.protectedHeader.alg, 'dir');
assert.equal(decrypted.protectedHeader.enc, 'A256GCM');
assert.equal(decrypted.payload.opaqueField, 'value-42');
await assert.rejects(
() => decryptClaims(jweToken, wrongEncKey, { currentDate: NOW }),
(err) => err instanceof errors.JWEDecryptionFailed && err.code === 'ERR_JWE_DECRYPTION_FAILED',
);
console.log('jose@6.2.18 contract passed');
Исходный сидер
аноним