CodeSampleX

샘플

jose 6.2.9: EncryptJWT

검증된 샘플 — npm jose 6.2.9: EncryptJWT. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: EncryptJWT creates compact 5-part JWE strings using direct…

sha256:58461617fbb89b24a186b39db05eb1bdb5d1e151bbc382f03100bb99d2e60223

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
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-26
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-09-07

케이스

HOW
목표
verify EncryptJWT in pkg:npm/jose@6.2.9
패키지
심벌
  • EncryptJWT
환경
node 22.23.2
생성일
2026-08-26T10:59:25Z

컨트랙트

  1. EncryptJWT creates compact 5-part JWE strings using direct symmetric encryption with A256GCM and jwtDecrypt verifies claims and protected header
  2. EncryptJWT constructor rejects non-object payloads such as strings or null with TypeError
  3. EncryptJWT encrypt rejects with JWEInvalid when called before setting headers
  4. EncryptJWT encrypt rejects with JWEInvalid when protected header lacks enc parameter
  5. jwtDecrypt rejects incorrect secret keys with JWEDecryptionFailed
  6. jwtDecrypt rejects tampered ciphertext with JWEDecryptionFailed
  7. jwtDecrypt rejects malformed compact JWE strings with JWEInvalid
  8. jwtDecrypt rejects expired tokens with JWTExpired
  9. jwtDecrypt rejects mismatched issuer or audience with JWTClaimValidationFailed
  10. EncryptJWT and jwtDecrypt support asymmetric key agreement with ECDH-ES+A256KW
  11. jwtDecrypt supports dynamic key resolution via key resolver callback function

파일

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# jose `EncryptJWT` and `jwtDecrypt` (Encrypted JWT / JWE)

## Prior Solution Search
`search_known_solution` returned `NO_SAFE_MATCH` for `EncryptJWT` in `jose@6.2.9`.

## Pinned Release
- `jose`: `6.2.9`

## Observed Behavior

When using `EncryptJWT` and `jwtDecrypt` for Encrypted JSON Web Token (JWE) creation and decryption:

1. **Direct Symmetric Encryption and Decryption (A256GCM)**:
   - `EncryptJWT` constructor accepts a JSON object payload (claims set).
   - Calling `setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })` and `encrypt(secretKey)` produces a 5-part dot-separated base64url encoded JWE string (`header.encryptedKey.iv.ciphertext.tag`). For direct encryption (`alg: 'dir'`), the encrypted key component is empty.
   - `jwtDecrypt(jwt, secretKey, options)` parses and decrypts the compact JWE, resolving to `{ payload: JWTPayload, protectedHeader: CompactJWEHeaderParameters }`.

2. **Payload Type Enforcement**:
   - `EncryptJWT` constructor strictly requires an object. Passing non-object types (e.g. strings or null) throws a synchronous `TypeError: JWT Claims Set MUST be an object`.

3. **Mandatory Header Requirement**:
   - Calling `encrypt()` without protected header throws `JWEInvalid` (`ERR_JWE_INVALID: either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`).
   - Calling `encrypt()` when protected header lacks `enc` parameter throws `JWEInvalid` (`ERR_JWE_INVALID: JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`).

4. **Decryption and Integrity Failures**:
   - Decrypting with an incorrect secret key fails with `JWEDecryptionFailed` (`ERR_JWE_DECRYPTION_FAILED: decryption operation failed`).
   - Tampered ciphertext fails with `JWEDecryptionFailed` (`ERR_JWE_DECRYPTION_FAILED: decryption operation failed`).
   - Malformed compact JWE strings (fewer or more than 5 parts) fail with `JWEInvalid` (`ERR_JWE_INVALID: Invalid Compact JWE`).

5. **Claim Validation (Expiration, Issuer, Audience)**:
   - Expired tokens throw `JWTExpired` (`ERR_JWT_EXPIRED: "exp" claim timestamp check failed`).
   - Mismatched issuer or audience throws `JWTClaimValidationFailed` (`ERR_JWT_CLAIM_VALIDATION_FAILED: unexpected "iss" claim value` or `unexpected "aud" claim value`).

6. **Asymmetric Key Agreement and Dynamic Key Resolution**:
   - `EncryptJWT` and `jwtDecrypt` support asymmetric key pairs (e.g. `ECDH-ES+A256KW` with `A256GCM`).
   - `jwtDecrypt` supports dynamic key resolution via a key resolver callback function `(protectedHeader, token) => KeyLike | Uint8Array`.
