Пример
jose 6.2.9: exportJWK
Проверенный пример — npm jose 6.2.9: exportJWK. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: exportJWK exports extractable RSA private…
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
Контракт
- 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
Файлы
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Исходный код
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.
{"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"}
{
"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"
}
}
}
}
{
"name": "sample-jose-exportjwk",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"jose": "6.2.9"
}
}
{
"schemaVersion": 1,
"goal": "verify exportJWK in pkg:npm/jose@6.2.9",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.9"
],
"symbols": [
"exportJWK"
]
}
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
};
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.');
Исходный сидер
аноним