CodeSampleX

샘플

jose 6.2.9: exportJWK

검증된 샘플 — npm jose 6.2.9: exportJWK. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: exportJWK exports extractable RSA private and public keys to…

sha256:24d869138a8a58f473a798d7d5f36a0d5b5fe023c86cb40f3a81ab052dcf70db

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

실행 증거

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

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

검증 실행 환경

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

케이스

HOW
목표
verify exportJWK in pkg:npm/jose@6.2.9
패키지
심벌
  • exportJWK
생성일
2026-08-26T10:59:41Z

컨트랙트

  1. exportJWK exports extractable RSA private and public keys to JWK format with kty RSA and appropriate components
  2. exportJWK exports extractable EC private and public keys with kty EC, crv P-256, coordinates x, y, and private parameter d
  3. exportJWK exports extractable OKP (Ed25519) private and public keys with kty OKP, crv Ed25519, public coordinate x, and private scalar d
  4. exportJWK exports symmetric CryptoKey and Uint8Array secrets to JWK format with kty oct and base64url-encoded k parameter
  5. exportJWK results can be imported back with importJWK to successfully sign and verify JWS payloads
  6. exportJWK rejects with TypeError when given non-extractable CryptoKey
  7. exportJWK rejects with TypeError when invoked with invalid key inputs such as null, undefined, numbers, or non-key objects

파일

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

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

소스

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

Use EXACTLY these public packages and versions:
  - pkg:npm/jose@6.2.9
Demonstrate these symbols/APIs:
  - exportJWK

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:0c9c41fa21ecad985ac764f81d6d97d549068c4d02752b339c205669a51ce978","contract":["exportJWK exports extractable RSA private and public keys to JWK format with kty RSA and appropriate components","exportJWK exports extractable EC private and public keys with kty EC, crv P-256, coordinates x, y, and private parameter d","exportJWK exports extractable OKP (Ed25519) private and public keys with kty OKP, crv Ed25519, public coordinate x, and private scalar d","exportJWK exports symmetric CryptoKey and Uint8Array secrets to JWK format with kty oct and base64url-encoded k parameter","exportJWK results can be imported back with importJWK to successfully sign and verify JWS payloads","exportJWK rejects with TypeError when given non-extractable CryptoKey","exportJWK rejects with TypeError when invoked with invalid key inputs such as null, undefined, numbers, or non-key objects"],"goal":"verify exportJWK in pkg:npm/jose@6.2.9","kind":"HOW","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"symbols":["exportJWK"]},"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.9"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.9","symbols":["exportJWK"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jose-exportjwk",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jose-exportjwk",
      "version": "1.0.0",
      "dependencies": {
        "jose": "6.2.9"
      }
    },
    "node_modules/jose": {
      "version": "6.2.9",
      "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.9.tgz",
      "integrity": "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA==",
      "license": "MIT",
      "funding": {
        "url": "https://github.com/sponsors/panva"
      }
    }
  }
}
package.json
{
  "name": "sample-jose-exportjwk",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jose": "6.2.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify exportJWK in pkg:npm/jose@6.2.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.9"
  ],
  "symbols": [
    "exportJWK"
  ]
}
src/index.mjs
import {
  exportJWK,
  importJWK,
  generateKeyPair,
  generateSecret,
  CompactSign,
  compactVerify
} from 'jose';

/**
 * Export a CryptoKey or KeyLike to a JWK.
 * @param {import('jose').CryptoKey | import('jose').KeyLike | Uint8Array} key
 * @returns {Promise<import('jose').JWK>}
 */
export async function exportKeyToJWK(key) {
  return await exportJWK(key);
}

/**
 * Export an asymmetric key pair to public and private JWKs.
 * @param {{ publicKey: any, privateKey: any }} keyPair
 * @returns {Promise<{ publicJwk: import('jose').JWK, privateJwk: import('jose').JWK }>}
 */
export async function exportKeyPairToJWK(keyPair) {
  const [publicJwk, privateJwk] = await Promise.all([
    exportJWK(keyPair.publicKey),
    exportJWK(keyPair.privateKey)
  ]);
  return { publicJwk, privateJwk };
}

/**
 * Export a symmetric secret (CryptoKey or Uint8Array) to an oct JWK.
 * @param {import('jose').CryptoKey | Uint8Array} secret
 * @returns {Promise<import('jose').JWK>}
 */
export async function exportSecretToJWK(secret) {
  return await exportJWK(secret);
}

/**
 * Perform a full round-trip export and import of an extractable key pair, verifying signature operations.
 * @param {string} alg - e.g. 'ES256', 'RS256', or 'EdDSA'
 * @param {string} [crv]
 * @returns {Promise<{ originalExport: import('jose').JWK, verified: boolean }>}
 */
export async function roundtripKeyPair(alg, crv) {
  const options = { extractable: true, ...(crv ? { crv } : {}) };
  const keyPair = await generateKeyPair(alg, options);
  const privateJwk = await exportJWK(keyPair.privateKey);
  const publicJwk = await exportJWK(keyPair.publicKey);

  const importedPrivate = await importJWK(privateJwk, alg);
  const importedPublic = await importJWK(publicJwk, alg);

  const payload = new TextEncoder().encode('sample verification payload');
  const jws = await new CompactSign(payload)
    .setProtectedHeader({ alg })
    .sign(importedPrivate);

  const { payload: verifiedPayload } = await compactVerify(jws, importedPublic);
  const verified = new TextDecoder().decode(verifiedPayload) === 'sample verification payload';

  return { originalExport: publicJwk, verified };
}

