CodeSampleX

Exemplo

jose 6.2.8

Amostra verificada para npm jose 6.2.8. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: CompactEncrypt and compactDecrypt perform direct…

sha256:18f20aab0b067fcca250ac3772485243f4fca9901e64c6176644abe9cdb81b93

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-23
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-08

Caso

HOW
Objetivo
verify pkg:npm/jose@6.2.8
Pacotes
Criado
2026-08-23T06:08:29Z

Contrato

  1. CompactEncrypt and compactDecrypt perform direct symmetric encryption and decryption with A256GCM, returning the original plaintext and protected header
  2. decodeProtectedHeader parses JWE protected header without requiring decryption key
  3. CompactEncrypt and compactDecrypt support key wrapping with A256KW and content encryption with A256GCM
  4. EncryptJWT and jwtDecrypt encrypt JSON claims and validate standard claims including issuer, audience, and expiration
  5. compactDecrypt throws JWEDecryptionFailed with code ERR_JWE_DECRYPTION_FAILED when decrypted with incorrect key or tampered ciphertext
  6. compactDecrypt throws JWEInvalid with code ERR_JWE_INVALID when provided with malformed JWE compact string
  7. jwtDecrypt throws JWTExpired with code ERR_JWT_EXPIRED and claim exp when decrypting expired token
  8. jwtDecrypt throws JWTClaimValidationFailed with code ERR_JWT_CLAIM_VALIDATION_FAILED when issuer or audience claims mismatch expected values

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 pkg:npm/jose@6.2.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jose@6.2.8

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:f70cd22390e68ba320cfc57b6a228ad00cbddff51fa4208fe3f9d22324ebad91","contract":["CompactEncrypt and compactDecrypt perform direct symmetric encryption and decryption with A256GCM, returning the original plaintext and protected header","decodeProtectedHeader parses JWE protected header without requiring decryption key","CompactEncrypt and compactDecrypt support key wrapping with A256KW and content encryption with A256GCM","EncryptJWT and jwtDecrypt encrypt JSON claims and validate standard claims including issuer, audience, and expiration","compactDecrypt throws JWEDecryptionFailed with code ERR_JWE_DECRYPTION_FAILED when decrypted with incorrect key or tampered ciphertext","compactDecrypt throws JWEInvalid with code ERR_JWE_INVALID when provided with malformed JWE compact string","jwtDecrypt throws JWTExpired with code ERR_JWT_EXPIRED and claim exp when decrypting expired token","jwtDecrypt throws JWTClaimValidationFailed with code ERR_JWT_CLAIM_VALIDATION_FAILED when issuer or audience claims mismatch expected values"],"goal":"verify pkg:npm/jose@6.2.8","kind":"HOW","packages":["pkg:npm/jose@6.2.8"],"schemaVersion":1},"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.8"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.8","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jose",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jose",
      "version": "1.0.0",
      "dependencies": {
        "jose": "6.2.8"
      }
    },
    "node_modules/jose": {
      "version": "6.2.8",
      "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.8.tgz",
      "integrity": "sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/panva"
      }
    }
  }
}
package.json
{
  "name": "sample-jose",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jose": "6.2.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/jose@6.2.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.8"
  ]
}
src/index.mjs
import {
  CompactEncrypt,
  compactDecrypt,
  decodeProtectedHeader,
  generateSecret,
  EncryptJWT,
  jwtDecrypt,
  errors
} from 'jose';

export async function encryptPayload(plaintext, secretKey, enc = 'A256GCM') {
  const encoded = typeof plaintext === 'string' ? new TextEncoder().encode(plaintext) : plaintext;
  return await new CompactEncrypt(encoded)
    .setProtectedHeader({ alg: 'dir', enc })
    .encrypt(secretKey);
}

export async function decryptPayload(jwe, secretKey) {
  const { plaintext, protectedHeader } = await compactDecrypt(jwe, secretKey);
  return {
    plaintext: new TextDecoder().decode(plaintext),
    rawPlaintext: plaintext,
    protectedHeader
  };
}

