=============== LIBRARY RULES =============== From library maintainers: - Outside Node.js call await init() once before use. - Pass a context when signing and expectedContext when verifying; pass aad when sealing and expectedAad when opening. - Free secret objects with using or free(), and wipe() any exported secret bytes. - The default hybrid signature suite is Ed25519+ML-DSA-65-v2; the default hybrid KEM is X25519+ML-KEM-768. ### Install quantum-safe-ts with npm Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/README.md Install the quantum-safe-ts package using npm. ```bash npm install quantum-safe-ts ``` -------------------------------- ### Start quantum-safe-mcp server Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/README.md Start the MCP server using npx. ```bash npx quantum-safe-mcp ``` -------------------------------- ### Working example: HybridSign and HybridKEM with context and AAD Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/context-and-aad.md Demonstrates signing and verification with context, and sealing and opening with AAD. Uses quantum-safe-ts. The example expects verification with wrong context to throw VerificationError, and checks the decrypted plaintext. ```typescript import { HybridKEM, HybridSign, Envelope, VerificationError, utf8 } from 'quantum-safe-ts'; const signer = new HybridSign(); using keys = signer.generateKeyPair(); const sm = signer.sign(utf8('transfer 5'), keys.secretKey, { context: utf8('payments-v1') }); signer.verify(sm, keys.publicKey, { expectedContext: utf8('payments-v1') }); // accepted try { signer.verify(sm, keys.publicKey, { expectedContext: utf8('auth-v1') }); // another purpose throw new Error('should have been refused'); } catch (e) { if (!(e instanceof VerificationError)) throw e; } const kem = new HybridKEM(); using recipient = kem.generateKeyPair(); const sealed = Envelope.seal(utf8('card on file'), recipient.publicKey, { aad: utf8('tenant-A') }); const plain = Envelope.open(sealed, recipient.secretKey, { expectedAad: utf8('tenant-A') }); if (new TextDecoder().decode(plain) !== 'card on file') throw new Error('unexpected'); ``` -------------------------------- ### Migration State Transition Example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms-full.txt Shows how to use MigrationStateManager and Upgrader to transition a key state and check for upgrade needs. Requires a store with atomic compareAndSet for cross-process safety. ```TypeScript import { MemoryMigrationStore, MigrationStateManager, Upgrader } from 'quantum-safe-ts'; const manager = new MigrationStateManager(new MemoryMigrationStore()); await manager.transition({ keyId: 'k1', fromState: 'classical_only', toState: 'hybrid_transition', algorithm: 'X25519+ML-KEM-768', actor: 'ci', }); if ((await manager.getCurrentState('k1')) !== 'hybrid_transition') throw new Error('state'); if (!Upgrader.checkNeedsUpgrade('classical_only')) throw new Error('needs upgrade'); ``` -------------------------------- ### HybridSign - Complete Example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/signatures.md Demonstrates key generation, signing, verification, and transport of a hybrid signature using Ed25519 + ML-DSA-65. ```APIDOC ## HybridSign - Complete Example ### Description Demonstrates the full lifecycle of a hybrid signature: key generation, signing, verification, and transport. ### Class `HybridSign` ### Methods #### `generateKeyPair()` - **Returns**: Key pair object with `secretKey` and `publicKey` properties. #### `sign(message, secretKey, options)` - **Parameters**: - `message` (Uint8Array) - Required - The message to sign. - `secretKey` - Required - The secret key from the key pair. - `options.context` (Uint8Array) - Optional - A context string to bind the signature. - **Returns**: `SignedMessage` object. #### `verify(signed, publicKey, options)` - **Parameters**: - `signed` (SignedMessage) - Required - The signed message to verify. - `publicKey` - Required - The public key from the key pair. - `options.expectedContext` (Uint8Array) - Optional - The expected context string. - **Throws**: `VerificationError` if verification fails. - **Returns**: Nothing. #### `isValid(signed, publicKey, options)` - **Parameters**: Same as `verify`. - **Returns**: Boolean indicating validity. #### `verifyBytes(message, signature, publicKey, options)` - **Parameters**: - `message` (Uint8Array) - Required - The original message. - `signature` (Uint8Array) - Required - The detached signature. - `publicKey` - Required - The public key. - `options.context` (Uint8Array) - Optional - The context string. - **Returns**: Boolean indicating validity. ### SignedMessage #### `toBytes()` - **Returns**: Uint8Array - Serialized signed message for transport. #### `fromBytes(bytes)` - **Parameters**: `bytes` (Uint8Array) - Required - Serialized signed message. - **Returns**: `SignedMessage` instance. #### `fromParts(parts)` - **Parameters**: `parts` (object) - Required - Object with `message` property (Uint8Array). - **Returns**: `SignedMessage` instance. ### Example Code ```ts import { HybridSign, SignedMessage, VerificationError, utf8 } from 'quantum-safe-ts'; const signer = new HybridSign(); // Ed25519 + ML-DSA-65, hedged using keys = signer.generateKeyPair(); const signed = signer.sign(utf8('release 1.2.3'), keys.secretKey, { context: utf8('myapp-release-v1') }); // Verify with the context YOU expect. Returns nothing; throws VerificationError unless valid. signer.verify(signed, keys.publicKey, { expectedContext: utf8('myapp-release-v1') }); // Transport: the signed message is self-contained. const wire = signed.toBytes(); const received = SignedMessage.fromBytes(wire); if (new TextDecoder().decode(received.message) !== 'release 1.2.3') throw new Error('message changed'); // Any change to the message, the signature, the context or the key is refused. const tampered = SignedMessage.fromParts({ ...received, message: utf8('release 9.9.9') }); try { signer.verify(tampered, keys.publicKey, { expectedContext: utf8('myapp-release-v1') }); throw new Error('should have failed'); } catch (e) { if (!(e instanceof VerificationError)) throw e; } ``` ``` -------------------------------- ### Complete example of Envelope.seal and Envelope.open Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/encryption.md This example shows the full workflow of encrypting a message with Envelope.seal and decrypting it with Envelope.open. It demonstrates using HybridKEM for key generation, handling AAD (Additional Authenticated Data), converting to and from bytes, and catching DecryptionAuthenticationError when the expected AAD does not match. ```typescript import { Envelope, HybridKEM, SealedMessage, DecryptionAuthenticationError, utf8 } from 'quantum-safe-ts'; using pair = new HybridKEM().generateKeyPair(); const sealed = Envelope.seal(utf8('secret'), pair.publicKey, { aad: utf8('item-42') }); // The recipient states the context it expects. const plain = Envelope.open(sealed, pair.secretKey, { expectedAad: utf8('item-42') }); if (new TextDecoder().decode(plain) !== 'secret') throw new Error('round trip failed'); // Store or send the bytes; read them back later. const wire = sealed.toBytes(); // CBOR, identical to quantum-safe-py's SealedMessage.to_bytes() const again = SealedMessage.fromBytes(wire); if (again.algorithm !== 'X25519+ML-KEM-768' || again.version !== 1) throw new Error('unexpected metadata'); // A different expected AAD is refused: nothing about *why*. try { Envelope.open(wire, pair.secretKey, { expectedAad: utf8('item-43') }); throw new Error('should not open'); } catch (e) { if (!(e instanceof DecryptionAuthenticationError)) throw e; } ``` -------------------------------- ### Set up MigrationStateManager with FileMigrationStore Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/migration.md Node.js example for creating a MigrationStateManager with a FileMigrationStore. This is for single-host, multi-process concurrency. The store uses a lock directory with heartbeat and atomic rename, but is not safe on network filesystems. ```TypeScript // Node.js only; a complete, running example with two racing workers is in the Cookbook (recipe 6). import { MigrationStateManager } from 'quantum-safe-ts'; import { FileMigrationStore } from 'quantum-safe-ts/file-store'; const manager = new MigrationStateManager(new FileMigrationStore('./migration-state')); ``` -------------------------------- ### Sample scan output with RSA and SHA-1 findings Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/audit.md Example output from scanning a small project with an RSA key and SHA-1 hash. Shows HIGH and MEDIUM findings with fix suggestions, and exits with code 1 because a HIGH finding meets the default --fail-on high. ```text [HIGH ] src/auth.ts:2:30 QSJ001 RSA key generation or use (rsa) fix: Encryption/key transport: HybridKEM + Envelope (X25519+ML-KEM-768; CNSA 2.0: pure ML-KEM-1024 via cnsa2.kem()). Signatures: HybridSign (Ed25519+ML-DSA-65; CNSA 2.0: pure ML-DSA-87). [MEDIUM ] src/auth.ts:3:23 QSJ030 SHA-1 (sha1) fix: SHA-384 or SHA-512. Scanned 1 file(s): 0 critical, 1 high, 1 medium, 0 low, 0 info. Static analysis sees only what the source names; an empty result is not evidence of absence. This is an inventory, not a compliance verdict. ``` -------------------------------- ### .qs-audit.json policy file example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/audit.md Example policy file that sets the failure threshold to 'high', ignores rule QSJ050, excludes test and legacy paths, and disables CNSA 2.0 reporting. This file is auto-loaded if present in the current directory unless --no-config is used. ```json { "failOn": "high", "ignoreRules": ["QSJ050"], "exclude": ["**/test/**", "legacy/**"], "cnsa2": false } ``` -------------------------------- ### Quick start with easy API for encryption and signing Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/README.md Demonstrates the easy API for generating encryption keys (X25519 + ML-KEM-768), encrypting/decrypting, and signing/verifying with Ed25519 + ML-DSA-65. Works on Node.js immediately; browsers and other runtimes require init() first. ```typescript import { easy } from 'quantum-safe-ts'; const { publicKey, secretKey } = easy.generateEncryptionKeys(); // PEM strings, X25519 + ML-KEM-768 const sealed = easy.encrypt(publicKey, 'attack at dawn'); // Uint8Array const plain = easy.decrypt(secretKey, sealed); // Uint8Array if (new TextDecoder().decode(plain) !== 'attack at dawn') throw new Error('round trip failed'); const signer = easy.generateSigningKeys(); // Ed25519 + ML-DSA-65 const signed = easy.sign(signer.secretKey, 'pay 10', { context: 'payments' }); const message = easy.verify(signer.publicKey, signed, { context: 'payments' }); // throws unless valid if (new TextDecoder().decode(message) !== 'pay 10') throw new Error('verify failed'); ``` -------------------------------- ### Initialize quantum-safe-ts with init() and generate encryption keys Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/runtimes.md Call init() once at startup and await it. On Node.js it is a no-op because the package initializes itself on import; calling it again or concurrently is fine. After initialization, isInitialized() returns true and easy.generateEncryptionKeys() produces a public key starting with '-----BEGIN'. ```TypeScript import { init, isInitialized, easy } from 'quantum-safe-ts'; await init(); // on Node.js this is a no-op because the package initialised itself on import await init(); // calling it again, or concurrently, is fine if (!isInitialized()) throw new Error('not initialised'); const { publicKey } = easy.generateEncryptionKeys(); if (!publicKey.startsWith('-----BEGIN')) throw new Error('unexpected key'); ``` -------------------------------- ### Minimal example: HybridKEM and Envelope Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms.txt Shows the core class API: initialize the library, generate a hybrid key pair (X25519+ML-KEM-768), seal and open an envelope with AAD. The 'using' declaration zeroizes secret buffers in WASM memory when the pair goes out of scope. init() is required in browsers/Deno/Bun/edge but is a no-op on Node.js. ```ts import { init, HybridKEM, Envelope, utf8 } from 'quantum-safe-ts'; await init(); // required in browsers/Deno/Bun/edge; no-op on Node.js const kem = new HybridKEM(); // X25519+ML-KEM-768 using pair = kem.generateKeyPair(); // using/free() zeroizes the owned secret buffers in WASM memory const sealed = Envelope.seal(utf8('secret'), pair.publicKey, { aad: utf8('ctx') }); const plain = Envelope.open(sealed, pair.secretKey); ``` -------------------------------- ### explain_rule Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/mcp.md Explains why a specific rule matters, the replacement, a code example using quantum-safe-ts, and references. ```APIDOC ## Tool: explain_rule ### Description Provides an explanation for a specific rule: why it matters, the replacement, a code example using quantum-safe-ts, and references. ### Inputs - **ruleId** (string) - Required - The rule identifier, e.g., `QSJ001`. ### Output - **explanation** - Why the rule matters. - **replacement** - The recommended replacement. - **codeExample** - A code example using quantum-safe-ts. - **references** - References. ### Notes - Read-only tool (`readOnlyHint: true`). ``` -------------------------------- ### Use quantum-safe-audit API from TypeScript Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/audit.md This example demonstrates the core API functions: scanPaths, buildCbom, shouldFail, and summary. It creates a temporary file with an RSA key generation call, scans it, and verifies the expected finding (QSJ001), the fail gate, and the CBOM output format. ```ts import { scanPaths, buildCbom, shouldFail, summary } from 'quantum-safe-audit'; import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; const dir = mkdtempSync(join(tmpdir(), 'qs-audit-doc-')); try { writeFileSync(join(dir, 'a.ts'), "import crypto from 'node:crypto';\ncrypto.generateKeyPairSync('rsa', { modulusLength: 2048 });\n"); const report = scanPaths([dir]); console.log(summary(report)); if (report.findings.length !== 1 || report.findings[0]!.ruleId !== 'QSJ001') throw new Error('expected one RSA finding'); if (!shouldFail(report)) throw new Error('a HIGH finding fails the default gate'); const cbom = buildCbom(report, { appName: 'demo' }) as { bomFormat: string; specVersion: string }; if (cbom.bomFormat !== 'CycloneDX' || cbom.specVersion !== '1.6') throw new Error('unexpected CBOM'); } finally { rmSync(dir, { recursive: true, force: true }); } ``` -------------------------------- ### Verify signature with expected context Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/concepts.md Shows how to sign and verify with a context, and that verification fails when the expected context does not match. The example uses HybridSign and VerificationError from 'quantum-safe-ts'. ```TypeScript import { HybridSign, VerificationError, utf8 } from 'quantum-safe-ts'; const signer = new HybridSign(); using keys = signer.generateKeyPair(); const signed = signer.sign(utf8('transfer 10 EUR'), keys.secretKey, { context: utf8('payments-v1') }); signer.verify(signed, keys.publicKey, { expectedContext: utf8('payments-v1') }); // ok let refused = 0; for (const expected of [utf8('login-v1'), new Uint8Array(0)]) { try { signer.verify(signed, keys.publicKey, { expectedContext: expected }); } catch (e) { if (e instanceof VerificationError) refused++; else throw e; } } if (refused !== 2) throw new Error('wrong or missing context must be refused'); ``` -------------------------------- ### quantum-safe-audit CLI commands Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/audit.md Shows the primary CLI commands for scanning, generating SARIF/CBOM reports, explaining rules, listing rules, and enriching SBOMs. The installed command is quantum-safe-audit (or pqc-audit from the alias package). ```bash npx quantum-safe-audit scan . # human-readable; exits 1 on HIGH or worse npx quantum-safe-audit scan . --format sarif --output audit.sarif # GitHub code scanning npx quantum-safe-audit cbom . --app-name my-app > cbom.json # CycloneDX 1.6 CBOM npx quantum-safe-audit explain QSJ010 # why a rule matters, and the fix npx quantum-safe-audit rules # every rule npx quantum-safe-audit sbom bom.json --output bom-pqc.json # enrich a CycloneDX SBOM ``` -------------------------------- ### Use MigrationStateManager with FileMigrationStore for key migration Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/cookbook.md Creates a MigrationStateManager backed by a file store, performs a transition from classical_only to hybrid_transition, then races two workers to advance to pqc_preferred, expecting exactly one to win. Verifies history and progress. The file store is single-host only; use a store with atomic compareAndSet for multi-host setups. ```TypeScript import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { MigrationStateManager } from 'quantum-safe-ts'; import { FileMigrationStore } from 'quantum-safe-ts/file-store'; const dir = mkdtempSync(join(tmpdir(), 'qs-migration-')); try { const manager = new MigrationStateManager(new FileMigrationStore(dir)); if (!manager.crossProcessSafe) throw new Error('the file store supports compare-and-set'); await manager.transition({ keyId: 'billing-signing', fromState: 'classical_only', toState: 'hybrid_transition', algorithm: 'Ed25519+ML-DSA-65', actor: 'rotation-job', reason: 'start of migration' }); // Two workers race to advance the same key; both believe it is in hybrid_transition. Exactly one wins. const outcomes = await Promise.allSettled([ manager.transition({ keyId: 'billing-signing', fromState: 'hybrid_transition', toState: 'pqc_preferred', algorithm: 'Ed25519+ML-DSA-65', actor: 'worker-1' }), manager.transition({ keyId: 'billing-signing', fromState: 'hybrid_transition', toState: 'pqc_preferred', algorithm: 'Ed25519+ML-DSA-65', actor: 'worker-2' }), ]); const won = outcomes.filter((o) => o.status === 'fulfilled').length; if (won !== 1) throw new Error(`exactly one writer must win, got ${won}`); const history = await manager.getHistory('billing-signing'); if (history.length !== 2 || (await manager.getCurrentState('billing-signing')) !== 'pqc_preferred') throw new Error('unexpected history'); const progress = await manager.migrationProgress(); if (progress.pqc_preferred !== 1) throw new Error('unexpected progress'); } finally { rmSync(dir, { recursive: true, force: true }); } ``` -------------------------------- ### Choose encryption and signing keys based on profile and verifier compatibility Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/choosing.md Shows how to select between pure ML-KEM-1024 (CNSA 2.0) and hybrid keys for encryption, and between default and legacy HybridSign formats for signing. The example demonstrates that the envelope version is determined by the key type, and that signing uses a context for verification. ```TypeScript import { HybridKEM, HybridSign, cnsa2, Envelope, utf8 } from 'quantum-safe-ts'; function encryptionKeys(cnsa2Profile: boolean) { // Pure ML-KEM-1024 (envelope v2) for the CNSA 2.0 profile; otherwise the hybrid default. return cnsa2Profile ? cnsa2.kem().generateKeyPair() : new HybridKEM().generateKeyPair(); } function signer(everyVerifierIsPy031OrTs: boolean) { // -v2 (the default) when every verifier can read it; the original format when an older Python verifier is involved. return everyVerifierIsPy031OrTs ? new HybridSign() : new HybridSign('Ed25519+ML-DSA-65'); } for (const profile of [false, true]) { using keys = encryptionKeys(profile); const sealed = Envelope.seal(utf8('data'), keys.publicKey); if (sealed.version !== (profile ? 2 : 1)) throw new Error('the version is chosen by the key, not by you'); } for (const modern of [false, true]) { const s = signer(modern); using kp = s.generateKeyPair(); const sm = s.sign(utf8('data'), kp.secretKey, { context: utf8('example-v1') }); s.verify(sm, kp.publicKey, { expectedContext: utf8('example-v1') }); } ``` -------------------------------- ### Complete HybridSign example with signing, verification, and tamper detection Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/signatures.md Shows a full workflow: generate a key pair, sign a message with a context, verify with the expected context, serialize and deserialize the signed message, and confirm that tampering is rejected. verify() throws VerificationError on failure; use isValid for a boolean or verifyBytes for detached signatures. ```TypeScript import { HybridSign, SignedMessage, VerificationError, utf8 } from 'quantum-safe-ts'; const signer = new HybridSign(); // Ed25519 + ML-DSA-65, hedged using keys = signer.generateKeyPair(); const signed = signer.sign(utf8('release 1.2.3'), keys.secretKey, { context: utf8('myapp-release-v1') }); // Verify with the context YOU expect. Returns nothing; throws VerificationError unless valid. signer.verify(signed, keys.publicKey, { expectedContext: utf8('myapp-release-v1') }); // Transport: the signed message is self-contained. const wire = signed.toBytes(); const received = SignedMessage.fromBytes(wire); if (new TextDecoder().decode(received.message) !== 'release 1.2.3') throw new Error('message changed'); // Any change to the message, the signature, the context or the key is refused. const tampered = SignedMessage.fromParts({ ...received, message: utf8('release 9.9.9') }); try { signer.verify(tampered, keys.publicKey, { expectedContext: utf8('myapp-release-v1') }); throw new Error('should have failed'); } catch (e) { if (!(e instanceof VerificationError)) throw e; } ``` -------------------------------- ### TypeScript: verify and open (Node.js, no-run) Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/python-interop.md TypeScript side of the round trip. Reads the files written by the Python example, verifies the signature with the expected context, and opens the envelope with the expected AAD. Marked no-run because it requires the Python-generated files. ```typescript import { readFileSync } from 'node:fs'; import { Envelope, HybridSign, PublicKey, SecretKey, SignedMessage, utf8 } from 'quantum-safe-ts'; const pub = PublicKey.fromPem(readFileSync('py-signing-public.pem', 'utf8')); const signed = SignedMessage.fromBytes(readFileSync('py-signed.bin')); new HybridSign('Ed25519+ML-DSA-65-v2').verify(signed, pub, { expectedContext: utf8('interop-v1') }); console.log(new TextDecoder().decode(signed.message)); // hello from Python using sk = SecretKey.fromPem(readFileSync('ts-encryption-secret.pem', 'utf8')); const plain = Envelope.open(readFileSync('py-sealed.bin'), sk, { expectedAad: utf8('interop-v1') }); console.log(new TextDecoder().decode(plain)); // secret for TypeScript ``` -------------------------------- ### Serialize and restore keys with quantum-safe-ts Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/keys.md Shows how to generate a key pair, serialize public and secret keys to PEM, JWK, and CBOR, restore them, and verify fingerprints. Secret keys are exported as PEM or CBOR, never JWK. The example uses `using` for explicit resource management and calls `.free()` on restored keys. ```TypeScript import { PublicKey, SecretKey, KeyPair, HybridKEM } from 'quantum-safe-ts'; using pair = new HybridKEM().generateKeyPair(); // Public keys: PEM, CBOR, JWK. All safe to publish. const pem = pair.publicKey.toPem(); // QUANTUM SAFE PUBLIC KEY, identical to quantum-safe-py's to_pem() const jwk = pair.publicKey.toJwk(); // kty "AKP"; public keys only const cbor = pair.publicKey.toCbor(); for (const back of [PublicKey.fromPem(pem), PublicKey.fromJwk(jwk), PublicKey.fromCbor(cbor)]) { if (back.fingerprint() !== pair.publicKey.fingerprint()) throw new Error('fingerprint changed'); back.free(); } // Secret keys: PEM or CBOR. These contain the secret: protect them. const secretPem = pair.secretKey.toPem(); // QUANTUM SAFE SECRET KEY using restored = SecretKey.fromPem(secretPem); if (restored.algorithm !== 'X25519+ML-KEM-768') throw new Error('unexpected algorithm'); // A pair travels as one CBOR bundle. const bundle = pair.toCborBundle(); using again = KeyPair.fromCborBundle(bundle); if (again.publicKey.fingerprint() !== pair.publicKey.fingerprint()) throw new Error('bundle changed the key'); ``` -------------------------------- ### Upgrade a classical key to hybrid with Upgrader.upgradeKemKey Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/migration.md Upgrades an existing X25519 key to a hybrid X25519+ML-KEM-768 key. The classical key bytes are extracted from a throwaway HybridKEM key pair, then passed to Upgrader.upgradeKemKey. The resulting key is verified to be a working hybrid key by encapsulating and decapsulating a shared secret. The example also checks the new algorithm and migration state, and clears the secret key bytes afterward. ```TypeScript import { HybridKEM, Upgrader, utf8 } from 'quantum-safe-ts'; // Pretend these are your existing X25519 key bytes (32 + 32 bytes). Here we lift them out of a throwaway key. using old = new HybridKEM().generateKeyPair(); const pubRaw = old.publicKey.toBytes(); const secRaw = old.secretKey.exportBytes(); const len = (raw: Uint8Array) => (raw[0]! << 8) | raw[1]!; const classicalPublic = pubRaw.slice(2, 2 + len(pubRaw)); const classicalSecret = secRaw.slice(2, 2 + len(secRaw)); const result = Upgrader.upgradeKemKey({ classicalSecret, classicalPublic, classicalAlgorithm: 'X25519', targetPqc: 'ML-KEM-768' }); using upgraded = result.keyPair; if (result.newAlgorithm !== 'X25519+ML-KEM-768' || result.migrationState !== 'hybrid_transition') throw new Error('unexpected'); // The upgraded key is a working hybrid key. const kem = new HybridKEM('X25519+ML-KEM-768'); const { ciphertext, sharedSecret } = kem.encapsulate(upgraded.publicKey); using back = kem.decapsulate(upgraded.secretKey, ciphertext); sharedSecret.free(); if (back.exportBytes().length !== 32) throw new Error('unexpected'); secRaw.fill(0); ``` -------------------------------- ### Complete streaming encryption example with sealStream and openStream Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/streaming.md Shows a full round trip: generate a key pair, seal an async iterable of Uint8Array pieces, concatenate the encrypted pieces, open the stream with expected AAD, and verify the plaintext. Also demonstrates that a truncated encrypted stream must be rejected with QuantumSafeError. The input can be split arbitrarily and can be empty; the encrypted output is also split arbitrarily. ```typescript import { HybridKEM, openStream, sealStream, QuantumSafeError, utf8 } from 'quantum-safe-ts'; using pair = new HybridKEM().generateKeyPair(); async function* source() { // any AsyncIterable or Iterable yield utf8('first part, '); yield utf8('second part'); } const pieces: Uint8Array[] = []; for await (const piece of sealStream(pair.publicKey, source(), { aad: utf8('backup-2026-10') })) pieces.push(piece); const encrypted = new Uint8Array(pieces.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of pieces) { encrypted.set(p, at); at += p.length; } let plain = ''; for await (const part of openStream(pair.secretKey, [encrypted], { expectedAad: utf8('backup-2026-10') })) plain += new TextDecoder().decode(part); if (plain !== 'first part, second part') throw new Error('round trip'); let rejected = false; try { for await (const _ of openStream(pair.secretKey, [encrypted.slice(0, encrypted.length - 3)], { expectedAad: utf8('backup-2026-10') })) { /* consume */ } } catch (e) { rejected = QuantumSafeError.is(e); } if (!rejected) throw new Error('a truncated stream must not open'); ``` -------------------------------- ### CBOM cryptographic-asset JSON example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/tools/audit.md Example of a cryptographic-asset entry in the CycloneDX 1.6 CBOM output. Shows the structure with cryptoProperties, evidence, and quantum-safe properties. The example is for RSA with classical security level 112 and NIST quantum security level 0. ```json { "type": "cryptographic-asset", "bom-ref": "detected-RSA-0", "name": "RSA", "cryptoProperties": { "assetType": "algorithm", "algorithmProperties": { "primitive": "pke", "classicalSecurityLevel": 112, "nistQuantumSecurityLevel": 0 }, "oid": "1.2.840.113549.1.1.1" }, "evidence": { "occurrences": [{ "location": "src/auth.ts", "line": 2, "offset": 29 }] }, "properties": [{ "name": "quantum-safe:rule-id", "value": "QSJ001" }, { "name": "quantum-safe:severity", "value": "HIGH" }, { "name": "quantum-safe:quantum-vulnerable", "value": "true" }] } ``` -------------------------------- ### Create LMS signer, sign, and verify Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/lms-signing.md Shows the full workflow: create a signer with a passphrase-protected key, sign firmware, verify with Lms.verify, and check the remaining signature count. The key directory is created with mkdtempSync and the seed is encrypted at rest. ```TypeScript import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Lms } from 'quantum-safe-ts'; import { LmsSigner } from 'quantum-safe-ts/lms-signer'; // Once, at key-ceremony time. The directory holds the key; keep it on a local disk and back it up only as described below. // The seed is encrypted at rest: say how (a passphrase here; a 32-byte key from your KMS is the other choice). const directory = join(mkdtempSync(join(tmpdir(), 'lms-')), 'release-key'); const signer = LmsSigner.create({ directory, height: 5, winternitz: 8, protection: { passphrase: 'a long passphrase from your secrets manager', scryptLog2N: 14 }, }); const publicKey = signer.publicKey; // 60 bytes: publish it (it is not secret) // Every release. const firmware = new TextEncoder().encode('firmware image bytes'); const signature = signer.sign(firmware); // Anywhere, in any runtime that runs quantum-safe-ts. Lms.verify(publicKey, firmware, signature); if (signer.remaining !== 31) throw new Error('one signature should have been consumed'); ``` -------------------------------- ### CNSA 2.0 Profile Usage Example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms-full.txt Shows how to use the cnsa2 module to generate a compliance report, select a pure ML-KEM-1024 KEM, and enforce CNSA 2.0 policy. The example throws errors if the defaults are not compliant and demonstrates that pure ML-KEM-1024 with envelope v2 meets KEM requirements. ```TypeScript import { cnsa2 } from 'quantum-safe-ts'; const report = cnsa2.report({ kem: 'X25519+ML-KEM-768', signature: 'Ed25519+ML-DSA-65' }); if (report.compliant) throw new Error('the defaults are below CNSA 2.0'); const kem = cnsa2.kem(); // pure ML-KEM-1024: Envelope.seal() then produces envelope v2 (HKDF-SHA-384) cnsa2.enforce({ kem: kem.algorithm, signature: 'ML-DSA-87' }, { strict: true }); // throws PolicyViolationError below the parameter sets (strict also rejects 'partial' hybrids) if (!cnsa2.report({ kem: kem.algorithm, includeCodeSigning: false }).compliant) throw new Error('pure ML-KEM-1024 + envelope v2 meets the KEM requirements'); ``` -------------------------------- ### Instantiate HybridKEM and list supported suites with kemSuites() Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/kem.md Creates a HybridKEM instance (defaults to X25519+ML-KEM-768), verifies the default algorithm, and prints a table of all supported suites with their properties (hybrid, NIST category, CNSA 2.0 compliance, and quantum-safe-py compatibility). Also checks that expected suite names are present. ```TypeScript import { HybridKEM, kemSuites } from 'quantum-safe-ts'; const kem = new HybridKEM(); // X25519+ML-KEM-768 if (kem.algorithm !== 'X25519+ML-KEM-768') throw new Error('unexpected default'); console.table(kemSuites().map((s) => ({ name: s.name, hybrid: s.hybrid, nistCategory: s.nistLevel, cnsa2: s.meetsCnsa2, pyCompatible: s.pyCompatible }))); const names = kemSuites().map((s) => s.name); for (const expected of ['X25519+ML-KEM-768', 'P-256+ML-KEM-768', 'X-Wing', 'ML-KEM-1024']) { if (!names.includes(expected)) throw new Error(`missing suite ${expected}`); } ``` -------------------------------- ### JWTSigner and JWTVerifier with clean signature format Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/jwt.md Example of using JWTSigner and JWTVerifier with a hybrid key using the clean signature format (e.g., Ed25519+ML-DSA-65-v2). ```APIDOC ## JWTSigner and JWTVerifier with clean signature format ### Description Example of using JWTSigner and JWTVerifier with a hybrid key using the clean signature format (e.g., Ed25519+ML-DSA-65-v2). ### Example ```ts import { HybridSign, JWTSigner, JWTVerifier } from 'quantum-safe-ts'; using keys = new HybridSign('Ed25519+ML-DSA-65-v2').generateKeyPair(); const token = new JWTSigner(keys).sign({ sub: 'svc-a' }, { expiresIn: 60 }); const claims = new JWTVerifier(keys.publicKey).verify(token, { requireExp: true }); if (claims.sub !== 'svc-a') throw new Error('unexpected'); const header = JSON.parse(new TextDecoder().decode(Uint8Array.from(Buffer.from(token.split('.')[0]!, 'base64url')))); if (header.alg !== 'Ed25519+ML-DSA-65-v2') throw new Error('the header names the key algorithm'); ``` ``` -------------------------------- ### Initialize with fetched WASM for slim entry Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms-full.txt For the slim entry (quantum-safe-ts/slim) which has no embedded WebAssembly, fetch the WASM file and pass it to init(). ```typescript await init({ wasm: fetch(url) }) ``` -------------------------------- ### Python Verify and Open Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/python-interop.md Demonstrates how to verify a signed message and open a sealed message using quantum-safe-py, with context and AAD matching. ```APIDOC ## Python Verify and Open ### Description Verifies a signed message and opens a sealed message using quantum-safe-py, with context and AAD matching. ### Method N/A (SDK usage) ### Endpoint N/A (SDK usage) ### Parameters #### Method Parameters - **HybridSign.verify(sm, pub, context=...)** - Required - Verifies a signed message. - **sm** (SignedMessage) - Required - The signed message. - **pub** (PublicKey) - Required - The public key. - **context** (bytes) - Required - The expected context. - **Envelope.open(sealed, sk, expected_aad=...)** - Required - Opens a sealed message. - **sealed** (SealedMessage) - Required - The sealed message. - **sk** (SecretKey) - Required - The secret key. - **expected_aad** (bytes) - Required - The expected AAD. ### Request Example ```python from quantum_safe import HybridSign from quantum_safe.types import PublicKey, SecretKey from quantum_safe.types.signatures import SignedMessage from quantum_safe.protocols.envelope import Envelope, SealedMessage pub = PublicKey.from_pem(open("ts-signing-public.pem").read()) sm = SignedMessage.from_cbor(open("ts-signed.bin", "rb").read()) HybridSign("Ed25519", "ML-DSA-65-v2").verify(sm, pub, context=b"interop-v1") # raises unless valid print(sm.message) # b'hello from TypeScript' sk = SecretKey.from_pem(open("py-encryption-secret.pem").read()) print(Envelope.open(SealedMessage.from_bytes(open("ts-sealed.bin", "rb").read()), sk, expected_aad=b"interop-v1")) ``` ### Response #### Success Response - **sm.message** (bytes) - The original message. - **Envelope.open** (bytes) - The decrypted message. #### Response Example ``` b'hello from TypeScript' b'secret for Python' ``` ``` -------------------------------- ### Verify detached message with verifyBytes Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/signatures.md Use signer.verifyBytes to check a detached message and signature blob. The example signs a message with a context and verifies it, then attempts verification with a tampered message, expecting a VerificationError. ```TypeScript import { Sign, VerificationError, utf8 } from 'quantum-safe-ts'; const signer = new Sign('ML-DSA-65-v2'); using keys = signer.generateKeyPair(); const signed = signer.sign(utf8('detached'), keys.secretKey, { context: utf8('ctx-v1') }); signer.verifyBytes(utf8('detached'), signed.signature, keys.publicKey, { context: utf8('ctx-v1') }); try { signer.verifyBytes(utf8('detached!'), signed.signature, keys.publicKey, { context: utf8('ctx-v1') }); throw new Error('should have failed'); } catch (e) { if (!(e instanceof VerificationError)) throw e; } ``` -------------------------------- ### Initialize slim entry with WebAssembly URL Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/runtimes.md Use the slim entry to avoid embedding WebAssembly in the bundle. You must serve the .wasm file yourself and pass it to init. Any call before init throws NotInitializedError. ```TypeScript // Vite shown; webpack: new URL('quantum-safe-ts/wasm', import.meta.url). The slim entry is covered by the package tests (slim.test.ts). import { init } from 'quantum-safe-ts/slim'; import wasmUrl from 'quantum-safe-ts/wasm?url'; await init({ wasm: fetch(wasmUrl) }); ``` -------------------------------- ### Use .free() in a finally block for explicit resource management Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/faq.md If using is not supported, call .free() in a finally block to release resources. Example: const pair = kem.generateKeyPair(); try { ... } finally { pair.free(); } ```typescript const pair = kem.generateKeyPair(); try { ... } finally { pair.free(); } ``` -------------------------------- ### init() Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/getting-started.md Initializes the WebAssembly module. Required outside Node.js; a harmless no-op on Node.js. ```APIDOC ## init() ### Description Initializes the WebAssembly module. Required outside Node.js; a harmless no-op on Node.js. ### Method init ### Parameters None ### Returns Promise ### Example ```ts await init(); ``` ``` -------------------------------- ### Envelope seal and open example Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms-full.txt Demonstrates sealing a message with AAD, opening it, serializing to CBOR, and verifying authentication failure on tampered AAD. Requires a hybrid key pair; throws DecryptionAuthenticationError on wrong key or tampering. ```TypeScript import { Envelope, HybridKEM, SealedMessage, DecryptionAuthenticationError, utf8 } from 'quantum-safe-ts'; using pair = new HybridKEM().generateKeyPair(); const sealed = Envelope.seal(utf8('secret'), pair.publicKey, { aad: utf8('item-42') }); // AES-256-GCM under an HKDF key const plain = Envelope.open(sealed, pair.secretKey); // Uint8Array; call wipe(plain) if sensitive const wire = sealed.toBytes(); // CBOR, identical to quantum-safe-py SealedMessage.to_bytes() const again = SealedMessage.fromBytes(wire); if (again.algorithm !== 'X25519+ML-KEM-768' || plain.length !== 6) throw new Error('unexpected'); try { Envelope.open(SealedMessage.fromParts({ ...again, aad: utf8('other') }), pair.secretKey); throw new Error('should not open'); } catch (e) { if (!(e instanceof DecryptionAuthenticationError)) throw e; } ``` -------------------------------- ### Python: Verify and Open with quantum-safe-py Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/python-interop.md Python code that reads the files written by the TypeScript example, verifies the signature with context b'interop-v1', and opens the sealed message with expected_aad b'interop-v1'. It prints the signed message and the opened secret. ```Python from quantum_safe import HybridSign from quantum_safe.types import PublicKey, SecretKey from quantum_safe.types.signatures import SignedMessage from quantum_safe.protocols.envelope import Envelope, SealedMessage pub = PublicKey.from_pem(open("ts-signing-public.pem").read()) sm = SignedMessage.from_cbor(open("ts-signed.bin", "rb").read()) HybridSign("Ed25519", "ML-DSA-65-v2").verify(sm, pub, context=b"interop-v1") # raises unless valid print(sm.message) # b'hello from TypeScript' sk = SecretKey.from_pem(open("py-encryption-secret.pem").read()) print(Envelope.open(SealedMessage.from_bytes(open("ts-sealed.bin", "rb").read()), sk, expected_aad=b"interop-v1")) ``` -------------------------------- ### Envelope version and unsupported pure ML-KEM algorithms Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/website/guide/encryption.md Demonstrates that sealing with a pure ML-KEM-1024 key produces envelope version 2, while pure ML-KEM-768 throws UnsupportedAlgorithmError. The example uses try/catch to verify the error type. ```TypeScript import { Envelope, KEM, UnsupportedAlgorithmError, utf8 } from 'quantum-safe-ts'; using pure1024 = new KEM('ML-KEM-1024').generateKeyPair(); if (Envelope.seal(utf8('x'), pure1024.publicKey).version !== 2) throw new Error('pure ML-KEM-1024 gives envelope v2'); using pure768 = new KEM('ML-KEM-768').generateKeyPair(); try { Envelope.seal(utf8('x'), pure768.publicKey); throw new Error('pure ML-KEM-768 envelopes are not produced'); } catch (e) { if (!(e instanceof UnsupportedAlgorithmError)) throw e; } ``` -------------------------------- ### init({ wasm }) Source: https://github.com/animeshshaw/quantum-safe-ts/blob/master/packages/quantum-safe-ts/llms.txt Initializes the quantum-safe-ts library. Must be called before any other operations, except in Node.js where it is automatic. In Cloudflare Workers, pass the precompiled WASM module. ```APIDOC ## init({ wasm }) ### Description Initializes the quantum-safe-ts library. Must be called before any other operations, except in Node.js where it is automatic. In Cloudflare Workers, pass the precompiled WASM module. ### Method init ### Parameters - **wasm** (WebAssembly.Module) - Optional - The precompiled WASM module to use in Cloudflare Workers. ### Example ```javascript await init({ wasm }); ``` ```