CodeSampleX

Beispiel

jose 6.2.4: compactVerify

Verifiziertes Beispiel für npm jose 6.2.4: compactVerify. Der Vertrag lief auf node 22 · linux debian/x64 · docker und bestand.

sha256:2ec033579bff8896dbd7c9eafe4996e94ddf3a6dfd37616a22ba82ad2eb66217

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung linux 24 · ubuntu · glibc 2.39 x64 npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
verify jose.compactVerify in pkg:npm/jose@6.2.4
Pakete
Symbole
  • jose.compactVerify
Erstellt
2026-09-04T12:23:53Z

Contract

  1. compactVerify verifies a compact JWS signed with a symmetric secret key (HS256) and returns the decoded payload bytes and protected header
  2. compactVerify verifies a compact JWS signed with an asymmetric private key (ES256) using the corresponding public key
  3. compactVerify accepts both string and Uint8Array representations of the compact JWS token
  4. compactVerify supports dynamic key resolution via key resolver callback function and returns the resolved key in the result
  5. compactVerify rejects tokens signed with disallowed algorithms via the algorithms option with JOSEAlgNotAllowed
  6. compactVerify rejects verification when using an incorrect key or tampered signature with JWSSignatureVerificationFailed
  7. compactVerify rejects malformed or invalid compact JWS strings with JWSInvalid

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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.compactVerify 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.compactVerify

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:52629925f5935c56aae539d528acf794fa9f22350c6de51ca6a33ca123e1b4d6","contract":["compactVerify verifies a compact JWS signed with a symmetric secret key (HS256) and returns the decoded payload bytes and protected header","compactVerify verifies a compact JWS signed with an asymmetric private key (ES256) using the corresponding public key","compactVerify accepts both string and Uint8Array representations of the compact JWS token","compactVerify supports dynamic key resolution via key resolver callback function and returns the resolved key in the result","compactVerify rejects tokens signed with disallowed algorithms via the algorithms option with JOSEAlgNotAllowed","compactVerify rejects verification when using an incorrect key or tampered signature with JWSSignatureVerificationFailed","compactVerify rejects malformed or invalid compact JWS strings with JWSInvalid"],"goal":"verify jose.compactVerify in pkg:npm/jose@6.2.4","kind":"HOW","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"symbols":["jose.compactVerify"]},"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.compactVerify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-jose-compact-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-jose-compact-verify",
      "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-compact-verify",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "jose": "6.2.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jose.compactVerify in pkg:npm/jose@6.2.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.4"
  ],
  "symbols": [
    "jose.compactVerify"
  ]
}
src/index.mjs
import { compactVerify } from 'jose';

/**
 * Verifies a compact JWS token using a key or dynamic key resolver callback.
 *
 * @param {string | Uint8Array} jws - Compact JWS string or Uint8Array
 * @param {Uint8Array | import('jose').KeyLike | import('jose').CompactVerifyGetKey} key - Verification key or key resolver callback
 * @param {import('jose').CompactVerifyOptions} [options] - Verification options such as allowed algorithms
 * @returns {Promise<{ payload: Uint8Array, protectedHeader: import('jose').CompactJWSHeaderParameters, key?: import('jose').KeyLike | Uint8Array }>}
 */
export async function verifyCompactJws(jws, key, options) {
  return compactVerify(jws, key, options);
}

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

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const rawMessage = 'CodeSampleX contract verification message';
const payloadBytes = encoder.encode(rawMessage);

// 1. compactVerify verifies a compact JWS signed with a symmetric secret key (HS256) and returns the decoded payload bytes and protected header
{
  const secretKey = await generateSecret('HS256');
  const jws = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'HS256', cty: 'text/plain' })
    .sign(secretKey);

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

  const { payload, protectedHeader } = await verifyCompactJws(jws, secretKey);
  assert.equal(decoder.decode(payload), rawMessage);
  assert.equal(protectedHeader.alg, 'HS256');
  assert.equal(protectedHeader.cty, 'text/plain');
}

