示例
jose 6.2.4: jwtDecrypt
已验证示例 — npm jose 6.2.4: jwtDecrypt. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: jwtDecrypt decrypts direct symmetric encrypted JWE tokens and…
sha256:c058a0109aced61a1acbfac63985f6016636a9b849b0ad7bd9b7119f0326f07d
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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-08-28 |
案例
HOW- 目标
- verify jose.jwtDecrypt in pkg:npm/jose@6.2.4
- 符号
-
- jose.jwtDecrypt
- 环境
- node 22.23.2
- 创建时间
- 2026-08-28T03:26:37Z
契约
- jwtDecrypt decrypts direct symmetric encrypted JWE tokens and returns the payload and protected header
- jwtDecrypt decrypts asymmetric encrypted JWE tokens using RSA-OAEP-256 private keys
- jwtDecrypt validates standard JWT claims including issuer, audience, and subject options
- jwtDecrypt throws JWTClaimValidationFailed when expected claim validation fails
- jwtDecrypt throws JWTExpired when the token expiration timestamp is in the past
- jwtDecrypt throws JWEDecryptionFailed when decrypting with an incorrect secret key or mismatched ciphertext
- jwtDecrypt throws JOSEAlgNotAllowed when the token algorithm does not match the keyManagementAlgorithms constraint
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.js
源代码
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 jose.jwtDecrypt in pkg:npm/jose@6.2.4
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jose@6.2.4
Demonstrate these symbols/APIs:
- jose.jwtDecrypt
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:f0fa914c6de6c99477606f419ea05cfb92517336089bb847a078220def548b4c","constraints":{"executionContext":"node"},"contract":["jwtDecrypt decrypts direct symmetric encrypted JWE tokens and returns the payload and protected header","jwtDecrypt decrypts asymmetric encrypted JWE tokens using RSA-OAEP-256 private keys","jwtDecrypt validates standard JWT claims including issuer, audience, and subject options","jwtDecrypt throws JWTClaimValidationFailed when expected claim validation fails","jwtDecrypt throws JWTExpired when the token expiration timestamp is in the past","jwtDecrypt throws JWEDecryptionFailed when decrypting with an incorrect secret key or mismatched ciphertext","jwtDecrypt throws JOSEAlgNotAllowed when the token algorithm does not match the keyManagementAlgorithms constraint"],"goal":"verify jose.jwtDecrypt in pkg:npm/jose@6.2.4","kind":"HOW","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"symbols":["jose.jwtDecrypt"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","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.4"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.4","symbols":["jose.jwtDecrypt"],"verifierAdapter":"node-typescript@1"}
{
"name": "jose-jwt-decrypt-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jose-jwt-decrypt-sample",
"version": "1.0.0",
"dependencies": {
"jose": "6.2.4"
}
},
"node_modules/jose": {
"version": "6.2.4",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.4.tgz",
"integrity": "sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
}
}
}
{
"name": "jose-jwt-decrypt-sample",
"version": "1.0.0",
"dependencies": {
"jose": "6.2.4"
}
}
{
"schemaVersion": 1,
"goal": "verify jose.jwtDecrypt in pkg:npm/jose@6.2.4",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.4"
],
"symbols": [
"jose.jwtDecrypt"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
const {
jwtDecrypt,
EncryptJWT,
generateSecret,
generateKeyPair,
errors,
} = require('jose');
/**
* Encrypts a payload into a compact JWE string using direct symmetric encryption ('dir' + 'A256GCM').
*
* @param {Record<string, any>} payload - JWT claims payload.
* @param {Uint8Array} secretKey - Symmetric secret key (32 bytes for A256GCM).
* @param {object} [options] - Additional JWT options.
* @param {string} [options.issuer] - Token issuer.
* @param {string|string[]} [options.audience] - Token audience.
* @param {string} [options.subject] - Token subject.
* @param {string|number} [options.expirationTime] - Token expiration time.
* @returns {Promise<string>} The compact JWE token string.
*/
async function createDirectJWE(payload, secretKey, options = {}) {
const encJwt = new EncryptJWT(payload)
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' });
if (options.issuer) {
encJwt.setIssuer(options.issuer);
}
if (options.audience) {
encJwt.setAudience(options.audience);
}
if (options.subject) {
encJwt.setSubject(options.subject);
}
if (options.expirationTime) {
encJwt.setExpirationTime(options.expirationTime);
}
return await encJwt.encrypt(secretKey);
}
/**
* Encrypts a payload into a compact JWE string using asymmetric key encryption ('RSA-OAEP-256' + 'A256GCM').
*
* @param {Record<string, any>} payload - JWT claims payload.
* @param {any} publicKey - Asymmetric public key.
* @param {object} [options] - Additional JWT options.
* @param {string} [options.issuer] - Token issuer.
* @param {string|string[]} [options.audience] - Token audience.
* @param {string} [options.subject] - Token subject.
* @param {string|number} [options.expirationTime] - Token expiration time.
* @returns {Promise<string>} The compact JWE token string.
*/
async function createAsymmetricJWE(payload, publicKey, options = {}) {
const encJwt = new EncryptJWT(payload)
.setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' });
if (options.issuer) {
encJwt.setIssuer(options.issuer);
}
if (options.audience) {
encJwt.setAudience(options.audience);
}
if (options.subject) {
encJwt.setSubject(options.subject);
}
if (options.expirationTime) {
encJwt.setExpirationTime(options.expirationTime);
}
return await encJwt.encrypt(publicKey);
}
/**
* Decrypts a compact JWE token string and validates its claims and algorithm constraints.
*
* @param {string} jwt - Encrypted compact JWE token.
* @param {Uint8Array|any} key - Secret key or private key for decryption.
* @param {object} [options] - Decryption and claim validation options.
* @param {string|string[]} [options.issuer] - Expected issuer(s).
* @param {string|string[]} [options.audience] - Expected audience(s).
* @param {string} [options.subject] - Expected subject.
* @param {string|number} [options.maxTokenAge] - Max age allowed for the token.
* @param {string[]} [options.keyManagementAlgorithms] - Whitelist of allowed alg values.
* @param {string[]} [options.contentEncryptionAlgorithms] - Whitelist of allowed enc values.
* @returns {Promise<{ payload: Record<string, any>, protectedHeader: Record<string, any>, key: any }>}
*/
async function decryptJWE(jwt, key, options = {}) {
return await jwtDecrypt(jwt, key, options);
}
module.exports = {
jwtDecrypt,
createDirectJWE,
createAsymmetricJWE,
decryptJWE,
generateSecret,
generateKeyPair,
errors,
};
const assert = require('node:assert/strict');
const {
jwtDecrypt,
createDirectJWE,
createAsymmetricJWE,
decryptJWE,
generateSecret,
generateKeyPair,
errors,
} = require('../src/index.js');
async function main() {
// Shared secret for symmetric encryption tests
const symmetricKey = await generateSecret('A256GCM');
// Contract 1: jwtDecrypt decrypts direct symmetric encrypted JWE tokens and returns the payload and protected header
{
const claims = { user_id: 'usr_42', role: 'admin', active: true };
const token = await createDirectJWE(claims, symmetricKey);
const result = await decryptJWE(token, symmetricKey);
assert.strictEqual(result.payload.user_id, 'usr_42');
assert.strictEqual(result.payload.role, 'admin');
assert.strictEqual(result.payload.active, true);
assert.strictEqual(result.protectedHeader.alg, 'dir');
assert.strictEqual(result.protectedHeader.enc, 'A256GCM');
}
// Contract 2: jwtDecrypt decrypts asymmetric encrypted JWE tokens using RSA-OAEP-256 private keys
{
const { publicKey, privateKey } = await generateKeyPair('RSA-OAEP-256');
const claims = { scope: 'read:profile write:settings', sub: 'asym_user_99' };
const token = await createAsymmetricJWE(claims, publicKey);
const result = await decryptJWE(token, privateKey);
assert.strictEqual(result.payload.sub, 'asym_user_99');
assert.strictEqual(result.payload.scope, 'read:profile write:settings');
assert.strictEqual(result.protectedHeader.alg, 'RSA-OAEP-256');
assert.strictEqual(result.protectedHeader.enc, 'A256GCM');
}
// Contract 3: jwtDecrypt validates standard JWT claims including issuer, audience, and subject options
{
const claims = { message: 'verified-claims' };
const token = await createDirectJWE(claims, symmetricKey, {
issuer: 'urn:codesamplex:auth',
audience: 'urn:codesamplex:api',
subject: 'sub-sample-123',
expirationTime: '1h',
});
const result = await decryptJWE(token, symmetricKey, {
issuer: 'urn:codesamplex:auth',
audience: 'urn:codesamplex:api',
subject: 'sub-sample-123',
});
assert.strictEqual(result.payload.iss, 'urn:codesamplex:auth');
assert.strictEqual(result.payload.aud, 'urn:codesamplex:api');
assert.strictEqual(result.payload.sub, 'sub-sample-123');
assert.strictEqual(result.payload.message, 'verified-claims');
}
// Contract 4: jwtDecrypt throws JWTClaimValidationFailed when expected claim validation fails
{
const token = await createDirectJWE({ test: true }, symmetricKey, {
issuer: 'urn:expected:issuer',
});
await assert.rejects(
async () => {
await decryptJWE(token, symmetricKey, {
issuer: 'urn:unmatched:issuer',
});
},
(err) => {
assert.ok(err instanceof errors.JWTClaimValidationFailed || err.code === 'ERR_JWT_CLAIM_VALIDATION_FAILED');
return true;
}
);
}
// Contract 5: jwtDecrypt throws JWTExpired when the token expiration timestamp is in the past
{
const expiredToken = await createDirectJWE({ test: 'expired' }, symmetricKey, {
expirationTime: '-30s',
});
await assert.rejects(
async () => {
await decryptJWE(expiredToken, symmetricKey);
},
(err) => {
assert.ok(err instanceof errors.JWTExpired || err.code === 'ERR_JWT_EXPIRED');
return true;
}
);
}
// Contract 6: jwtDecrypt throws JWEDecryptionFailed when decrypting with an incorrect secret key or mismatched ciphertext
{
const token = await createDirectJWE({ secret: 'data' }, symmetricKey);
const wrongKey = await generateSecret('A256GCM');
await assert.rejects(
async () => {
await decryptJWE(token, wrongKey);
},
(err) => {
assert.ok(err instanceof errors.JWEDecryptionFailed || err.code === 'ERR_JWE_DECRYPTION_FAILED');
return true;
}
);
}
// Contract 7: jwtDecrypt throws JOSEAlgNotAllowed when the token algorithm does not match the keyManagementAlgorithms constraint
{
const token = await createDirectJWE({ data: 'alg-check' }, symmetricKey);
await assert.rejects(
async () => {
await decryptJWE(token, symmetricKey, {
keyManagementAlgorithms: ['RSA-OAEP-256'],
});
},
(err) => {
assert.ok(err instanceof errors.JOSEAlgNotAllowed || err.code === 'ERR_JOSE_ALG_NOT_ALLOWED');
return true;
}
);
}
console.log('All pkg:npm/jose@6.2.4 contracts passed successfully.');
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
原始种子者
匿名