export {
  exportJWK,
  importJWK,
  generateKeyPair,
  generateSecret
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  exportKeyToJWK,
  exportKeyPairToJWK,
  exportSecretToJWK,
  roundtripKeyPair,
  exportJWK,
  importJWK,
  generateKeyPair,
  generateSecret
} from '../src/index.mjs';

// 1. exportJWK exports extractable RSA private and public keys to JWK format with kty 'RSA' and appropriate components
{
  const rsaPair = await generateKeyPair('RS256', { extractable: true });
  const { publicJwk, privateJwk } = await exportKeyPairToJWK(rsaPair);

  assert.equal(publicJwk.kty, 'RSA');
  assert.equal(typeof publicJwk.n, 'string');
  assert.equal(typeof publicJwk.e, 'string');
  assert.equal(publicJwk.d, undefined);
  assert.equal(publicJwk.p, undefined);

  assert.equal(privateJwk.kty, 'RSA');
  assert.equal(typeof privateJwk.n, 'string');
  assert.equal(typeof privateJwk.e, 'string');
  assert.equal(typeof privateJwk.d, 'string');
  assert.equal(typeof privateJwk.p, 'string');
  assert.equal(typeof privateJwk.q, 'string');
  assert.equal(typeof privateJwk.dp, 'string');
  assert.equal(typeof privateJwk.dq, 'string');
  assert.equal(typeof privateJwk.qi, 'string');
}

// 2. exportJWK exports extractable EC private and public keys with kty 'EC', crv 'P-256', coordinates x, y, and private parameter d
{
  const ecPair = await generateKeyPair('ES256', { extractable: true });
  const publicJwk = await exportKeyToJWK(ecPair.publicKey);
  const privateJwk = await exportKeyToJWK(ecPair.privateKey);

  assert.equal(publicJwk.kty, 'EC');
  assert.equal(publicJwk.crv, 'P-256');
  assert.equal(typeof publicJwk.x, 'string');
  assert.equal(typeof publicJwk.y, 'string');
  assert.equal(publicJwk.d, undefined);

  assert.equal(privateJwk.kty, 'EC');
  assert.equal(privateJwk.crv, 'P-256');
  assert.equal(typeof privateJwk.x, 'string');
  assert.equal(typeof privateJwk.y, 'string');
  assert.equal(typeof privateJwk.d, 'string');
}

// 3. exportJWK exports extractable OKP (Ed25519) private and public keys with kty 'OKP', crv 'Ed25519', public coordinate x, and private scalar d
{
  const okpPair = await generateKeyPair('EdDSA', { crv: 'Ed25519', extractable: true });
  const publicJwk = await exportKeyToJWK(okpPair.publicKey);
  const privateJwk = await exportKeyToJWK(okpPair.privateKey);

  assert.equal(publicJwk.kty, 'OKP');
  assert.equal(publicJwk.crv, 'Ed25519');
  assert.equal(typeof publicJwk.x, 'string');
  assert.equal(publicJwk.d, undefined);

  assert.equal(privateJwk.kty, 'OKP');
  assert.equal(privateJwk.crv, 'Ed25519');
  assert.equal(typeof privateJwk.x, 'string');
  assert.equal(typeof privateJwk.d, 'string');
}

// 4. exportJWK exports symmetric CryptoKey and Uint8Array secrets to JWK format with kty 'oct' and base64url-encoded k parameter
{
  const cryptoSecret = await generateSecret('HS256', { extractable: true });
  const jwkFromCryptoKey = await exportSecretToJWK(cryptoSecret);
  assert.equal(jwkFromCryptoKey.kty, 'oct');
  assert.equal(typeof jwkFromCryptoKey.k, 'string');
  assert.ok(jwkFromCryptoKey.k.length > 0);

  const rawSecret = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
  const jwkFromRaw = await exportSecretToJWK(rawSecret);
  assert.equal(jwkFromRaw.kty, 'oct');
  assert.equal(typeof jwkFromRaw.k, 'string');
  assert.ok(jwkFromRaw.k.length > 0);
}

// 5. exportJWK results can be imported back with importJWK to successfully sign and verify JWS payloads
{
  const es256Result = await roundtripKeyPair('ES256');
  assert.equal(es256Result.originalExport.kty, 'EC');
  assert.equal(es256Result.verified, true);

  const rs256Result = await roundtripKeyPair('RS256');
  assert.equal(rs256Result.originalExport.kty, 'RSA');
  assert.equal(rs256Result.verified, true);
}

// 6. exportJWK rejects with TypeError when given non-extractable CryptoKey
{
  const nonExtractablePair = await generateKeyPair('ES256', { extractable: false });
  await assert.rejects(
    async () => {
      await exportJWK(nonExtractablePair.privateKey);
    },
    (err) => {
      assert(err instanceof TypeError);
      assert.match(err.message, /non-extractable/);
      return true;
    }
  );

  const nonExtractableSecret = await generateSecret('HS256', { extractable: false });
  await assert.rejects(
    async () => {
      await exportJWK(nonExtractableSecret);
    },
    (err) => {
      assert(err instanceof TypeError);
      assert.match(err.message, /non-extractable/);
      return true;
    }
  );
}

// 7. exportJWK rejects with TypeError when invoked with invalid key inputs such as null, undefined, numbers, or non-key objects
{
  const invalidInputs = [null, undefined, 'not-a-key', 12345, {}, true];
  for (const input of invalidInputs) {
    await assert.rejects(
      async () => {
        await exportJWK(input);
      },
      (err) => {
        assert(err instanceof TypeError);
        return true;
      }
    );
  }
}

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

오리진 시더

익명