PROMPT.md
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 EncryptJWT in pkg:npm/jose@6.2.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jose@6.2.9
Demonstrate these symbols/APIs:
  - EncryptJWT
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.
csx.json
{"case":{"caseId":"case:sha256:6ffe77bcb00ccc2ece23018fafc94d8a50f400790b470a3d388d59505b2db9e1","constraints":{"executionContext":"node"},"contract":["EncryptJWT creates compact 5-part JWE strings using direct symmetric encryption with A256GCM and jwtDecrypt verifies claims and protected header","EncryptJWT constructor rejects non-object payloads such as strings or null with TypeError","EncryptJWT encrypt rejects with JWEInvalid when called before setting headers","EncryptJWT encrypt rejects with JWEInvalid when protected header lacks enc parameter","jwtDecrypt rejects incorrect secret keys with JWEDecryptionFailed","jwtDecrypt rejects tampered ciphertext with JWEDecryptionFailed","jwtDecrypt rejects malformed compact JWE strings with JWEInvalid","jwtDecrypt rejects expired tokens with JWTExpired","jwtDecrypt rejects mismatched issuer or audience with JWTClaimValidationFailed","EncryptJWT and jwtDecrypt support asymmetric key agreement with ECDH-ES+A256KW","jwtDecrypt supports dynamic key resolution via key resolver callback function"],"goal":"verify EncryptJWT in pkg:npm/jose@6.2.9","kind":"HOW","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"symbols":["EncryptJWT"]},"contractCommand":["node","test/contract.mjs"],"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.9"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.9","symbols":["EncryptJWT"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "jose-encrypt-jwt-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "jose-encrypt-jwt-sample",
      "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"
      }
    }
  }
}
package.json
{
  "name": "jose-encrypt-jwt-sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "jose": "6.2.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify EncryptJWT in pkg:npm/jose@6.2.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.9"
  ],
  "symbols": [
    "EncryptJWT"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import * as jose from 'jose';
import assert from 'node:assert/strict';

async function run() {
  const secretKey = await jose.generateSecret('A256GCM');
  const payload = { sub: 'user_123', role: 'admin', 'urn:example:claim': true };

  // 1. Direct symmetric encryption and decryption with EncryptJWT (A256GCM)
  // EncryptJWT produces a 5-part compact JWE string (header.encryptedKey.iv.ciphertext.tag).
  // Direct encryption (alg: 'dir') leaves the encrypted key component empty.
  const jwt = await new jose.EncryptJWT(payload)
    .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
    .setIssuedAt()
    .setIssuer('urn:example:issuer')
    .setAudience('urn:example:audience')
    .setExpirationTime('2h')
    .encrypt(secretKey);

  assert.equal(typeof jwt, 'string');
  const parts = jwt.split('.');
  assert.equal(parts.length, 5);
  assert.equal(parts[1], ''); // dir algorithm has empty encrypted key part

  const { payload: decryptedPayload, protectedHeader } = await jose.jwtDecrypt(jwt, secretKey, {
    issuer: 'urn:example:issuer',
    audience: 'urn:example:audience',
  });

  assert.equal(decryptedPayload.sub, 'user_123');
  assert.equal(decryptedPayload.role, 'admin');
  assert.equal(decryptedPayload['urn:example:claim'], true);
  assert.equal(decryptedPayload.iss, 'urn:example:issuer');
  assert.deepEqual(decryptedPayload.aud, 'urn:example:audience');
  assert.equal(typeof decryptedPayload.iat, 'number');
  assert.equal(typeof decryptedPayload.exp, 'number');
  assert.deepEqual(protectedHeader, { alg: 'dir', enc: 'A256GCM' });

  // 2. Non-object payload validation
  // EncryptJWT constructor strictly requires an object payload. Non-object arguments throw TypeError.
  assert.throws(
    () => new jose.EncryptJWT('plain-text-string'),
    (err) => {
      assert(err instanceof TypeError);
      assert.equal(err.message, 'JWT Claims Set MUST be an object');
      return true;
    }
  );

  assert.throws(
    () => new jose.EncryptJWT(null),
    (err) => {
      assert(err instanceof TypeError);
      assert.equal(err.message, 'JWT Claims Set MUST be an object');
      return true;
    }
  );

  // 3. Mandatory Protected Header
  // Calling encrypt() without setProtectedHeader throws JWEInvalid (ERR_JWE_INVALID).
  await assert.rejects(
    async () => new jose.EncryptJWT(payload).encrypt(secretKey),
    (err) => {
      assert(err instanceof jose.errors.JWEInvalid);
      assert.equal(err.code, 'ERR_JWE_INVALID');
      assert.equal(err.message, 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
      return true;
    }
  );

  // 4. Missing enc header parameter
  // Calling encrypt() when protected header lacks 'enc' parameter throws JWEInvalid (ERR_JWE_INVALID).
  await assert.rejects(
    async () => new jose.EncryptJWT(payload)
      .setProtectedHeader({ alg: 'dir' })
      .encrypt(secretKey),
    (err) => {
      assert(err instanceof jose.errors.JWEInvalid);
      assert.equal(err.code, 'ERR_JWE_INVALID');
      assert.equal(err.message, 'JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
      return true;
    }
  );

  // 5. Decryption failure with wrong key
  // Decrypting with an incorrect secret key fails with JWEDecryptionFailed (ERR_JWE_DECRYPTION_FAILED).
  const wrongSecretKey = await jose.generateSecret('A256GCM');
  await assert.rejects(
    async () => jose.jwtDecrypt(jwt, wrongSecretKey),
    (err) => {
      assert(err instanceof jose.errors.JWEDecryptionFailed);
      assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
      assert.equal(err.message, 'decryption operation failed');
      return true;
    }
  );

  // 6. Decryption failure with tampered ciphertext
  const tamperedParts = [...parts];
  const originalCiphertext = jose.base64url.decode(tamperedParts[3]);
  originalCiphertext[0] ^= 0xff; // flip bits in ciphertext
  tamperedParts[3] = jose.base64url.encode(originalCiphertext);
  const tamperedJwt = tamperedParts.join('.');

  await assert.rejects(
    async () => jose.jwtDecrypt(tamperedJwt, secretKey),
    (err) => {
      assert(err instanceof jose.errors.JWEDecryptionFailed);
      assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
      assert.equal(err.message, 'decryption operation failed');
      return true;
    }
  );

  // 7. Malformed compact JWE structure
  // Passing compact strings without exactly 5 parts throws JWEInvalid (ERR_JWE_INVALID).
  await assert.rejects(
    async () => jose.jwtDecrypt('invalid.compact.jwe.format', secretKey),
    (err) => {
      assert(err instanceof jose.errors.JWEInvalid);
      assert.equal(err.code, 'ERR_JWE_INVALID');
      assert.equal(err.message, 'Invalid Compact JWE');
      return true;
    }
  );

  // 8. Expiration validation failure
  // Expired token throws JWTExpired (ERR_JWT_EXPIRED).
  const expiredJwt = await new jose.EncryptJWT({ sub: 'user_123' })
    .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
    .setExpirationTime('-1s')
    .encrypt(secretKey);

  await assert.rejects(
    async () => jose.jwtDecrypt(expiredJwt, secretKey),
    (err) => {
      assert(err instanceof jose.errors.JWTExpired);
      assert.equal(err.code, 'ERR_JWT_EXPIRED');
      assert.equal(err.message, '"exp" claim timestamp check failed');
      return true;
    }
  );

  // 9. Claim validation failure for issuer and audience
  // Mismatched expected issuer or audience throws JWTClaimValidationFailed (ERR_JWT_CLAIM_VALIDATION_FAILED).
  await assert.rejects(
    async () => jose.jwtDecrypt(jwt, secretKey, { issuer: 'urn:different:issuer' }),
    (err) => {
      assert(err instanceof jose.errors.JWTClaimValidationFailed);
      assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
      assert.equal(err.message, 'unexpected "iss" claim value');
      return true;
    }
  );

  await assert.rejects(
    async () => jose.jwtDecrypt(jwt, secretKey, { audience: 'urn:different:audience' }),
    (err) => {
      assert(err instanceof jose.errors.JWTClaimValidationFailed);
      assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
      assert.equal(err.message, 'unexpected "aud" claim value');
      return true;
    }
  );

  // 10. Asymmetric key encryption and decryption (ECDH-ES key agreement)
  // EncryptJWT supports asymmetric public key encryption with ECDH-ES+A256KW.
  const { privateKey, publicKey } = await jose.generateKeyPair('ECDH-ES+A256KW');
  const asymmetricJwt = await new jose.EncryptJWT({ sub: 'asymmetric_user' })
    .setProtectedHeader({ alg: 'ECDH-ES+A256KW', enc: 'A256GCM', kid: 'key-2026' })
    .encrypt(publicKey);

  assert.equal(asymmetricJwt.split('.').length, 5);
  assert.notEqual(asymmetricJwt.split('.')[1], ''); // Key wrapping populates encrypted key part

  const asymmetricDecrypted = await jose.jwtDecrypt(asymmetricJwt, privateKey);
  assert.equal(asymmetricDecrypted.payload.sub, 'asymmetric_user');
  assert.equal(asymmetricDecrypted.protectedHeader.alg, 'ECDH-ES+A256KW');
  assert.equal(asymmetricDecrypted.protectedHeader.enc, 'A256GCM');
  assert.equal(asymmetricDecrypted.protectedHeader.kid, 'key-2026');

  // 11. Key resolver callback function support
  // jwtDecrypt supports resolving decryption keys dynamically via a resolver callback.
  const keyMap = new Map([
    ['key-2026', privateKey],
  ]);

  const keyResolver = async (header) => {
    const key = keyMap.get(header.kid);
    if (!key) {
      throw new Error('Key not found');
    }
    return key;
  };

  const resolvedDecrypted = await jose.jwtDecrypt(asymmetricJwt, keyResolver);
  assert.equal(resolvedDecrypted.payload.sub, 'asymmetric_user');
  assert.equal(resolvedDecrypted.protectedHeader.kid, 'key-2026');

  // Resolver rejecting when key is missing
  const unknownKidJwt = await new jose.EncryptJWT({ sub: 'unknown' })
    .setProtectedHeader({ alg: 'ECDH-ES+A256KW', enc: 'A256GCM', kid: 'unknown-key-id' })
    .encrypt(publicKey);

  await assert.rejects(
    async () => jose.jwtDecrypt(unknownKidJwt, keyResolver),
    (err) => {
      assert.equal(err.message, 'Key not found');
      return true;
    }
  );
}

run();

오리진 시더

익명