export async function encryptWithKeyWrap(plaintext, keyWrapKey, alg = 'A256KW', enc = 'A256GCM') {
  const encoded = typeof plaintext === 'string' ? new TextEncoder().encode(plaintext) : plaintext;
  return await new CompactEncrypt(encoded)
    .setProtectedHeader({ alg, enc })
    .encrypt(keyWrapKey);
}

export async function createEncryptedToken(payload, secretKey, options = {}) {
  const jwt = new EncryptJWT(payload)
    .setProtectedHeader({ alg: 'dir', enc: options.enc || 'A256GCM' });

  if (options.issuer) {
    jwt.setIssuer(options.issuer);
  }
  if (options.audience) {
    jwt.setAudience(options.audience);
  }
  if (options.expirationTime) {
    jwt.setExpirationTime(options.expirationTime);
  }
  if (options.issuedAt !== false) {
    jwt.setIssuedAt();
  }

  return await jwt.encrypt(secretKey);
}

export async function verifyAndDecryptToken(token, secretKey, options = {}) {
  return await jwtDecrypt(token, secretKey, options);
}

export {
  CompactEncrypt,
  compactDecrypt,
  decodeProtectedHeader,
  generateSecret,
  EncryptJWT,
  jwtDecrypt,
  errors
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  encryptPayload,
  decryptPayload,
  encryptWithKeyWrap,
  createEncryptedToken,
  verifyAndDecryptToken,
  CompactEncrypt,
  compactDecrypt,
  decodeProtectedHeader,
  generateSecret,
  EncryptJWT,
  jwtDecrypt,
  errors
} from '../src/index.mjs';

// 1. CompactEncrypt and compactDecrypt perform direct symmetric encryption and decryption with A256GCM, returning the original plaintext and protected header
{
  const secretKey = await generateSecret('A256GCM');
  const message = 'confidential message payload';
  const jwe = await encryptPayload(message, secretKey);

  assert.equal(typeof jwe, 'string');
  const parts = jwe.split('.');
  assert.equal(parts.length, 5, 'JWE compact serialization must contain 5 dot-separated parts');

  const result = await decryptPayload(jwe, secretKey);
  assert.equal(result.plaintext, message);
  assert.deepEqual(result.protectedHeader, { alg: 'dir', enc: 'A256GCM' });
}

// 2. decodeProtectedHeader parses JWE protected header without requiring decryption key
{
  const secretKey = await generateSecret('A256GCM');
  const jwe = await encryptPayload('data', secretKey);
  const header = decodeProtectedHeader(jwe);
  assert.equal(header.alg, 'dir');
  assert.equal(header.enc, 'A256GCM');
}

// 3. CompactEncrypt and compactDecrypt support key wrapping with A256KW and content encryption with A256GCM
{
  const kwKey = await generateSecret('A256KW');
  const message = 'wrapped key confidential data';
  const jwe = await encryptWithKeyWrap(message, kwKey, 'A256KW', 'A256GCM');

  const header = decodeProtectedHeader(jwe);
  assert.deepEqual(header, { alg: 'A256KW', enc: 'A256GCM' });

  const result = await compactDecrypt(jwe, kwKey);
  assert.equal(new TextDecoder().decode(result.plaintext), message);
  assert.deepEqual(result.protectedHeader, { alg: 'A256KW', enc: 'A256GCM' });
}

// 4. EncryptJWT and jwtDecrypt encrypt JSON claims and validate standard claims including issuer, audience, and expiration
{
  const secretKey = await generateSecret('A256GCM');
  const claims = { sub: 'subject-12345', role: 'admin', scope: ['read', 'write'] };
  const token = await createEncryptedToken(claims, secretKey, {
    issuer: 'https://example.com/auth',
    audience: 'https://example.com/api',
    expirationTime: '2h'
  });

  const decrypted = await verifyAndDecryptToken(token, secretKey, {
    issuer: 'https://example.com/auth',
    audience: 'https://example.com/api'
  });

  assert.equal(decrypted.payload.sub, 'subject-12345');
  assert.equal(decrypted.payload.role, 'admin');
  assert.deepEqual(decrypted.payload.scope, ['read', 'write']);
  assert.equal(decrypted.payload.iss, 'https://example.com/auth');
  assert.equal(decrypted.payload.aud, 'https://example.com/api');
  assert.ok(typeof decrypted.payload.exp === 'number');
  assert.ok(typeof decrypted.payload.iat === 'number');
  assert.deepEqual(decrypted.protectedHeader, { alg: 'dir', enc: 'A256GCM' });
}

