Пример
jose 6.2.9: importJWK
Проверенный пример — npm jose 6.2.9: importJWK. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: assert importJWK with an oct JWK returns…
sha256:76fcd8cd260a2adae4ee2160ae506e46c7b91b3524185704b8f984617ee7c1e9
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 2
- Ключи подписи, собравшие его
- 1
Заявленная среда
node 22 linux 24 · ubuntu · glibc 2.39 x64 node 22 javascript 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 importJWK in pkg:npm/jose@6.2.9
- Пакеты
- Символы
-
- importJWK
- Окружение
- node 22
- Создан
- 2026-08-26T10:59:57Z
Контракт
- assert importJWK with an oct JWK returns a Uint8Array containing decoded bytes, which can sign and verify an HS256 JWT
- assert importJWK with an RSA public JWK and RS256 returns a public CryptoKey, and an RSA private JWK returns a private CryptoKey that signs a JWT verified by the public CryptoKey
- assert importJWK with an EC P-256 JWK and ES256 returns CryptoKeys that sign and verify an ES256 JWT
- assert importJWK with an OKP Ed25519 JWK and EdDSA returns CryptoKeys that sign and verify an EdDSA JWT
- assert importJWK with extractable: true produces a CryptoKey with extractable set to true
- assert importJWK throws a TypeError when jwk is not an object or when an oct JWK is missing the k property
- assert importJWK throws a TypeError when alg is omitted for non-oct keys and jwk.alg is not present
- assert importJWK throws errors.JOSENotSupported with code ERR_JOSE_NOT_SUPPORTED when kty is unsupported
- assert importJWK returns a Promise and never throws synchronously, rejecting asynchronously on invalid input
Файлы
- 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 importJWK 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:
- importJWK
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:df356a4917654b4aad86e3b5bb348c7a06d0ad7da418ebd24b7ecc98b32835d9","contract":["assert importJWK with an oct JWK returns a Uint8Array containing decoded bytes, which can sign and verify an HS256 JWT","assert importJWK with an RSA public JWK and RS256 returns a public CryptoKey, and an RSA private JWK returns a private CryptoKey that signs a JWT verified by the public CryptoKey","assert importJWK with an EC P-256 JWK and ES256 returns CryptoKeys that sign and verify an ES256 JWT","assert importJWK with an OKP Ed25519 JWK and EdDSA returns CryptoKeys that sign and verify an EdDSA JWT","assert importJWK with extractable: true produces a CryptoKey with extractable set to true","assert importJWK throws a TypeError when jwk is not an object or when an oct JWK is missing the k property","assert importJWK throws a TypeError when alg is omitted for non-oct keys and jwk.alg is not present","assert importJWK throws errors.JOSENotSupported with code ERR_JOSE_NOT_SUPPORTED when kty is unsupported","assert importJWK returns a Promise and never throws synchronously, rejecting asynchronously on invalid input"],"goal":"verify importJWK in pkg:npm/jose@6.2.9","kind":"HOW","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"symbols":["importJWK"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jose@6.2.9"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.9","symbols":["importJWK"],"verifierAdapter":"node-typescript@1"}
{
"name": "csx-sample-npm-jose-importjwk",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "csx-sample-npm-jose-importjwk",
"version": "1.0.0",
"license": "MIT-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": "csx-sample-npm-jose-importjwk",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"jose": "6.2.9"
}
}
{
"schemaVersion": 1,
"goal": "verify importJWK in pkg:npm/jose@6.2.9",
"kind": "HOW",
"packages": [
"pkg:npm/jose@6.2.9"
],
"symbols": [
"importJWK"
]
}
import { importJWK, SignJWT, jwtVerify, errors } from 'jose';
/**
* Import a symmetric (oct) JSON Web Key into a Uint8Array key suitable for HMAC operations.
*
* @param {object} jwk - JSON Web Key object with kty: 'oct'
* @param {string} [alg] - Target algorithm (e.g. 'HS256')
* @returns {Promise<Uint8Array>}
*/
export async function importSymmetricJWK(jwk, alg) {
return importJWK(jwk, alg);
}
/**
* Import an asymmetric (RSA, EC, or OKP) JSON Web Key into a WebCrypto CryptoKey.
*
* @param {object} jwk - JSON Web Key object (e.g. kty: 'RSA' | 'EC' | 'OKP')
* @param {string} [alg] - JWA algorithm identifier (e.g. 'RS256', 'ES256', 'EdDSA')
* @param {object} [options] - Key import options such as extractable
* @returns {Promise<CryptoKey>}
*/
export async function importAsymmetricJWK(jwk, alg, options) {
return importJWK(jwk, alg, options);
}
/**
* Sign and verify a token using keys imported via importJWK.
*
* @param {object} payload - Token payload
* @param {object} privateJWK - Signing key JWK
* @param {object} publicJWK - Verification key JWK (or symmetric JWK)
* @param {string} alg - Algorithm identifier (e.g. 'HS256', 'RS256', 'ES256', 'EdDSA')
* @returns {Promise<{ jwt: string, payload: object }>}
*/
export async function signAndVerifyWithJWK(payload, privateJWK, publicJWK, alg) {
const signKey = await importJWK(privateJWK, alg);
const verifyKey = await importJWK(publicJWK, alg);
const jwt = await new SignJWT(payload)
.setProtectedHeader({ alg })
.setIssuedAt()
.sign(signKey);
const { payload: verifiedPayload } = await jwtVerify(jwt, verifyKey);
return { jwt, payload: verifiedPayload };
}
import assert from 'node:assert/strict';
import {
importJWK,
exportJWK,
generateKeyPair,
SignJWT,
jwtVerify,
errors
} from 'jose';
import {
importSymmetricJWK,
importAsymmetricJWK,
signAndVerifyWithJWK
} from '../src/index.mjs';
// 1. assert importJWK with an oct JWK returns a Uint8Array containing decoded bytes, which can sign and verify an HS256 JWT
{
const octJwk = {
kty: 'oct',
k: 'GawgguFyGrWKav7AX4VKUg',
alg: 'HS256'
};
const key = await importJWK(octJwk);
assert(key instanceof Uint8Array, 'Symmetric JWK must import as Uint8Array');
assert.equal(key.length, 16, 'Decoded oct key length mismatch');
const jwt = await new SignJWT({ sub: 'user_oct' })
.setProtectedHeader({ alg: 'HS256' })
.sign(key);
const { payload } = await jwtVerify(jwt, key);
assert.equal(payload.sub, 'user_oct');
}
// 2. assert importJWK with an RSA public JWK and RS256 returns a public CryptoKey, and an RSA private JWK returns a private CryptoKey that signs a JWT verified by the public CryptoKey
{
const { publicKey, privateKey } = await generateKeyPair('RS256', { extractable: true });
const pubJwk = await exportJWK(publicKey);
const privJwk = await exportJWK(privateKey);
const importedPub = await importJWK(pubJwk, 'RS256');
const importedPriv = await importJWK(privJwk, 'RS256');
assert(importedPub instanceof CryptoKey, 'RSA public key must be CryptoKey');
assert.equal(importedPub.type, 'public');
assert(importedPriv instanceof CryptoKey, 'RSA private key must be CryptoKey');
assert.equal(importedPriv.type, 'private');
const { payload } = await signAndVerifyWithJWK({ sub: 'user_rsa' }, privJwk, pubJwk, 'RS256');
assert.equal(payload.sub, 'user_rsa');
}
// 3. assert importJWK with an EC P-256 JWK and ES256 returns CryptoKeys that sign and verify an ES256 JWT
{
const { publicKey, privateKey } = await generateKeyPair('ES256', { extractable: true });
const pubJwk = await exportJWK(publicKey);
const privJwk = await exportJWK(privateKey);
const importedPub = await importJWK(pubJwk, 'ES256');
const importedPriv = await importJWK(privJwk, 'ES256');
assert.equal(importedPub.type, 'public');
assert.equal(importedPriv.type, 'private');
const { payload } = await signAndVerifyWithJWK({ sub: 'user_ec' }, privJwk, pubJwk, 'ES256');
assert.equal(payload.sub, 'user_ec');
}
// 4. assert importJWK with an OKP Ed25519 JWK and EdDSA returns CryptoKeys that sign and verify an EdDSA JWT
{
const { publicKey, privateKey } = await generateKeyPair('EdDSA', { crv: 'Ed25519', extractable: true });
const pubJwk = await exportJWK(publicKey);
const privJwk = await exportJWK(privateKey);
const importedPub = await importJWK(pubJwk, 'EdDSA');
const importedPriv = await importJWK(privJwk, 'EdDSA');
assert.equal(importedPub.type, 'public');
assert.equal(importedPriv.type, 'private');
const { payload } = await signAndVerifyWithJWK({ sub: 'user_okp' }, privJwk, pubJwk, 'EdDSA');
assert.equal(payload.sub, 'user_okp');
}
// 5. assert importJWK with extractable: true produces a CryptoKey with extractable set to true
{
const { publicKey } = await generateKeyPair('RS256', { extractable: true });
const pubJwk = await exportJWK(publicKey);
const keyExtTrue = await importJWK(pubJwk, 'RS256', { extractable: true });
assert.equal(keyExtTrue.extractable, true);
const keyExtFalse = await importJWK(pubJwk, 'RS256', { extractable: false });
assert.equal(keyExtFalse.extractable, false);
}
// 6. assert importJWK throws a TypeError when jwk is not an object or when an oct JWK is missing the k property
{
await assert.rejects(
async () => importJWK('not-an-object'),
{
name: 'TypeError',
message: 'JWK must be an object'
}
);
await assert.rejects(
async () => importJWK({ kty: 'oct' }, 'HS256'),
{
name: 'TypeError',
message: 'missing "k" (Key Value) Parameter value'
}
);
}
// 7. assert importJWK throws a TypeError when alg is omitted for non-oct keys and jwk.alg is not present
{
await assert.rejects(
async () => importJWK({ kty: 'RSA', n: 'abc', e: 'AQAB' }),
{
name: 'TypeError',
message: '"alg" argument is required when "jwk.alg" is not present'
}
);
}
// 8. assert importJWK throws errors.JOSENotSupported with code ERR_JOSE_NOT_SUPPORTED when kty is unsupported
{
await assert.rejects(
async () => importJWK({ kty: 'UNSUPPORTED' }, 'HS256'),
(err) => {
assert(err instanceof errors.JOSENotSupported);
assert.equal(err.code, 'ERR_JOSE_NOT_SUPPORTED');
return true;
}
);
}
// 9. assert importJWK returns a Promise and never throws synchronously, rejecting asynchronously on invalid input
{
const syncReturn = importJWK(null);
assert(syncReturn instanceof Promise, 'importJWK must return a Promise');
await assert.rejects(syncReturn, { name: 'TypeError' });
}
console.log('All contract assertions passed successfully.');
Исходный сидер
аноним