CodeSampleX

Exemple

jose 6.2.4: CompactSign

Échantillon vérifié pour npm jose 6.2.4: CompactSign. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:ff3f647630ddea3c8f1ca75989293657ec1bffd70a6c725e0c6290cb5e0f4f94

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-04

Cas

HOW
Objectif
verify jose.CompactSign in pkg:npm/jose@6.2.4
Paquets
Symboles
  • jose.CompactSign
Environnement
node 22.23.2
Créé
2026-09-04T11:29:52Z

Contrat

  1. CompactSign produces a three-part compact JWS using a symmetric secret key and HS256 algorithm that verifies with compactVerify
  2. CompactSign produces a compact JWS using an ECDSA private key and ES256 algorithm that verifies with the public key
  3. CompactSign produces a compact JWS using an RSA-PSS private key and PS256 algorithm that verifies with the public key
  4. CompactSign attaches custom protected headers including kid, typ, and cty to the signed token
  5. CompactSign signs an empty Uint8Array payload producing a compact JWS with an empty payload segment
  6. CompactSign rejects signing without a protected header with JWSInvalid error
  7. CompactSign throws a TypeError when initialized with a non-Uint8Array payload
  8. CompactSign rejects signing when a symmetric algorithm header is signed with an asymmetric key

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

.npmrc
audit=false
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.CompactSign 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.CompactSign

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:f5bdd270ed5083e493c469f7df95dcb9b23077a80fb65d454ecf3a3c432daa3e","contract":["CompactSign produces a three-part compact JWS using a symmetric secret key and HS256 algorithm that verifies with compactVerify","CompactSign produces a compact JWS using an ECDSA private key and ES256 algorithm that verifies with the public key","CompactSign produces a compact JWS using an RSA-PSS private key and PS256 algorithm that verifies with the public key","CompactSign attaches custom protected headers including kid, typ, and cty to the signed token","CompactSign signs an empty Uint8Array payload producing a compact JWS with an empty payload segment","CompactSign rejects signing without a protected header with JWSInvalid error","CompactSign throws a TypeError when initialized with a non-Uint8Array payload","CompactSign rejects signing when a symmetric algorithm header is signed with an asymmetric key"],"goal":"verify jose.CompactSign in pkg:npm/jose@6.2.4","kind":"HOW","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"symbols":["jose.CompactSign"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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.4"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.4","symbols":["jose.CompactSign"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jose-compact-sign",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jose-compact-sign",
      "version": "1.0.0",
      "license": "MIT-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": "sample-jose-compact-sign",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jose": "6.2.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jose.CompactSign in pkg:npm/jose@6.2.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.4"
  ],
  "symbols": [
    "jose.CompactSign"
  ]
}
src/index.mjs
import { CompactSign, compactVerify } from 'jose';

/**
 * Signs a payload into a compact JWS token (3 dot-separated base64url parts).
 *
 * @param {Uint8Array} payload - Raw byte payload to sign
 * @param {import('jose').CompactJWSHeaderParameters} protectedHeader - JWS protected header (must include alg)
 * @param {Uint8Array | import('jose').KeyLike} key - Symmetric secret or asymmetric private key
 * @param {import('jose').SignOptions} [options] - Additional sign options
 * @returns {Promise<string>} Compact JWS string
 */
export async function createCompactSign(payload, protectedHeader, key, options) {
  const signer = new CompactSign(payload).setProtectedHeader(protectedHeader);
  return signer.sign(key, options);
}

export { CompactSign, compactVerify };
export default CompactSign;
test/contract.mjs
import assert from 'node:assert/strict';
import {
  CompactSign,
  compactVerify,
  generateSecret,
  generateKeyPair,
  errors
} from 'jose';
import { createCompactSign } from '../src/index.mjs';

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const testPayload = encoder.encode('CompactSign contract test payload');