// 2. compactVerify verifies a compact JWS signed with an asymmetric private key (ES256) using the corresponding public key
{
  const { publicKey, privateKey } = await generateKeyPair('ES256');
  const jws = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'ES256' })
    .sign(privateKey);

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

// 3. compactVerify accepts both string and Uint8Array representations of the compact JWS token
{
  const secretKey = await generateSecret('HS256');
  const jwsString = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'HS256' })
    .sign(secretKey);
  const jwsUint8Array = encoder.encode(jwsString);

  const resultFromString = await compactVerify(jwsString, secretKey);
  const resultFromUint8 = await compactVerify(jwsUint8Array, secretKey);

  assert.equal(decoder.decode(resultFromString.payload), rawMessage);
  assert.equal(decoder.decode(resultFromUint8.payload), rawMessage);
  assert.equal(resultFromString.protectedHeader.alg, 'HS256');
  assert.equal(resultFromUint8.protectedHeader.alg, 'HS256');
}

// 4. compactVerify supports dynamic key resolution via key resolver callback function and returns the resolved key in the result
{
  const keyA = await generateSecret('HS256');
  const keyB = await generateSecret('HS256');
  const keyStore = new Map([
    ['key-1', keyA],
    ['key-2', keyB],
  ]);

  const jws = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'HS256', kid: 'key-2' })
    .sign(keyB);

  const keyResolver = async (protectedHeader) => {
    const key = keyStore.get(protectedHeader.kid);
    if (!key) throw new Error('Key not found');
    return key;
  };

  const { payload, protectedHeader, key } = await compactVerify(jws, keyResolver);
  assert.equal(decoder.decode(payload), rawMessage);
  assert.equal(protectedHeader.kid, 'key-2');
  assert.equal(key, keyB);
}

// 5. compactVerify rejects tokens signed with disallowed algorithms via the algorithms option with JOSEAlgNotAllowed
{
  const secretKey = await generateSecret('HS256');
  const jws = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'HS256' })
    .sign(secretKey);

  await assert.rejects(
    async () => {
      await compactVerify(jws, secretKey, {
        algorithms: ['ES256'],
      });
    },
    (err) => {
      assert(err instanceof errors.JOSEAlgNotAllowed);
      assert.equal(err.code, 'ERR_JOSE_ALG_NOT_ALLOWED');
      return true;
    }
  );
}

// 6. compactVerify rejects verification when using an incorrect key or tampered signature with JWSSignatureVerificationFailed
{
  const key1 = await generateSecret('HS256');
  const key2 = await generateSecret('HS256');

  const jws = await new CompactSign(payloadBytes)
    .setProtectedHeader({ alg: 'HS256' })
    .sign(key1);

  // Mismatched key
  await assert.rejects(
    async () => {
      await compactVerify(jws, key2);
    },
    (err) => {
      assert(err instanceof errors.JWSSignatureVerificationFailed);
      assert.equal(err.code, 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED');
      return true;
    }
  );

  // Tampered payload
  const parts = jws.split('.');
  parts[1] = Buffer.from('tampered-payload').toString('base64url');
  const tamperedJws = parts.join('.');

  await assert.rejects(
    async () => {
      await compactVerify(tamperedJws, key1);
    },
    (err) => {
      assert(err instanceof errors.JWSSignatureVerificationFailed);
      assert.equal(err.code, 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED');
      return true;
    }
  );
}

// 7. compactVerify rejects malformed or invalid compact JWS strings with JWSInvalid
{
  const secretKey = await generateSecret('HS256');

  await assert.rejects(
    async () => {
      await compactVerify('invalid.jws.extra.four.segments', secretKey);
    },
    (err) => {
      assert(err instanceof errors.JWSInvalid);
      assert.equal(err.code, 'ERR_JWS_INVALID');
      return true;
    }
  );

  await assert.rejects(
    async () => {
      await compactVerify('not-a-valid-token', secretKey);
    },
    (err) => {
      assert(err instanceof errors.JWSInvalid);
      assert.equal(err.code, 'ERR_JWS_INVALID');
      return true;
    }
  );
}

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

Ursprungs-Seeder

anonym