CodeSampleX

Пример

jose 6.2.4: SignJWT

Проверенный пример — npm jose 6.2.4: SignJWT. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: SignJWT signs a JWT with a symmetric secret…

sha256:d6f4215be955952a98a9a2206817f4ced15397bff02e67bfaafb1d77fc341ea1

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-06

Кейс

HOW
Цель
verify jose.SignJWT in pkg:npm/jose@6.2.4
Пакеты
Символы
  • jose.SignJWT
Создан
2026-09-06T04:57:23Z

Контракт

  1. SignJWT signs a JWT with a symmetric secret key (HS256) and returns a compact 3-part serialized string verifiable by jwtVerify
  2. SignJWT signs a JWT with an asymmetric private key (ES256) verifiable by the corresponding public key
  3. SignJWT sets standard claims including issuer, subject, audience, expiration time, and JWT ID via builder methods
  4. SignJWT supports multiple audience claims specified as an array of strings
  5. SignJWT rejects signing when neither protectedHeader nor unprotectedHeader is set with JWSInvalid
  6. SignJWT produced tokens with past expiration times are rejected during verification with JWTExpired
  7. SignJWT produced tokens with future not-before times are rejected during verification with JWTClaimValidationFailed

Файлы

  • 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 jose.SignJWT 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.SignJWT

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:57d8d332dee068c4caa9391c63816dff94465493b1a72152db642ae4e5ae6382","contract":["SignJWT signs a JWT with a symmetric secret key (HS256) and returns a compact 3-part serialized string verifiable by jwtVerify","SignJWT signs a JWT with an asymmetric private key (ES256) verifiable by the corresponding public key","SignJWT sets standard claims including issuer, subject, audience, expiration time, and JWT ID via builder methods","SignJWT supports multiple audience claims specified as an array of strings","SignJWT rejects signing when neither protectedHeader nor unprotectedHeader is set with JWSInvalid","SignJWT produced tokens with past expiration times are rejected during verification with JWTExpired","SignJWT produced tokens with future not-before times are rejected during verification with JWTClaimValidationFailed"],"goal":"verify jose.SignJWT in pkg:npm/jose@6.2.4","kind":"HOW","packages":["pkg:npm/jose@6.2.4"],"schemaVersion":1,"symbols":["jose.SignJWT"]},"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.4"],"schemaVersion":1,"subject":"pkg:npm/jose@6.2.4","symbols":["jose.SignJWT"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-jose-sign-jwt",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-jose-sign-jwt",
      "version": "1.0.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": "verify-jose-sign-jwt",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "jose": "6.2.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jose.SignJWT in pkg:npm/jose@6.2.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jose@6.2.4"
  ],
  "symbols": [
    "jose.SignJWT"
  ]
}
src/index.mjs
import { SignJWT } from 'jose';

/**
 * Creates and signs a JSON Web Token (JWT) with the provided payload, protected header, and options.
 *
 * @param {Record<string, unknown>} payload - Claims payload
 * @param {Uint8Array | import('jose').KeyLike} key - Signing key
 * @param {import('jose').JWTHeaderParameters} protectedHeader - Protected header parameters
 * @param {object} [options] - Additional standard claims
 * @param {string} [options.issuer] - Issuer claim
 * @param {string | string[]} [options.audience] - Audience claim
 * @param {string} [options.subject] - Subject claim
 * @param {string | number} [options.expirationTime] - Expiration time
 * @param {string | number} [options.notBefore] - Not before time
 * @param {string} [options.jti] - JWT ID
 * @param {number | false} [options.issuedAt] - Issued at time or false to skip
 * @returns {Promise<string>} Signed compact JWT
 */
export async function createSignedJwt(payload, key, protectedHeader, options = {}) {
  const jwt = new SignJWT(payload).setProtectedHeader(protectedHeader);

  if (options.issuer !== undefined) jwt.setIssuer(options.issuer);
  if (options.audience !== undefined) jwt.setAudience(options.audience);
  if (options.subject !== undefined) jwt.setSubject(options.subject);
  if (options.expirationTime !== undefined) jwt.setExpirationTime(options.expirationTime);
  if (options.notBefore !== undefined) jwt.setNotBefore(options.notBefore);
  if (options.jti !== undefined) jwt.setJti(options.jti);
  if (options.issuedAt !== false) jwt.setIssuedAt(options.issuedAt);

  return jwt.sign(key);
}

