샘플
jose 6.2.4: jwtDecrypt
검증된 샘플 — npm jose 6.2.4: jwtDecrypt. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: jwtDecrypt decrypts direct symmetric encrypted JWE tokens…
sha256:c058a0109aced61a1acbfac63985f6016636a9b849b0ad7bd9b7119f0326f07d
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
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);
});
오리진 시더
익명