CodeSampleX

サンプル

jose 6.2.9: importJWK

検証済みサンプル — npm jose 6.2.9: importJWK. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: assert importJWK with an oct JWK returns a Uint8Array…

sha256:76fcd8cd260a2adae4ee2160ae506e46c7b91b3524185704b8f984617ee7c1e9

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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

コントラクト

  1. assert importJWK with an oct JWK returns a Uint8Array containing decoded bytes, which can sign and verify an HS256 JWT
  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
  3. assert importJWK with an EC P-256 JWK and ES256 returns CryptoKeys that sign and verify an ES256 JWT
  4. assert importJWK with an OKP Ed25519 JWK and EdDSA returns CryptoKeys that sign and verify an EdDSA JWT
  5. assert importJWK with extractable: true produces a CryptoKey with extractable set to true
  6. assert importJWK throws a TypeError when jwk is not an object or when an oct JWK is missing the k property
  7. assert importJWK throws a TypeError when alg is omitted for non-oct keys and jwk.alg is not present
  8. assert importJWK throws errors.JOSENotSupported with code ERR_JOSE_NOT_SUPPORTED when kty is unsupported
  9. 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

ソースアーティファクトをダウンロード (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 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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-npm-jose-importjwk",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "jose": "6.2.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify importJWK in pkg:npm/jose@6.2.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.9"
  ],
  "symbols": [
    "importJWK"
  ]
}
src/index.mjs
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 };
}
test/contract.mjs
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.');

オリジンシーダー

匿名