// 1. CompactSign produces a three-part compact JWS using a symmetric secret key and HS256 algorithm that verifies with compactVerify
{
  const secretKey = await generateSecret('HS256');
  const jws = await createCompactSign(testPayload, { alg: 'HS256' }, secretKey);

  assert.equal(typeof jws, 'string');
  const parts = jws.split('.');
  assert.equal(parts.length, 3);

  const { payload, protectedHeader } = await compactVerify(jws, secretKey);
  assert.equal(decoder.decode(payload), 'CompactSign contract test payload');
  assert.equal(protectedHeader.alg, 'HS256');
}

// 2. CompactSign produces a compact JWS using an ECDSA private key and ES256 algorithm that verifies with the public key
{
  const { publicKey, privateKey } = await generateKeyPair('ES256');
  const signer = new CompactSign(testPayload);
  const jws = await signer.setProtectedHeader({ alg: 'ES256' }).sign(privateKey);

  const { payload, protectedHeader } = await compactVerify(jws, publicKey);
  assert.equal(decoder.decode(payload), 'CompactSign contract test payload');
  assert.equal(protectedHeader.alg, 'ES256');
}

// 3. CompactSign produces a compact JWS using an RSA-PSS private key and PS256 algorithm that verifies with the public key
{
  const { publicKey, privateKey } = await generateKeyPair('PS256');
  const signer = new CompactSign(testPayload);
  const jws = await signer.setProtectedHeader({ alg: 'PS256' }).sign(privateKey);

  const { payload, protectedHeader } = await compactVerify(jws, publicKey);
  assert.equal(decoder.decode(payload), 'CompactSign contract test payload');
  assert.equal(protectedHeader.alg, 'PS256');
}

// 4. CompactSign attaches custom protected headers including kid, typ, and cty to the signed token
{
  const secretKey = await generateSecret('HS256');
  const signer = new CompactSign(testPayload);
  const customHeader = {
    alg: 'HS256',
    kid: 'signing-key-1',
    typ: 'JWT',
    cty: 'text/plain'
  };
  const jws = await signer.setProtectedHeader(customHeader).sign(secretKey);

  const { protectedHeader } = await compactVerify(jws, secretKey);
  assert.equal(protectedHeader.kid, 'signing-key-1');
  assert.equal(protectedHeader.typ, 'JWT');
  assert.equal(protectedHeader.cty, 'text/plain');
}

// 5. CompactSign signs an empty Uint8Array payload producing a compact JWS with an empty payload segment
{
  const secretKey = await generateSecret('HS256');
  const emptyPayload = new Uint8Array(0);
  const signer = new CompactSign(emptyPayload);
  const jws = await signer.setProtectedHeader({ alg: 'HS256' }).sign(secretKey);

  const parts = jws.split('.');
  assert.equal(parts.length, 3);
  assert.equal(parts[1], '');

  const { payload } = await compactVerify(jws, secretKey);
  assert.equal(payload.length, 0);
}

// 6. CompactSign rejects signing without a protected header with JWSInvalid error
{
  const secretKey = await generateSecret('HS256');
  const signer = new CompactSign(testPayload);

  await assert.rejects(
    async () => {
      await signer.sign(secretKey);
    },
    (err) => {
      assert(err instanceof errors.JWSInvalid);
      assert.equal(err.code, 'ERR_JWS_INVALID');
      return true;
    }
  );
}

// 7. CompactSign throws a TypeError when initialized with a non-Uint8Array payload
{
  assert.throws(
    () => {
      new CompactSign('not a uint8array');
    },
    {
      name: 'TypeError',
      message: 'payload must be an instance of Uint8Array'
    }
  );

  assert.throws(
    () => {
      new CompactSign(null);
    },
    {
      name: 'TypeError'
    }
  );
}

// 8. CompactSign rejects signing when a symmetric algorithm header is signed with an asymmetric key
{
  const { privateKey } = await generateKeyPair('ES256');
  const signer = new CompactSign(testPayload).setProtectedHeader({ alg: 'HS256' });

  await assert.rejects(
    async () => {
      await signer.sign(privateKey);
    },
    {
      name: 'TypeError'
    }
  );
}

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

Seeder d'origine

anonyme