샘플
jose 6.2.4: EncryptJWT
검증된 샘플 — npm jose 6.2.4: EncryptJWT. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: EncryptJWT produces a 5-part compact encrypted JWT with…
sha256:300a831ee2bf237f60139f31290884a85f77f1a4041640c9e58eab2afdac6876
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
linux 24 · ubuntu · glibc 2.39 x64 npm
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-21 |
케이스
HOW- 목표
- verify jose.EncryptJWT in pkg:npm/jose@6.2.4
- 패키지
- 심벌
-
- jose.EncryptJWT
- 생성일
- 2026-08-21T16:55:16Z
컨트랙트
- EncryptJWT produces a 5-part compact encrypted JWT with direct symmetric encryption (dir + A256GCM) that can be decrypted with jwtDecrypt
- EncryptJWT produces an encrypted JWT using symmetric key wrapping (A256KW + A256GCM)
- EncryptJWT produces an encrypted JWT using RSA public key encryption (RSA-OAEP-256 + A128CBC-HS256)
- EncryptJWT supports dynamic key resolution via key resolver callback during decryption
- EncryptJWT enforces exp and nbf claims throwing JWTExpired or JWTClaimValidationFailed when invalid
- EncryptJWT throws JWEInvalid when attempting to encrypt without protected or unprotected headers
- EncryptJWT encrypted token fails decryption with JWEDecryptionFailed when decrypted with incorrect key or tampered ciphertext
파일
- 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 jose.EncryptJWT 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.EncryptJWT
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:fe857f357ec891e9670e641345136de09d24755fab2b1d9b1bb055b93fb2b71f","contract":["EncryptJWT produces a 5-part compact encrypted JWT with direct symmetric encryption (dir + A256GCM) that can be decrypted with jwtDecrypt","EncryptJWT produces an encrypted JWT using symmetric key wrapping (A256KW + A256GCM)","EncryptJWT produces an encrypted JWT using RSA public key encryption (RSA-OAEP-256 + A128CBC-HS256)","EncryptJWT supports dynamic key resolution via key resolver callback during decryption","EncryptJWT enforces exp and nbf claims throwing JWTExpired or JWTClaimValidationFailed when invalid","EncryptJWT throws JWEInvalid when attempting to encrypt without protected or unprotected headers","EncryptJWT encrypted token fails decryption with JWEDecryptionFailed when decrypted with incorrect key or tampered ciphertext"],"goal":"verify jose.EncryptJWT in pkg:npm/jose@6.2.4","kind":"HOW","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"symbols":["jose.EncryptJWT"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.4","symbols":["jose.EncryptJWT"],"verifierAdapter":"node-typescript@1"}
{
"name": "verify-jose-encrypt-jwt",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "verify-jose-encrypt-jwt",
"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": "verify-jose-encrypt-jwt",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"jose": "6.2.4"
}
}
{
"schemaVersion": 1,
"goal": "verify jose.EncryptJWT in pkg:npm/jose@6.2.4",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.4"
],
"symbols": [
"jose.EncryptJWT"
]
}
import { EncryptJWT, jwtDecrypt } from 'jose';
/**
* Creates and encrypts a JSON Web Token (JWT).
*
* @param {object} payload - The JWT claims set / payload object.
* @param {object} protectedHeader - The JWE protected header containing alg and enc.
* @param {Uint8Array | import('jose').KeyLike} key - The symmetric key or public key for encryption.
* @param {object} [claims] - Standard JWT claims such as issuer, subject, audience, expirationTime, etc.
* @returns {Promise<string>} The compact encrypted JWT string.
*/
export async function createEncryptedJWT(payload, protectedHeader, key, claims = {}) {
const jwt = new EncryptJWT(payload);
if (protectedHeader) {
jwt.setProtectedHeader(protectedHeader);
}
if (claims.issuer) jwt.setIssuer(claims.issuer);
if (claims.subject) jwt.setSubject(claims.subject);
if (claims.audience) jwt.setAudience(claims.audience);
if (claims.jti) jwt.setJti(claims.jti);
if (claims.expirationTime) jwt.setExpirationTime(claims.expirationTime);
if (claims.notBefore) jwt.setNotBefore(claims.notBefore);
if (claims.issuedAt !== undefined) {
if (claims.issuedAt === true) {
jwt.setIssuedAt();
} else {
jwt.setIssuedAt(claims.issuedAt);
}
}
return jwt.encrypt(key);
}
/**
* Decrypts a JSON Web Token (JWT).
*
* @param {string} jwt - The compact encrypted JWT string.
* @param {Uint8Array | import('jose').KeyLike | import('jose').JWTDecryptGetKey} key - Decryption key or resolver callback.
* @param {object} [options] - Verification options such as issuer, audience, etc.
* @returns {Promise<{ payload: import('jose').JWTPayload, protectedHeader: import('jose').CompactJWEHeaderParameters }>}
*/
export async function decryptEncryptedJWT(jwt, key, options) {
return jwtDecrypt(jwt, key, options);
}
export { EncryptJWT, jwtDecrypt };
export default EncryptJWT;
import assert from 'node:assert/strict';
import {
EncryptJWT,
jwtDecrypt,
generateSecret,
generateKeyPair,
errors
} from 'jose';
import { createEncryptedJWT, decryptEncryptedJWT } from '../src/index.mjs';
// 1. EncryptJWT produces a 5-part compact encrypted JWT with direct symmetric encryption (dir + A256GCM) that can be decrypted with jwtDecrypt
{
const secretKey = await generateSecret('A256GCM');
const jwt = await createEncryptedJWT(
{ custom: 'value' },
{ alg: 'dir', enc: 'A256GCM' },
secretKey,
{
issuer: 'urn:example:issuer',
subject: 'urn:example:subject',
audience: 'urn:example:audience',
jti: 'token-id-123',
issuedAt: true,
expirationTime: '2h'
}
);
assert.equal(typeof jwt, 'string');
assert.equal(jwt.split('.').length, 5);
const { payload, protectedHeader } = await decryptEncryptedJWT(jwt, secretKey, {
issuer: 'urn:example:issuer',
audience: 'urn:example:audience',
});
assert.equal(payload.custom, 'value');
assert.equal(payload.iss, 'urn:example:issuer');
assert.equal(payload.sub, 'urn:example:subject');
assert.equal(payload.aud, 'urn:example:audience');
assert.equal(payload.jti, 'token-id-123');
assert.equal(typeof payload.iat, 'number');
assert.equal(typeof payload.exp, 'number');
assert.equal(protectedHeader.alg, 'dir');
assert.equal(protectedHeader.enc, 'A256GCM');
}
// 2. EncryptJWT produces an encrypted JWT using symmetric key wrapping (A256KW + A256GCM)
{
const wrappingKey = await generateSecret('A256KW');
const jwt = await new EncryptJWT({ role: 'admin' })
.setProtectedHeader({ alg: 'A256KW', enc: 'A256GCM' })
.encrypt(wrappingKey);
const { payload, protectedHeader } = await jwtDecrypt(jwt, wrappingKey);
assert.equal(payload.role, 'admin');
assert.equal(protectedHeader.alg, 'A256KW');
assert.equal(protectedHeader.enc, 'A256GCM');
}
// 3. EncryptJWT produces an encrypted JWT using RSA public key encryption (RSA-OAEP-256 + A128CBC-HS256)
{
const { publicKey, privateKey } = await generateKeyPair('RSA-OAEP-256');
const jwt = await new EncryptJWT({ user: 'alice' })
.setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A128CBC-HS256' })
.encrypt(publicKey);
const { payload, protectedHeader } = await jwtDecrypt(jwt, privateKey);
assert.equal(payload.user, 'alice');
assert.equal(protectedHeader.alg, 'RSA-OAEP-256');
assert.equal(protectedHeader.enc, 'A128CBC-HS256');
}
// 4. EncryptJWT supports dynamic key resolution via key resolver callback during decryption
{
const secretKey1 = await generateSecret('A256GCM');
const secretKey2 = await generateSecret('A256GCM');
const keyStore = new Map([
['key-1', secretKey1],
['key-2', secretKey2],
]);
const jwt = await new EncryptJWT({ claim: 'dynamic' })
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM', kid: 'key-2' })
.encrypt(secretKey2);
const keyResolver = async (protectedHeader) => {
const key = keyStore.get(protectedHeader.kid);
if (!key) throw new Error('Key not found');
return key;
};
const { payload, protectedHeader } = await jwtDecrypt(jwt, keyResolver);
assert.equal(payload.claim, 'dynamic');
assert.equal(protectedHeader.kid, 'key-2');
}
// 5. EncryptJWT enforces exp and nbf claims throwing JWTExpired or JWTClaimValidationFailed when invalid
{
const secretKey = await generateSecret('A256GCM');
const expiredJwt = await new EncryptJWT({ test: 'expired' })
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
.setIssuedAt(Math.floor(Date.now() / 1000) - 60)
.setExpirationTime(Math.floor(Date.now() / 1000) - 10)
.encrypt(secretKey);
await assert.rejects(
async () => {
await jwtDecrypt(expiredJwt, secretKey);
},
(err) => {
assert(err instanceof errors.JWTExpired);
assert.equal(err.code, 'ERR_JWT_EXPIRED');
assert.equal(err.claim, 'exp');
return true;
}
);
const futureJwt = await new EncryptJWT({ test: 'future' })
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
.setNotBefore(Math.floor(Date.now() / 1000) + 120)
.encrypt(secretKey);
await assert.rejects(
async () => {
await jwtDecrypt(futureJwt, secretKey);
},
(err) => {
assert(err instanceof errors.JWTClaimValidationFailed);
assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
assert.equal(err.claim, 'nbf');
return true;
}
);
}
// 6. EncryptJWT throws JWEInvalid when attempting to encrypt without protected or unprotected headers
{
const secretKey = await generateSecret('A256GCM');
const encrypter = new EncryptJWT({ test: 'missing-header' });
await assert.rejects(
async () => {
await encrypter.encrypt(secretKey);
},
(err) => {
assert(err instanceof errors.JWEInvalid);
assert.equal(err.code, 'ERR_JWE_INVALID');
return true;
}
);
}
// 7. EncryptJWT encrypted token fails decryption with JWEDecryptionFailed when decrypted with incorrect key or tampered ciphertext
{
const key1 = await generateSecret('A256GCM');
const key2 = await generateSecret('A256GCM');
const jwt = await new EncryptJWT({ test: 'tamper' })
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
.encrypt(key1);
await assert.rejects(
async () => {
await jwtDecrypt(jwt, key2);
},
(err) => {
assert(err instanceof errors.JWEDecryptionFailed);
assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
return true;
}
);
const parts = jwt.split('.');
parts[3] = 'AAAA' + parts[3].slice(4);
const corruptedJwt = parts.join('.');
await assert.rejects(
async () => {
await jwtDecrypt(corruptedJwt, key1);
},
(err) => {
assert(err instanceof errors.JWEDecryptionFailed);
assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
return true;
}
);
}
console.log('Contract tests passed successfully.');
오리진 시더
익명