Ejemplo
jose 6.2.5: FlattenedEncrypt
Muestra verificada para npm jose 6.2.5: FlattenedEncrypt. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.
sha256:9a2a2b1ebac05c54174e60f7d1683edef32774834411eeb0403d716b5725a262
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 debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-09-01 |
Caso
HOW- Objetivo
- verify FlattenedEncrypt in pkg:npm/jose@6.2.5
- Paquetes
- Símbolos
-
- FlattenedEncrypt
- Entorno
- node 22.23.2
- Creado
- 2026-09-01T10:51:42Z
Contrato
- FlattenedEncrypt produces a Flattened JWE object with ciphertext, iv, tag, and protected header
- FlattenedEncrypt supports symmetric encryption using direct shared key and A256GCM algorithm
- FlattenedEncrypt supports shared unprotected headers and per-recipient unprotected headers
- FlattenedEncrypt binds Additional Authenticated Data (AAD) into integrity check
- FlattenedEncrypt supports asymmetric key encryption using ECDH-ES algorithm
- FlattenedEncrypt encrypted JWE fails decryption when ciphertext or tag is modified
- FlattenedEncrypt rejects encryption without setting protected or unprotected header
Archivos
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
Código fuente
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 FlattenedEncrypt in pkg:npm/jose@6.2.5
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jose@6.2.5
Demonstrate these symbols/APIs:
- FlattenedEncrypt
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:1ef187a3ecd3e56fa15e869b04097f84b8a77f13ec8777561e5c1210cbc211ca","contract":["FlattenedEncrypt produces a Flattened JWE object with ciphertext, iv, tag, and protected header","FlattenedEncrypt supports symmetric encryption using direct shared key and A256GCM algorithm","FlattenedEncrypt supports shared unprotected headers and per-recipient unprotected headers","FlattenedEncrypt binds Additional Authenticated Data (AAD) into integrity check","FlattenedEncrypt supports asymmetric key encryption using ECDH-ES algorithm","FlattenedEncrypt encrypted JWE fails decryption when ciphertext or tag is modified","FlattenedEncrypt rejects encryption without setting protected or unprotected header"],"goal":"verify FlattenedEncrypt in pkg:npm/jose@6.2.5","kind":"HOW","packages":["pkg:npm/jose@6.2.5"],"schemaVersion":1,"symbols":["FlattenedEncrypt"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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.5"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.5","symbols":["FlattenedEncrypt"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-jose-flattened-encrypt",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-jose-flattened-encrypt",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"jose": "6.2.5"
}
},
"node_modules/jose": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.5.tgz",
"integrity": "sha512-2E5L2yRp03FnwreJLJX8/r7mHiZICCf8kG7fAsTWkSQTDAcc46NIZoQLKy+EJ8sPoJlxyS4OQR5H70LjIZZlIQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
}
}
}
{
"name": "sample-jose-flattened-encrypt",
"version": "1.0.0",
"private": true,
"license": "MIT-0",
"type": "module",
"dependencies": {
"jose": "6.2.5"
}
}
{
"schemaVersion": 1,
"goal": "verify FlattenedEncrypt in pkg:npm/jose@6.2.5",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.5"
],
"symbols": [
"FlattenedEncrypt"
]
}
import {
FlattenedEncrypt,
flattenedDecrypt,
generateSecret,
generateKeyPair
} from 'jose';
const encoder = new TextEncoder();
const decoder = new TextDecoder();
/**
* Encrypts a plaintext string into a Flattened JWE object.
*
* @param {string|Uint8Array} plaintext - Plaintext payload to encrypt.
* @param {Uint8Array|CryptoKey} key - Key to encrypt with (symmetric secret or recipient public key).
* @param {object} protectedHeader - JWE protected header containing alg and enc.
* @param {object} [options] - Additional options.
* @returns {Promise<import('jose').FlattenedJWE>}
*/
export async function encryptFlattened(plaintext, key, protectedHeader = { alg: 'dir', enc: 'A256GCM' }, options = {}) {
const bytes = typeof plaintext === 'string' ? encoder.encode(plaintext) : plaintext;
const encrypter = new FlattenedEncrypt(bytes);
if (protectedHeader) {
encrypter.setProtectedHeader(protectedHeader);
}
if (options.unprotectedHeader) {
encrypter.setUnprotectedHeader(options.unprotectedHeader);
}
if (options.sharedUnprotectedHeader) {
encrypter.setSharedUnprotectedHeader(options.sharedUnprotectedHeader);
}
if (options.additionalAuthenticatedData) {
const aad = typeof options.additionalAuthenticatedData === 'string'
? encoder.encode(options.additionalAuthenticatedData)
: options.additionalAuthenticatedData;
encrypter.setAdditionalAuthenticatedData(aad);
}
if (options.keyManagementParameters) {
encrypter.setKeyManagementParameters(options.keyManagementParameters);
}
if (options.contentEncryptionKey) {
encrypter.setContentEncryptionKey(options.contentEncryptionKey);
}
if (options.initializationVector) {
encrypter.setInitializationVector(options.initializationVector);
}
return await encrypter.encrypt(key);
}
/**
* Decrypts a Flattened JWE object back into plaintext string and metadata.
*
* @param {import('jose').FlattenedJWE} jwe - Flattened JWE object.
* @param {Uint8Array|CryptoKey} key - Secret key or recipient private key.
* @param {object} [options] - Decryption options.
* @returns {Promise<{ plaintext: string, plaintextBytes: Uint8Array, protectedHeader?: object, unprotectedHeader?: object, sharedUnprotectedHeader?: object, additionalAuthenticatedData?: Uint8Array }>}
*/
export async function decryptFlattened(jwe, key, options) {
const result = await flattenedDecrypt(jwe, key, options);
return {
plaintext: decoder.decode(result.plaintext),
plaintextBytes: result.plaintext,
protectedHeader: result.protectedHeader,
unprotectedHeader: result.unprotectedHeader,
sharedUnprotectedHeader: result.sharedUnprotectedHeader,
additionalAuthenticatedData: result.additionalAuthenticatedData
};
}
export {
FlattenedEncrypt,
flattenedDecrypt,
generateSecret,
generateKeyPair
};
import assert from 'node:assert/strict';
import {
FlattenedEncrypt,
flattenedDecrypt,
generateSecret,
generateKeyPair,
encryptFlattened,
decryptFlattened
} from '../src/index.js';
import * as jose from 'jose';
const encoder = new TextEncoder();
const decoder = new TextDecoder();
// 1. Verify module exports and constructor
assert.equal(typeof FlattenedEncrypt, 'function', 'FlattenedEncrypt must be a class/function');
assert.strictEqual(FlattenedEncrypt, jose.FlattenedEncrypt, 'FlattenedEncrypt must match jose export');
assert.equal(typeof flattenedDecrypt, 'function', 'flattenedDecrypt must be a function');
assert.strictEqual(flattenedDecrypt, jose.flattenedDecrypt, 'flattenedDecrypt must match jose export');
// 2. FlattenedEncrypt produces a Flattened JWE object with ciphertext, iv, tag, and protected header
const secretKey = await generateSecret('A256GCM');
const payloadText = 'Hello, CodeSampleX Secure Payload!';
const plaintextBytes = encoder.encode(payloadText);
const encrypter = new FlattenedEncrypt(plaintextBytes);
encrypter.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' });
const jwe = await encrypter.encrypt(secretKey);
assert.equal(typeof jwe, 'object', 'JWE must be an object');
assert.equal(typeof jwe.ciphertext, 'string', 'ciphertext must be a base64url string');
assert.equal(typeof jwe.iv, 'string', 'iv must be a base64url string');
assert.equal(typeof jwe.tag, 'string', 'tag must be a base64url string');
assert.equal(typeof jwe.protected, 'string', 'protected must be a base64url string');
assert.ok(jwe.ciphertext.length > 0, 'ciphertext must not be empty');
assert.ok(jwe.iv.length > 0, 'iv must not be empty');
assert.ok(jwe.tag.length > 0, 'tag must not be empty');
assert.ok(jwe.protected.length > 0, 'protected header must not be empty');
const decrypted = await flattenedDecrypt(jwe, secretKey);
assert.equal(decoder.decode(decrypted.plaintext), payloadText, 'Decrypted plaintext must match original');
assert.deepEqual(decrypted.protectedHeader, { alg: 'dir', enc: 'A256GCM' }, 'Protected header must match');
// 3. Helper functions encryptFlattened and decryptFlattened
const helperJwe = await encryptFlattened(payloadText, secretKey, { alg: 'dir', enc: 'A256GCM' });
const helperDecrypted = await decryptFlattened(helperJwe, secretKey);
assert.equal(helperDecrypted.plaintext, payloadText, 'Helper decrypted plaintext must match');
assert.deepEqual(helperDecrypted.protectedHeader, { alg: 'dir', enc: 'A256GCM' });
// 4. FlattenedEncrypt supports shared unprotected headers and per-recipient unprotected headers
const sharedHeader = { kid: 'key-2026' };
const recipientHeader = { cty: 'text/plain' };
const encWithHeaders = new FlattenedEncrypt(plaintextBytes);
encWithHeaders.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' });
encWithHeaders.setSharedUnprotectedHeader(sharedHeader);
encWithHeaders.setUnprotectedHeader(recipientHeader);
const jweWithHeaders = await encWithHeaders.encrypt(secretKey);
assert.deepEqual(jweWithHeaders.unprotected, sharedHeader, 'shared unprotected header must be at jwe.unprotected');
assert.deepEqual(jweWithHeaders.header, recipientHeader, 'recipient unprotected header must be at jwe.header');
const decryptedWithHeaders = await flattenedDecrypt(jweWithHeaders, secretKey);
assert.equal(decoder.decode(decryptedWithHeaders.plaintext), payloadText);
assert.deepEqual(decryptedWithHeaders.sharedUnprotectedHeader, sharedHeader);
assert.deepEqual(decryptedWithHeaders.unprotectedHeader, recipientHeader);
// 5. FlattenedEncrypt binds Additional Authenticated Data (AAD) into integrity check
const aadBytes = encoder.encode('authenticated-session-42');
const encWithAad = new FlattenedEncrypt(plaintextBytes);
encWithAad.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' });
encWithAad.setAdditionalAuthenticatedData(aadBytes);
const jweWithAad = await encWithAad.encrypt(secretKey);
assert.equal(typeof jweWithAad.aad, 'string', 'AAD must be base64url encoded');
const decryptedWithAad = await flattenedDecrypt(jweWithAad, secretKey);
assert.equal(decoder.decode(decryptedWithAad.plaintext), payloadText);
assert.deepEqual(decryptedWithAad.additionalAuthenticatedData, aadBytes, 'AAD must match original bytes');
// 6. FlattenedEncrypt supports asymmetric key encryption (e.g. ECDH-ES)
const { publicKey, privateKey } = await generateKeyPair('ECDH-ES');
const encAsymmetric = new FlattenedEncrypt(plaintextBytes);
encAsymmetric.setProtectedHeader({ alg: 'ECDH-ES', enc: 'A256GCM' });
const jweAsymmetric = await encAsymmetric.encrypt(publicKey);
const decryptedAsymmetric = await flattenedDecrypt(jweAsymmetric, privateKey);
assert.equal(decoder.decode(decryptedAsymmetric.plaintext), payloadText);
assert.equal(decryptedAsymmetric.protectedHeader.alg, 'ECDH-ES');
assert.equal(decryptedAsymmetric.protectedHeader.enc, 'A256GCM');
// 7. FlattenedEncrypt fails decryption when ciphertext or tag is modified
const tamperedJwe = {
...jwe,
ciphertext: jwe.ciphertext.slice(0, -4) + 'AAAA'
};
await assert.rejects(
async () => {
await flattenedDecrypt(tamperedJwe, secretKey);
},
(err) => {
return err instanceof Error;
},
'Decryption of tampered ciphertext must reject'
);
// 8. FlattenedEncrypt rejects encryption without setting headers
const unconfiguredEncrypter = new FlattenedEncrypt(plaintextBytes);
await assert.rejects(
async () => {
await unconfiguredEncrypter.encrypt(secretKey);
},
(err) => {
return err instanceof TypeError || err instanceof Error;
},
'Encryption without headers must reject'
);
console.log('Contract tests passed successfully.');
Seeder de origen
anónimo