CodeSampleX

샘플

jose 6.2.4: CompactSign

검증된 샘플 — npm jose 6.2.4: CompactSign. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: CompactSign produces a three-part compact JWS using a…

sha256:ff3f647630ddea3c8f1ca75989293657ec1bffd70a6c725e0c6290cb5e0f4f94

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify jose.CompactSign in pkg:npm/jose@6.2.4
패키지
심벌
  • jose.CompactSign
환경
node 22.23.2
생성일
2026-09-04T11:29:52Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

.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.');

오리진 시더

익명