// 5. compactDecrypt throws JWEDecryptionFailed with code ERR_JWE_DECRYPTION_FAILED when decrypted with incorrect key or tampered ciphertext
{
  const key1 = await generateSecret('A256GCM');
  const key2 = await generateSecret('A256GCM');
  const jwe = await encryptPayload('sensitive info', key1);

  // Wrong key
  await assert.rejects(
    async () => { await decryptPayload(jwe, key2); },
    (err) => {
      assert(err instanceof errors.JWEDecryptionFailed);
      assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
      return true;
    }
  );

  // Tampered ciphertext
  const parts = jwe.split('.');
  parts[3] = 'tampered' + parts[3].slice(8);
  const tamperedJwe = parts.join('.');
  await assert.rejects(
    async () => { await decryptPayload(tamperedJwe, key1); },
    (err) => {
      assert(err instanceof errors.JWEDecryptionFailed);
      assert.equal(err.code, 'ERR_JWE_DECRYPTION_FAILED');
      return true;
    }
  );
}

// 6. compactDecrypt throws JWEInvalid with code ERR_JWE_INVALID when provided with malformed JWE compact string
{
  const secretKey = await generateSecret('A256GCM');
  await assert.rejects(
    async () => { await decryptPayload('invalid.compact.jwe', secretKey); },
    (err) => {
      assert(err instanceof errors.JWEInvalid);
      assert.equal(err.code, 'ERR_JWE_INVALID');
      return true;
    }
  );
}

// 7. jwtDecrypt throws JWTExpired with code ERR_JWT_EXPIRED and claim exp when decrypting expired token
{
  const secretKey = await generateSecret('A256GCM');
  const expiredToken = await new EncryptJWT({ sub: 'user-expired' })
    .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
    .setExpirationTime('-10s')
    .encrypt(secretKey);

  await assert.rejects(
    async () => { await verifyAndDecryptToken(expiredToken, secretKey); },
    (err) => {
      assert(err instanceof errors.JWTExpired);
      assert.equal(err.code, 'ERR_JWT_EXPIRED');
      assert.equal(err.claim, 'exp');
      assert.equal(err.reason, 'check_failed');
      return true;
    }
  );
}

// 8. jwtDecrypt throws JWTClaimValidationFailed with code ERR_JWT_CLAIM_VALIDATION_FAILED when issuer or audience claims mismatch expected values
{
  const secretKey = await generateSecret('A256GCM');
  const token = await createEncryptedToken({ sub: 'user-mismatch' }, secretKey, {
    issuer: 'https://example.com/expected-issuer',
    audience: 'https://example.com/expected-audience',
    expirationTime: '1h'
  });

  // Issuer mismatch
  await assert.rejects(
    async () => {
      await verifyAndDecryptToken(token, secretKey, {
        issuer: 'https://example.com/other-issuer'
      });
    },
    (err) => {
      assert(err instanceof errors.JWTClaimValidationFailed);
      assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
      assert.equal(err.claim, 'iss');
      assert.equal(err.reason, 'check_failed');
      return true;
    }
  );

  // Audience mismatch
  await assert.rejects(
    async () => {
      await verifyAndDecryptToken(token, secretKey, {
        issuer: 'https://example.com/expected-issuer',
        audience: 'https://example.com/other-audience'
      });
    },
    (err) => {
      assert(err instanceof errors.JWTClaimValidationFailed);
      assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
      assert.equal(err.claim, 'aud');
      assert.equal(err.reason, 'check_failed');
      return true;
    }
  );
}

console.log('Contract tests passed successfully.');

Seeder de origem

anônimo