CodeSampleX

Sample

jose 6.2.4: EncryptJWT

Verified sample for npm jose 6.2.4: EncryptJWT. The contract ran on node 22 · linux alpine/x64 · docker and passed: EncryptJWT produces a 5-part compact…

sha256:300a831ee2bf237f60139f31290884a85f77f1a4041640c9e58eab2afdac6876

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify jose.EncryptJWT in pkg:npm/jose@6.2.4
Packages
Symbols
  • jose.EncryptJWT
Created
2026-08-21T16:55:16Z

Contract

  1. EncryptJWT produces a 5-part compact encrypted JWT with direct symmetric encryption (dir + A256GCM) that can be decrypted with jwtDecrypt
  2. EncryptJWT produces an encrypted JWT using symmetric key wrapping (A256KW + A256GCM)
  3. EncryptJWT produces an encrypted JWT using RSA public key encryption (RSA-OAEP-256 + A128CBC-HS256)
  4. EncryptJWT supports dynamic key resolution via key resolver callback during decryption
  5. EncryptJWT enforces exp and nbf claims throwing JWTExpired or JWTClaimValidationFailed when invalid
  6. EncryptJWT throws JWEInvalid when attempting to encrypt without protected or unprotected headers
  7. EncryptJWT encrypted token fails decryption with JWEDecryptionFailed when decrypted with incorrect key or tampered ciphertext

Files

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

Download the source artifact (tar.gz)

Source

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 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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "name": "verify-jose-encrypt-jwt",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "jose": "6.2.4"
  }
}
spec.json
{
  "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"
  ]
}
src/index.mjs
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;
test/contract.mjs
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.');

Origin Seeder

anonymous