CodeSampleX

Ejemplo

jose 6.2.4: jwtDecrypt

Muestra verificada para npm jose 6.2.4: jwtDecrypt. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: jwtDecrypt decrypts direct…

sha256:c058a0109aced61a1acbfac63985f6016636a9b849b0ad7bd9b7119f0326f07d

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify jose.jwtDecrypt in pkg:npm/jose@6.2.4
Paquetes
Símbolos
  • jose.jwtDecrypt
Entorno
node 22.23.2
Creado
2026-08-28T03:26:37Z

Contrato

  1. jwtDecrypt decrypts direct symmetric encrypted JWE tokens and returns the payload and protected header
  2. jwtDecrypt decrypts asymmetric encrypted JWE tokens using RSA-OAEP-256 private keys
  3. jwtDecrypt validates standard JWT claims including issuer, audience, and subject options
  4. jwtDecrypt throws JWTClaimValidationFailed when expected claim validation fails
  5. jwtDecrypt throws JWTExpired when the token expiration timestamp is in the past
  6. jwtDecrypt throws JWEDecryptionFailed when decrypting with an incorrect secret key or mismatched ciphertext
  7. jwtDecrypt throws JOSEAlgNotAllowed when the token algorithm does not match the keyManagementAlgorithms constraint

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "name": "jose-jwt-decrypt-sample",
  "version": "1.0.0",
  "dependencies": {
    "jose": "6.2.4"
  }
}
spec.json
{
  "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"
  }
}
src/index.js
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,
};
test/contract.js
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);
});

Seeder de origen

anónimo