export { SignJWT };
export default createSignedJwt;
test/contract.mjs
import assert from 'node:assert/strict';
import {
  SignJWT,
  jwtVerify,
  generateSecret,
  generateKeyPair,
  errors
} from 'jose';
import { createSignedJwt } from '../src/index.mjs';

// 1. SignJWT signs a JWT with a symmetric secret key (HS256) and returns a compact 3-part serialized string verifiable by jwtVerify
{
  const secret = await generateSecret('HS256');
  const token = await createSignedJwt(
    { 'urn:example:claim': true },
    secret,
    { alg: 'HS256', typ: 'JWT' }
  );

  assert.equal(typeof token, 'string');
  const parts = token.split('.');
  assert.equal(parts.length, 3);

  const { payload, protectedHeader } = await jwtVerify(token, secret);
  assert.equal(payload['urn:example:claim'], true);
  assert.equal(protectedHeader.alg, 'HS256');
  assert.equal(protectedHeader.typ, 'JWT');
}

// 2. SignJWT signs a JWT with an asymmetric private key (ES256) verifiable by the corresponding public key
{
  const { privateKey, publicKey } = await generateKeyPair('ES256');
  const token = await new SignJWT({ data: 42 })
    .setProtectedHeader({ alg: 'ES256' })
    .sign(privateKey);

  assert.equal(typeof token, 'string');
  const { payload, protectedHeader } = await jwtVerify(token, publicKey);
  assert.equal(payload.data, 42);
  assert.equal(protectedHeader.alg, 'ES256');
}

// 3. SignJWT sets standard claims including issuer, subject, audience, expiration time, and JWT ID via builder methods
{
  const secret = await generateSecret('HS256');
  const token = await new SignJWT({ user: 'sample-user' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setIssuer('urn:example:issuer')
    .setSubject('sample-subject')
    .setAudience('urn:example:audience')
    .setExpirationTime('2h')
    .setJti('sample-jti-123')
    .sign(secret);

  const { payload } = await jwtVerify(token, secret, {
    issuer: 'urn:example:issuer',
    audience: 'urn:example:audience',
    subject: 'sample-subject'
  });

  assert.equal(payload.user, 'sample-user');
  assert.equal(payload.iss, 'urn:example:issuer');
  assert.equal(payload.sub, 'sample-subject');
  assert.equal(payload.aud, 'urn:example:audience');
  assert.equal(payload.jti, 'sample-jti-123');
  assert.equal(typeof payload.iat, 'number');
  assert.equal(typeof payload.exp, 'number');
}

// 4. SignJWT supports multiple audience claims specified as an array of strings
{
  const secret = await generateSecret('HS256');
  const token = await new SignJWT({ scope: 'read' })
    .setProtectedHeader({ alg: 'HS256' })
    .setAudience(['aud-primary', 'aud-secondary'])
    .sign(secret);

  const { payload } = await jwtVerify(token, secret, {
    audience: 'aud-primary'
  });
  assert.deepEqual(payload.aud, ['aud-primary', 'aud-secondary']);
}

// 5. SignJWT rejects signing when neither protectedHeader nor unprotectedHeader is set with JWSInvalid
{
  const secret = await generateSecret('HS256');
  await assert.rejects(
    async () => {
      await new SignJWT({ value: 100 }).sign(secret);
    },
    (err) => {
      assert(err instanceof errors.JWSInvalid);
      assert.equal(err.code, 'ERR_JWS_INVALID');
      return true;
    }
  );
}

// 6. SignJWT produced tokens with past expiration times are rejected during verification with JWTExpired
{
  const secret = await generateSecret('HS256');
  const expiredToken = await new SignJWT({ expired: true })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('-10s')
    .sign(secret);

  await assert.rejects(
    async () => {
      await jwtVerify(expiredToken, secret);
    },
    (err) => {
      assert(err instanceof errors.JWTExpired);
      assert.equal(err.code, 'ERR_JWT_EXPIRED');
      return true;
    }
  );
}

// 7. SignJWT produced tokens with future not-before times are rejected during verification with JWTClaimValidationFailed
{
  const secret = await generateSecret('HS256');
  const futureToken = await new SignJWT({ active: false })
    .setProtectedHeader({ alg: 'HS256' })
    .setNotBefore('+1h')
    .sign(secret);

  await assert.rejects(
    async () => {
      await jwtVerify(futureToken, secret);
    },
    (err) => {
      assert(err instanceof errors.JWTClaimValidationFailed);
      assert.equal(err.code, 'ERR_JWT_CLAIM_VALIDATION_FAILED');
      assert.equal(err.claim, 'nbf');
      return true;
    }
  );
}

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

Исходный сидер

аноним