@maatara/core-pqc 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -456,6 +456,65 @@ async function sha256B64u(data) {
456
456
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
457
457
  return b64uEncode(new Uint8Array(hashBuffer));
458
458
  }
459
+ // ============================================================================
460
+ // ALGORITHMIC OPTIMIZATIONS (arXiv:2501.02305, arXiv:2504.17033)
461
+ // ============================================================================
462
+ // High-performance data structures for verification operations
463
+ // WASM bindings for algorithm functions
464
+ const wasm_create_nonce_cache = wasmPkg__namespace.create_nonce_cache;
465
+ const wasm_nonce_cache_info = wasmPkg__namespace.nonce_cache_info;
466
+ const wasm_sssp_config = wasmPkg__namespace.sssp_config;
467
+ const wasm_provenance_path_config = wasmPkg__namespace.provenance_path_config;
468
+ const wasm_elastic_hash_config = wasmPkg__namespace.elastic_hash_config;
469
+ /**
470
+ * Create a nonce cache configuration for replay attack prevention.
471
+ * Based on Elastic Hashing - O(1) amortized, O(log(1/δ)) worst-case.
472
+ *
473
+ * @param capacity - Maximum number of nonces to track
474
+ * @param ttlMs - Time-to-live in milliseconds before nonces expire
475
+ */
476
+ async function createNonceCacheConfig(capacity, ttlMs) {
477
+ await initWasm();
478
+ return JSON.parse(wasm_create_nonce_cache(capacity, ttlMs));
479
+ }
480
+ /**
481
+ * Get information about the nonce cache algorithm.
482
+ */
483
+ async function getNonceCacheInfo() {
484
+ await initWasm();
485
+ return JSON.parse(wasm_nonce_cache_info());
486
+ }
487
+ /**
488
+ * Get optimal SSSP configuration for graph verification.
489
+ * Uses Frontier-Reduced SSSP - O(m × log^(2/3)(n)) complexity.
490
+ *
491
+ * @param nodes - Expected number of nodes in the graph
492
+ */
493
+ async function getSSSPConfig(nodes) {
494
+ await initWasm();
495
+ return JSON.parse(wasm_sssp_config(nodes));
496
+ }
497
+ /**
498
+ * Get optimized configuration for provenance chain verification.
499
+ *
500
+ * @param chainLength - Number of blocks in the provenance chain
501
+ * @param branches - Average number of branches per block
502
+ */
503
+ async function getProvenancePathConfig(chainLength, branches) {
504
+ await initWasm();
505
+ return JSON.parse(wasm_provenance_path_config(chainLength, branches));
506
+ }
507
+ /**
508
+ * Get elastic hash table configuration for key caching.
509
+ * Optimal for PQC public key caching with O(1) amortized lookups.
510
+ *
511
+ * @param capacity - Maximum number of entries
512
+ * @param loadFactor - Target load factor (0.0 to 1.0, recommend 0.95)
513
+ */
514
+ async function getElasticHashConfig(capacity, loadFactor = 0.95) {
515
+ await initWasm();
516
+ return JSON.parse(wasm_elastic_hash_config(capacity, loadFactor));
517
+ }
459
518
 
460
519
  exports.aesGcmUnwrap = aesGcmUnwrap;
461
520
  exports.aesGcmWrap = aesGcmWrap;
@@ -468,10 +527,15 @@ exports.buildPolicyPreimage = buildPolicyPreimage;
468
527
  exports.buildTransferPreimage = buildTransferPreimage;
469
528
  exports.constantTimeEqual = constantTimeEqual;
470
529
  exports.createAttestation = createAttestation;
530
+ exports.createNonceCacheConfig = createNonceCacheConfig;
471
531
  exports.createProvenanceCommitment = createProvenanceCommitment;
472
532
  exports.dilithiumKeygen = dilithiumKeygen;
473
533
  exports.dilithiumSign = dilithiumSign;
474
534
  exports.dilithiumVerify = dilithiumVerify;
535
+ exports.getElasticHashConfig = getElasticHashConfig;
536
+ exports.getNonceCacheInfo = getNonceCacheInfo;
537
+ exports.getProvenancePathConfig = getProvenancePathConfig;
538
+ exports.getSSSPConfig = getSSSPConfig;
475
539
  exports.hkdfSha256 = hkdfSha256;
476
540
  exports.initWasm = initWasm;
477
541
  exports.jcsCanonicalize = jcsCanonicalize;
@@ -484,4 +548,4 @@ exports.verifyAttestations = verifyAttestations;
484
548
  exports.verifyCommitmentReveal = verifyCommitmentReveal;
485
549
  exports.verifyProvenanceCommitment = verifyProvenanceCommitment;
486
550
  exports.verifyThreshold = verifyThreshold;
487
- //# sourceMappingURL=index.js.map
551
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../../src/index.ts"],"sourcesContent":["// Ma'atara Core PQC Toolkit\n// Post-Quantum Cryptography for Browser and Node.js\n// \n// SECURITY NOTICE: This library implements FIPS 204 (ML-DSA) and FIPS 203 (ML-KEM)\n// post-quantum cryptographic algorithms. Key material should be:\n// 1. Stored securely (encrypted at rest)\n// 2. Transmitted only over secure channels\n// 3. Zeroized after use when possible\n// 4. Protected by hardware security modules for high-value operations\n//\n// See docs/WASM_SECURITY_MODEL.md for browser-specific security considerations.\n\n// ============================================================================\n// SECURITY CONSTANTS\n// ============================================================================\nconst MAX_MESSAGE_SIZE = 16 * 1024 * 1024; // 16MB - prevent memory exhaustion\nconst MAX_KEY_SIZE = 1024 * 1024; // 1MB - reasonable for PQC keys\nconst MAX_ATTESTATION_COUNT = 100; // Prevent DoS from large attestation arrays\n\nexport interface KyberKeypair {\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface KyberEncap {\n kem_ct_b64u: string;\n shared_b64u: string;\n}\n\nexport interface AesGcmWrap {\n iv_b64u: string;\n ct_b64u: string;\n}\n\nexport interface DilithiumKeypair {\n algorithm: string;\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface DilithiumSignResult {\n signature_b64u: string;\n algorithm: string;\n}\n\nexport interface DilithiumVerifyResult {\n is_valid: boolean;\n algorithm: string;\n}\n\nexport interface HkdfResult {\n key_b64u: string;\n}\n\nexport interface AesGcmUnwrapResult {\n dek_b64u: string;\n}\n\n// Import WASM functions (namespace import for better bundler compatibility)\nimport * as wasmPkg from '@maatara/core-pqc-wasm';\nconst wasm_kyber_keygen = (wasmPkg as any).kyber_keygen as () => string;\nconst wasm_kyber_encaps = (wasmPkg as any).kyber_encaps as (p: string) => string;\nconst wasm_kyber_decaps = (wasmPkg as any).kyber_decaps as (s: string, c: string) => string;\nconst wasm_hkdf_sha256 = (wasmPkg as any).hkdf_sha256 as (s: string, i: string, salt?: string, len?: number) => string;\nconst wasm_aes_gcm_wrap = (wasmPkg as any).aes_gcm_wrap as (k: string, d: string, a: string) => string;\nconst wasm_aes_gcm_unwrap = (wasmPkg as any).aes_gcm_unwrap as (k: string, iv: string, ct: string, a: string) => string;\nconst wasm_dilithium_keygen = (wasmPkg as any).dilithium_keygen as () => string;\nconst wasm_dilithium_sign = (wasmPkg as any).dilithium_sign as (m: string, s: string) => string;\nconst wasm_dilithium_verify = (wasmPkg as any).dilithium_verify as (m: string, sig: string, p: string) => string;\n\n// Deterministic/canonicalization and governance helpers\nexport interface CanonicalOut { canonical: string; msg_b64u?: string; msgB64u?: string }\n\n// Initialize WASM\nlet wasmReady = false;\n\n/**\n * Initialize the underlying WASM module.\n * - In browsers/bundlers where the glue knows how to fetch the .wasm, you can call without params.\n * - If your bundler provides a URL or Module for the .wasm, pass it as the first argument.\n */\nexport async function initWasm(wasmInput?: any): Promise<void> {\n if (wasmReady) return;\n const maybeInit = (wasmPkg as any).default;\n if (typeof maybeInit === 'function') {\n // Some environments require a URL/Module/bytes for initialization.\n // We forward the optional value if provided; otherwise let the glue resolve it.\n if (wasmInput !== undefined) {\n await maybeInit(wasmInput);\n } else {\n await maybeInit();\n }\n }\n wasmReady = true;\n}\n\n// Kyber functions\nexport async function kyberKeygen(): Promise<KyberKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberEncaps(publicB64u: string): Promise<KyberEncap> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_encaps(publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberDecaps(secretB64u: string, kemCtB64u: string): Promise<{ shared_b64u: string }> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_decaps(secretB64u, kemCtB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// HKDF functions\nexport async function hkdfSha256(\n secretB64u: string,\n infoB64u: string,\n saltB64u?: string,\n len: number = 32\n): Promise<HkdfResult> {\n await initWasm();\n const result = JSON.parse(wasm_hkdf_sha256(secretB64u, infoB64u, saltB64u, len));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// AES-GCM functions\nexport async function aesGcmWrap(\n keyB64u: string,\n dekB64u: string,\n aadB64u: string\n): Promise<AesGcmWrap> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_wrap(keyB64u, dekB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function aesGcmUnwrap(\n keyB64u: string,\n ivB64u: string,\n ctB64u: string,\n aadB64u: string\n): Promise<AesGcmUnwrapResult> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_unwrap(keyB64u, ivB64u, ctB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// Dilithium functions\n\n/**\n * Generate a new ML-DSA-65 (Dilithium) keypair.\n * SECURITY: Keys should be stored encrypted at rest.\n * For high-value operations, consider hardware security modules.\n */\nexport async function dilithiumKeygen(): Promise<DilithiumKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_dilithium_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Sign a message using ML-DSA-65 (Dilithium).\n * @param messageB64u - Base64url-encoded message to sign\n * @param secretB64u - Base64url-encoded secret key\n * SECURITY: Secret key should be zeroized after use if possible.\n */\nexport async function dilithiumSign(\n messageB64u: string,\n secretB64u: string\n): Promise<DilithiumSignResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (secretB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Secret key exceeds maximum size of ${MAX_KEY_SIZE} bytes`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_sign(messageB64u, secretB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Verify a ML-DSA-65 (Dilithium) signature.\n * @param messageB64u - Base64url-encoded message\n * @param signatureB64u - Base64url-encoded signature\n * @param publicB64u - Base64url-encoded public key\n */\nexport async function dilithiumVerify(\n messageB64u: string,\n signatureB64u: string,\n publicB64u: string\n): Promise<DilithiumVerifyResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (signatureB64u.length > MAX_KEY_SIZE || publicB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Signature or public key exceeds maximum size`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_verify(messageB64u, signatureB64u, publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// ---- Deterministic helpers (multisig/art token) ----\nexport async function jcsCanonicalize(json: unknown): Promise<string> {\n await initWasm();\n const raw = (wasmPkg as any).jcs_canonicalize(JSON.stringify(json));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return out.canonical as string;\n}\n\nexport async function buildPolicyPreimage(policy: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_governance(JSON.stringify(policy));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildMintPreimage(header: unknown, asset: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_mint(JSON.stringify(header), JSON.stringify(asset));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildTransferPreimage(header: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_transfer(JSON.stringify(header));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildAnchorPreimage(userId: string, rootHex: string, epoch: string, chains: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_anchor(userId, rootHex, epoch, JSON.stringify(chains));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\n// ---- Veritas Block Preimage (NEW v2 JCS canonical form) ----\n// We migrate block signing to a canonical (JCS) JSON similar to other preimages.\n// Legacy (v1) blocks used a hand-crafted JSON.stringify of a plain object with fixed insertion order.\n// This helper produces a canonical JSON string and msg_b64u = b64url(UTF-8(canonical JSON)).\n// NOTE: We intentionally EXCLUDE signature, encryptionKeyHash, and any runtime-only fields.\n// Fields included (ordered via JCS lexical ordering):\n// contentType, dataHash, index, metadataHash, ownerPublicKey, previousHash, signatureAlg, timestamp, version\n// index & timestamp MUST be strings representing decimal integers (BigInt safe) – caller responsibility.\nexport interface BlockPreimageInput {\n index: string | number | bigint;\n timestamp: string | number | bigint;\n previousHash: string;\n dataHash: string;\n metadataHash: string;\n signatureAlg: string; // e.g. 'dilithium2'\n ownerPublicKey: string; // Dilithium public key (base64url)\n contentType?: string; // default 'application/json'\n version: number; // block format / protocol version\n}\n\nexport async function buildBlockPreimage(block: BlockPreimageInput): Promise<CanonicalOut> {\n await initWasm();\n // Normalize fields per spec\n const normalized = {\n contentType: block.contentType || 'application/json',\n dataHash: block.dataHash,\n index: block.index.toString(),\n metadataHash: block.metadataHash,\n ownerPublicKey: block.ownerPublicKey,\n previousHash: block.previousHash,\n signatureAlg: block.signatureAlg,\n timestamp: block.timestamp.toString(),\n version: block.version,\n };\n // Use JCS canonicalization via wasm jcs_canonicalize (already exposed through jcsCanonicalize helper)\n const canonical = await jcsCanonicalize(normalized);\n const msg_b64u = b64uEncode(new TextEncoder().encode(canonical));\n return { canonical, msg_b64u, msgB64u: msg_b64u };\n}\n\nexport async function validateRoyalty(receiver: string, bps: number): Promise<boolean> {\n await initWasm();\n const raw = (wasmPkg as any).validate_royalty(receiver, bps);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) return false;\n return !!out.ok;\n}\n\nexport async function verifyAttestations(msgB64u: string, attestations: Array<{ alg: string; publicKeyB64u: string; signatureB64u: string }>, allowedPublicKeys?: string[]): Promise<number> {\n await initWasm();\n const raw = (wasmPkg as any).verify_attestations(msgB64u, JSON.stringify(attestations), allowedPublicKeys ? JSON.stringify(allowedPublicKeys) : undefined);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return Number(out.valid_count || 0);\n}\n\n// Utility functions\n// Cross-env base64url helpers (browser + Node)\nfunction _fromByteArray(bytes: Uint8Array): string {\n if (typeof btoa === 'function') {\n // Browser\n let s = '';\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return btoa(s);\n }\n // Node\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction _toByteArray(b64: string): Uint8Array {\n if (typeof atob === 'function') {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n }\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n\nexport function b64uEncode(data: Uint8Array): string {\n return _fromByteArray(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+/g, '');\n}\n\nexport function b64uDecode(str: string): Uint8Array {\n const b64 = str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '=');\n return _toByteArray(b64);\n}\n\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n// ============================================================================\n// THRESHOLD SIGNATURES & GOVERNANCE\n// ============================================================================\n\nexport interface GovernancePolicy {\n policyId: string;\n version: number;\n chainId: string;\n threshold: number;\n signers: Array<{\n publicKeyB64u: string;\n keyId: string;\n weight: number;\n role: 'owner' | 'guardian' | 'delegate' | 'recovery';\n }>;\n operations: Array<{\n action: string;\n requiredThreshold?: number;\n requiredRoles?: string[];\n maxValue?: string;\n timelock?: number;\n }>;\n validFrom: number;\n validUntil: number;\n createdAt: number;\n createdBy: string;\n policySignature: string;\n}\n\nexport interface Attestation {\n signerKeyId: string;\n signerPublicKeyB64u: string;\n operationHash: string;\n operationType: string;\n attestedAt: number;\n expiresAt: number;\n signatureAlg: 'dilithium2';\n signatureB64u: string;\n}\n\nexport interface AggregatedSignature {\n policyId: string;\n policyVersion: number;\n operationHash: string;\n attestations: Attestation[];\n totalWeight: number;\n thresholdMet: boolean;\n verifiedAt: number;\n}\n\n/**\n * Create an attestation for a threshold signature operation.\n */\nexport async function createAttestation(\n operation: { type: string; payload: unknown },\n signerKeys: { keyId: string; publicKeyB64u: string; secretKeyB64u: string },\n expiresInSeconds: number = 3600\n): Promise<Attestation> {\n await initWasm();\n \n // Build deterministic preimage for the operation\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const operationHash = await sha256B64u(preimageBytes);\n const msgB64u = b64uEncode(preimageBytes);\n \n // Sign the preimage\n const sig = await dilithiumSign(msgB64u, signerKeys.secretKeyB64u);\n \n return {\n signerKeyId: signerKeys.keyId,\n signerPublicKeyB64u: signerKeys.publicKeyB64u,\n operationHash,\n operationType: operation.type,\n attestedAt: Date.now(),\n expiresAt: Date.now() + expiresInSeconds * 1000,\n signatureAlg: 'dilithium2',\n signatureB64u: sig.signature_b64u\n };\n}\n\n/**\n * Verify an attestation signature.\n */\nexport async function verifyAttestation(\n attestation: Attestation,\n operation: { type: string; payload: unknown }\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Rebuild expected operation hash\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const expectedHash = await sha256B64u(preimageBytes);\n \n if (attestation.operationHash !== expectedHash) {\n return { valid: false, error: 'Operation hash mismatch' };\n }\n \n // Check expiry\n if (attestation.expiresAt < Date.now()) {\n return { valid: false, error: 'Attestation expired' };\n }\n \n // Verify signature\n const msgB64u = b64uEncode(preimageBytes);\n const result = await dilithiumVerify(msgB64u, attestation.signatureB64u, attestation.signerPublicKeyB64u);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that an aggregated signature meets the threshold policy.\n */\nexport async function verifyThreshold(\n aggregated: AggregatedSignature,\n operation: { type: string; payload: unknown },\n policy: GovernancePolicy\n): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n \n // Check policy match\n if (aggregated.policyId !== policy.policyId) {\n errors.push('Policy ID mismatch');\n }\n \n // Verify each attestation and compute weight\n let validWeight = 0;\n for (const attestation of aggregated.attestations) {\n const signer = policy.signers.find(s => s.publicKeyB64u === attestation.signerPublicKeyB64u);\n if (!signer) {\n errors.push(`Signer ${attestation.signerKeyId} not in policy`);\n continue;\n }\n \n const result = await verifyAttestation(attestation, operation);\n if (!result.valid) {\n errors.push(`Attestation from ${attestation.signerKeyId}: ${result.error}`);\n continue;\n }\n \n validWeight += signer.weight;\n }\n \n // Check threshold\n if (validWeight < policy.threshold) {\n errors.push(`Threshold not met: weight ${validWeight} < required ${policy.threshold}`);\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n// ============================================================================\n// PRE-REGISTRATION COMMITMENT SCHEME\n// ============================================================================\n\nexport interface ProvenanceCommitment {\n type: 'ProvenanceCommitment';\n version: 1;\n commitmentHash: string;\n creatorPublicKey: string;\n timestamp: number;\n signature: string;\n}\n\nexport interface CommitmentReveal {\n commitmentHash: string;\n salt: string;\n assetHash: string;\n}\n\n/**\n * Create a provenance commitment for an asset before public disclosure.\n * This establishes a timestamped claim without revealing the asset content.\n */\nexport async function createProvenanceCommitment(\n assetBytes: Uint8Array,\n keys: { publicKeyB64u: string; secretKeyB64u: string }\n): Promise<{ commitment: ProvenanceCommitment; reveal: CommitmentReveal }> {\n await initWasm();\n \n // Generate random salt\n const salt = crypto.getRandomValues(new Uint8Array(32));\n \n // Compute commitment hash = SHA256(asset || salt || publicKey)\n const publicKeyBytes = b64uDecode(keys.publicKeyB64u);\n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const commitmentHash = await sha256B64u(preimage);\n const assetHash = await sha256B64u(assetBytes);\n \n // Build commitment object (without signature)\n const commitmentData = {\n type: 'ProvenanceCommitment' as const,\n version: 1 as const,\n commitmentHash,\n creatorPublicKey: keys.publicKeyB64u,\n timestamp: Date.now()\n };\n \n // Sign the commitment\n const canonical = await jcsCanonicalize(commitmentData);\n const sig = await dilithiumSign(b64uEncode(new TextEncoder().encode(canonical)), keys.secretKeyB64u);\n \n const commitment: ProvenanceCommitment = {\n ...commitmentData,\n signature: sig.signature_b64u\n };\n \n const reveal: CommitmentReveal = {\n commitmentHash,\n salt: b64uEncode(salt),\n assetHash\n };\n \n return { commitment, reveal };\n}\n\n/**\n * Verify a provenance commitment signature.\n */\nexport async function verifyProvenanceCommitment(\n commitment: ProvenanceCommitment\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Reconstruct the signed data (without signature field)\n const commitmentData = {\n type: commitment.type,\n version: commitment.version,\n commitmentHash: commitment.commitmentHash,\n creatorPublicKey: commitment.creatorPublicKey,\n timestamp: commitment.timestamp\n };\n \n const canonical = await jcsCanonicalize(commitmentData);\n const msgB64u = b64uEncode(new TextEncoder().encode(canonical));\n \n const result = await dilithiumVerify(msgB64u, commitment.signature, commitment.creatorPublicKey);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid commitment signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that a revealed asset matches a commitment.\n */\nexport async function verifyCommitmentReveal(\n commitment: ProvenanceCommitment,\n assetBytes: Uint8Array,\n reveal: CommitmentReveal\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // First verify the commitment signature\n const sigResult = await verifyProvenanceCommitment(commitment);\n if (!sigResult.valid) {\n return { valid: false, error: `Commitment signature invalid: ${sigResult.error}` };\n }\n \n // Verify asset hash matches\n const computedAssetHash = await sha256B64u(assetBytes);\n if (computedAssetHash !== reveal.assetHash) {\n return { valid: false, error: 'Asset hash does not match reveal' };\n }\n \n // Reconstruct commitment hash\n const salt = b64uDecode(reveal.salt);\n const publicKeyBytes = b64uDecode(commitment.creatorPublicKey);\n \n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const computedCommitmentHash = await sha256B64u(preimage);\n \n if (computedCommitmentHash !== commitment.commitmentHash) {\n return { valid: false, error: 'Commitment hash does not match reveal' };\n }\n \n return { valid: true };\n}\n\n// ============================================================================\n// HELPER: SHA-256 with base64url output\n// ============================================================================\n\nasync function sha256B64u(data: Uint8Array): Promise<string> {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data as unknown as BufferSource);\n return b64uEncode(new Uint8Array(hashBuffer));\n}\n\n// ============================================================================\n// ALGORITHMIC OPTIMIZATIONS (arXiv:2501.02305, arXiv:2504.17033)\n// ============================================================================\n// High-performance data structures for verification operations\n\n// WASM bindings for algorithm functions\nconst wasm_create_nonce_cache = (wasmPkg as any).create_nonce_cache as (capacity: number, ttl_ms: number) => string;\nconst wasm_nonce_cache_info = (wasmPkg as any).nonce_cache_info as () => string;\nconst wasm_sssp_config = (wasmPkg as any).sssp_config as (nodes: number) => string;\nconst wasm_provenance_path_config = (wasmPkg as any).provenance_path_config as (chain_length: number, branches: number) => string;\nconst wasm_elastic_hash_config = (wasmPkg as any).elastic_hash_config as (capacity: number, load_factor: number) => string;\n\n/**\n * Nonce Cache Configuration\n * Uses Elastic Hashing (arXiv:2501.02305) for O(1) amortized lookup\n */\nexport interface NonceCacheConfig {\n type: string;\n capacity: number;\n ttl_ms: number;\n algorithm: string;\n complexity: string;\n}\n\n/**\n * Create a nonce cache configuration for replay attack prevention.\n * Based on Elastic Hashing - O(1) amortized, O(log(1/δ)) worst-case.\n * \n * @param capacity - Maximum number of nonces to track\n * @param ttlMs - Time-to-live in milliseconds before nonces expire\n */\nexport async function createNonceCacheConfig(capacity: number, ttlMs: number): Promise<NonceCacheConfig> {\n await initWasm();\n return JSON.parse(wasm_create_nonce_cache(capacity, ttlMs));\n}\n\n/**\n * Get information about the nonce cache algorithm.\n */\nexport async function getNonceCacheInfo(): Promise<{\n name: string;\n paper: string;\n probe_complexity: string;\n load_factor: number;\n features: string[];\n}> {\n await initWasm();\n return JSON.parse(wasm_nonce_cache_info());\n}\n\n/**\n * SSSP (Single-Source Shortest Path) Configuration\n * Uses Frontier-Reduced algorithm (arXiv:2504.17033)\n */\nexport interface SSSPConfig {\n name: string;\n paper: string;\n complexity: string;\n nodes: number;\n pivots_k: number;\n batch_t: number;\n use_cases: string[];\n}\n\n/**\n * Get optimal SSSP configuration for graph verification.\n * Uses Frontier-Reduced SSSP - O(m × log^(2/3)(n)) complexity.\n * \n * @param nodes - Expected number of nodes in the graph\n */\nexport async function getSSSPConfig(nodes: number): Promise<SSSPConfig> {\n await initWasm();\n return JSON.parse(wasm_sssp_config(nodes));\n}\n\n/**\n * Provenance Path Configuration\n * Optimized parameters for chain of custody verification\n */\nexport interface ProvenancePathConfig {\n algorithm: string;\n chain_length: number;\n branches: number;\n estimated_nodes: number;\n estimated_edges: number;\n pivots_k: number;\n batch_t: number;\n complexity: string;\n verification_mode: string;\n}\n\n/**\n * Get optimized configuration for provenance chain verification.\n * \n * @param chainLength - Number of blocks in the provenance chain\n * @param branches - Average number of branches per block\n */\nexport async function getProvenancePathConfig(chainLength: number, branches: number): Promise<ProvenancePathConfig> {\n await initWasm();\n return JSON.parse(wasm_provenance_path_config(chainLength, branches));\n}\n\n/**\n * Elastic Hash Configuration\n * High-performance hash table for key caching\n */\nexport interface ElasticHashConfig {\n algorithm: string;\n paper: string;\n capacity: number;\n load_factor: number;\n levels: number;\n probe_complexity: {\n amortized: string;\n worst_case: string;\n };\n use_cases: string[];\n}\n\n/**\n * Get elastic hash table configuration for key caching.\n * Optimal for PQC public key caching with O(1) amortized lookups.\n * \n * @param capacity - Maximum number of entries\n * @param loadFactor - Target load factor (0.0 to 1.0, recommend 0.95)\n */\nexport async function getElasticHashConfig(capacity: number, loadFactor: number = 0.95): Promise<ElasticHashConfig> {\n await initWasm();\n return JSON.parse(wasm_elastic_hash_config(capacity, loadFactor));\n}\n"],"names":["wasmPkg"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC1C,MAAM,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;AA4CjC,MAAM,iBAAiB,GAAIA,kBAAe,CAAC,YAA4B;AACvE,MAAM,iBAAiB,GAAIA,kBAAe,CAAC,YAAqC;AAChF,MAAM,iBAAiB,GAAIA,kBAAe,CAAC,YAAgD;AAC3F,MAAM,gBAAgB,GAAIA,kBAAe,CAAC,WAA4E;AACtH,MAAM,iBAAiB,GAAIA,kBAAe,CAAC,YAA2D;AACtG,MAAM,mBAAmB,GAAIA,kBAAe,CAAC,cAA0E;AACvH,MAAM,qBAAqB,GAAIA,kBAAe,CAAC,gBAAgC;AAC/E,MAAM,mBAAmB,GAAIA,kBAAe,CAAC,cAAkD;AAC/F,MAAM,qBAAqB,GAAIA,kBAAe,CAAC,gBAAiE;AAKhH;AAC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;;;AAMG;AACI,eAAe,oBAAoB,CAAC,QAAgB,EAAE,aAAqB,IAAI,EAAA;IACpF,MAAM,QAAQ,EAAE;IAChB,OAAO,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;AACnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.mjs CHANGED
@@ -435,6 +435,65 @@ async function sha256B64u(data) {
435
435
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
436
436
  return b64uEncode(new Uint8Array(hashBuffer));
437
437
  }
438
+ // ============================================================================
439
+ // ALGORITHMIC OPTIMIZATIONS (arXiv:2501.02305, arXiv:2504.17033)
440
+ // ============================================================================
441
+ // High-performance data structures for verification operations
442
+ // WASM bindings for algorithm functions
443
+ const wasm_create_nonce_cache = wasmPkg.create_nonce_cache;
444
+ const wasm_nonce_cache_info = wasmPkg.nonce_cache_info;
445
+ const wasm_sssp_config = wasmPkg.sssp_config;
446
+ const wasm_provenance_path_config = wasmPkg.provenance_path_config;
447
+ const wasm_elastic_hash_config = wasmPkg.elastic_hash_config;
448
+ /**
449
+ * Create a nonce cache configuration for replay attack prevention.
450
+ * Based on Elastic Hashing - O(1) amortized, O(log(1/δ)) worst-case.
451
+ *
452
+ * @param capacity - Maximum number of nonces to track
453
+ * @param ttlMs - Time-to-live in milliseconds before nonces expire
454
+ */
455
+ async function createNonceCacheConfig(capacity, ttlMs) {
456
+ await initWasm();
457
+ return JSON.parse(wasm_create_nonce_cache(capacity, ttlMs));
458
+ }
459
+ /**
460
+ * Get information about the nonce cache algorithm.
461
+ */
462
+ async function getNonceCacheInfo() {
463
+ await initWasm();
464
+ return JSON.parse(wasm_nonce_cache_info());
465
+ }
466
+ /**
467
+ * Get optimal SSSP configuration for graph verification.
468
+ * Uses Frontier-Reduced SSSP - O(m × log^(2/3)(n)) complexity.
469
+ *
470
+ * @param nodes - Expected number of nodes in the graph
471
+ */
472
+ async function getSSSPConfig(nodes) {
473
+ await initWasm();
474
+ return JSON.parse(wasm_sssp_config(nodes));
475
+ }
476
+ /**
477
+ * Get optimized configuration for provenance chain verification.
478
+ *
479
+ * @param chainLength - Number of blocks in the provenance chain
480
+ * @param branches - Average number of branches per block
481
+ */
482
+ async function getProvenancePathConfig(chainLength, branches) {
483
+ await initWasm();
484
+ return JSON.parse(wasm_provenance_path_config(chainLength, branches));
485
+ }
486
+ /**
487
+ * Get elastic hash table configuration for key caching.
488
+ * Optimal for PQC public key caching with O(1) amortized lookups.
489
+ *
490
+ * @param capacity - Maximum number of entries
491
+ * @param loadFactor - Target load factor (0.0 to 1.0, recommend 0.95)
492
+ */
493
+ async function getElasticHashConfig(capacity, loadFactor = 0.95) {
494
+ await initWasm();
495
+ return JSON.parse(wasm_elastic_hash_config(capacity, loadFactor));
496
+ }
438
497
 
439
- export { aesGcmUnwrap, aesGcmWrap, b64uDecode, b64uEncode, buildAnchorPreimage, buildBlockPreimage, buildMintPreimage, buildPolicyPreimage, buildTransferPreimage, constantTimeEqual, createAttestation, createProvenanceCommitment, dilithiumKeygen, dilithiumSign, dilithiumVerify, hkdfSha256, initWasm, jcsCanonicalize, kyberDecaps, kyberEncaps, kyberKeygen, validateRoyalty, verifyAttestation, verifyAttestations, verifyCommitmentReveal, verifyProvenanceCommitment, verifyThreshold };
498
+ export { aesGcmUnwrap, aesGcmWrap, b64uDecode, b64uEncode, buildAnchorPreimage, buildBlockPreimage, buildMintPreimage, buildPolicyPreimage, buildTransferPreimage, constantTimeEqual, createAttestation, createNonceCacheConfig, createProvenanceCommitment, dilithiumKeygen, dilithiumSign, dilithiumVerify, getElasticHashConfig, getNonceCacheInfo, getProvenancePathConfig, getSSSPConfig, hkdfSha256, initWasm, jcsCanonicalize, kyberDecaps, kyberEncaps, kyberKeygen, validateRoyalty, verifyAttestation, verifyAttestations, verifyCommitmentReveal, verifyProvenanceCommitment, verifyThreshold };
440
499
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../src/index.ts"],"sourcesContent":["// Ma'atara Core PQC Toolkit\n// Post-Quantum Cryptography for Browser and Node.js\n// \n// SECURITY NOTICE: This library implements FIPS 204 (ML-DSA) and FIPS 203 (ML-KEM)\n// post-quantum cryptographic algorithms. Key material should be:\n// 1. Stored securely (encrypted at rest)\n// 2. Transmitted only over secure channels\n// 3. Zeroized after use when possible\n// 4. Protected by hardware security modules for high-value operations\n//\n// See docs/WASM_SECURITY_MODEL.md for browser-specific security considerations.\n\n// ============================================================================\n// SECURITY CONSTANTS\n// ============================================================================\nconst MAX_MESSAGE_SIZE = 16 * 1024 * 1024; // 16MB - prevent memory exhaustion\nconst MAX_KEY_SIZE = 1024 * 1024; // 1MB - reasonable for PQC keys\nconst MAX_ATTESTATION_COUNT = 100; // Prevent DoS from large attestation arrays\n\nexport interface KyberKeypair {\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface KyberEncap {\n kem_ct_b64u: string;\n shared_b64u: string;\n}\n\nexport interface AesGcmWrap {\n iv_b64u: string;\n ct_b64u: string;\n}\n\nexport interface DilithiumKeypair {\n algorithm: string;\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface DilithiumSignResult {\n signature_b64u: string;\n algorithm: string;\n}\n\nexport interface DilithiumVerifyResult {\n is_valid: boolean;\n algorithm: string;\n}\n\nexport interface HkdfResult {\n key_b64u: string;\n}\n\nexport interface AesGcmUnwrapResult {\n dek_b64u: string;\n}\n\n// Import WASM functions (namespace import for better bundler compatibility)\nimport * as wasmPkg from '@maatara/core-pqc-wasm';\nconst wasm_kyber_keygen = (wasmPkg as any).kyber_keygen as () => string;\nconst wasm_kyber_encaps = (wasmPkg as any).kyber_encaps as (p: string) => string;\nconst wasm_kyber_decaps = (wasmPkg as any).kyber_decaps as (s: string, c: string) => string;\nconst wasm_hkdf_sha256 = (wasmPkg as any).hkdf_sha256 as (s: string, i: string, salt?: string, len?: number) => string;\nconst wasm_aes_gcm_wrap = (wasmPkg as any).aes_gcm_wrap as (k: string, d: string, a: string) => string;\nconst wasm_aes_gcm_unwrap = (wasmPkg as any).aes_gcm_unwrap as (k: string, iv: string, ct: string, a: string) => string;\nconst wasm_dilithium_keygen = (wasmPkg as any).dilithium_keygen as () => string;\nconst wasm_dilithium_sign = (wasmPkg as any).dilithium_sign as (m: string, s: string) => string;\nconst wasm_dilithium_verify = (wasmPkg as any).dilithium_verify as (m: string, sig: string, p: string) => string;\n\n// Deterministic/canonicalization and governance helpers\nexport interface CanonicalOut { canonical: string; msg_b64u?: string; msgB64u?: string }\n\n// Initialize WASM\nlet wasmReady = false;\n\n/**\n * Initialize the underlying WASM module.\n * - In browsers/bundlers where the glue knows how to fetch the .wasm, you can call without params.\n * - If your bundler provides a URL or Module for the .wasm, pass it as the first argument.\n */\nexport async function initWasm(wasmInput?: any): Promise<void> {\n if (wasmReady) return;\n const maybeInit = (wasmPkg as any).default;\n if (typeof maybeInit === 'function') {\n // Some environments require a URL/Module/bytes for initialization.\n // We forward the optional value if provided; otherwise let the glue resolve it.\n if (wasmInput !== undefined) {\n await maybeInit(wasmInput);\n } else {\n await maybeInit();\n }\n }\n wasmReady = true;\n}\n\n// Kyber functions\nexport async function kyberKeygen(): Promise<KyberKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberEncaps(publicB64u: string): Promise<KyberEncap> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_encaps(publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberDecaps(secretB64u: string, kemCtB64u: string): Promise<{ shared_b64u: string }> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_decaps(secretB64u, kemCtB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// HKDF functions\nexport async function hkdfSha256(\n secretB64u: string,\n infoB64u: string,\n saltB64u?: string,\n len: number = 32\n): Promise<HkdfResult> {\n await initWasm();\n const result = JSON.parse(wasm_hkdf_sha256(secretB64u, infoB64u, saltB64u, len));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// AES-GCM functions\nexport async function aesGcmWrap(\n keyB64u: string,\n dekB64u: string,\n aadB64u: string\n): Promise<AesGcmWrap> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_wrap(keyB64u, dekB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function aesGcmUnwrap(\n keyB64u: string,\n ivB64u: string,\n ctB64u: string,\n aadB64u: string\n): Promise<AesGcmUnwrapResult> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_unwrap(keyB64u, ivB64u, ctB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// Dilithium functions\n\n/**\n * Generate a new ML-DSA-65 (Dilithium) keypair.\n * SECURITY: Keys should be stored encrypted at rest.\n * For high-value operations, consider hardware security modules.\n */\nexport async function dilithiumKeygen(): Promise<DilithiumKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_dilithium_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Sign a message using ML-DSA-65 (Dilithium).\n * @param messageB64u - Base64url-encoded message to sign\n * @param secretB64u - Base64url-encoded secret key\n * SECURITY: Secret key should be zeroized after use if possible.\n */\nexport async function dilithiumSign(\n messageB64u: string,\n secretB64u: string\n): Promise<DilithiumSignResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (secretB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Secret key exceeds maximum size of ${MAX_KEY_SIZE} bytes`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_sign(messageB64u, secretB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Verify a ML-DSA-65 (Dilithium) signature.\n * @param messageB64u - Base64url-encoded message\n * @param signatureB64u - Base64url-encoded signature\n * @param publicB64u - Base64url-encoded public key\n */\nexport async function dilithiumVerify(\n messageB64u: string,\n signatureB64u: string,\n publicB64u: string\n): Promise<DilithiumVerifyResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (signatureB64u.length > MAX_KEY_SIZE || publicB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Signature or public key exceeds maximum size`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_verify(messageB64u, signatureB64u, publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// ---- Deterministic helpers (multisig/art token) ----\nexport async function jcsCanonicalize(json: unknown): Promise<string> {\n await initWasm();\n const raw = (wasmPkg as any).jcs_canonicalize(JSON.stringify(json));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return out.canonical as string;\n}\n\nexport async function buildPolicyPreimage(policy: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_governance(JSON.stringify(policy));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildMintPreimage(header: unknown, asset: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_mint(JSON.stringify(header), JSON.stringify(asset));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildTransferPreimage(header: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_transfer(JSON.stringify(header));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildAnchorPreimage(userId: string, rootHex: string, epoch: string, chains: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_anchor(userId, rootHex, epoch, JSON.stringify(chains));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\n// ---- Veritas Block Preimage (NEW v2 JCS canonical form) ----\n// We migrate block signing to a canonical (JCS) JSON similar to other preimages.\n// Legacy (v1) blocks used a hand-crafted JSON.stringify of a plain object with fixed insertion order.\n// This helper produces a canonical JSON string and msg_b64u = b64url(UTF-8(canonical JSON)).\n// NOTE: We intentionally EXCLUDE signature, encryptionKeyHash, and any runtime-only fields.\n// Fields included (ordered via JCS lexical ordering):\n// contentType, dataHash, index, metadataHash, ownerPublicKey, previousHash, signatureAlg, timestamp, version\n// index & timestamp MUST be strings representing decimal integers (BigInt safe) – caller responsibility.\nexport interface BlockPreimageInput {\n index: string | number | bigint;\n timestamp: string | number | bigint;\n previousHash: string;\n dataHash: string;\n metadataHash: string;\n signatureAlg: string; // e.g. 'dilithium2'\n ownerPublicKey: string; // Dilithium public key (base64url)\n contentType?: string; // default 'application/json'\n version: number; // block format / protocol version\n}\n\nexport async function buildBlockPreimage(block: BlockPreimageInput): Promise<CanonicalOut> {\n await initWasm();\n // Normalize fields per spec\n const normalized = {\n contentType: block.contentType || 'application/json',\n dataHash: block.dataHash,\n index: block.index.toString(),\n metadataHash: block.metadataHash,\n ownerPublicKey: block.ownerPublicKey,\n previousHash: block.previousHash,\n signatureAlg: block.signatureAlg,\n timestamp: block.timestamp.toString(),\n version: block.version,\n };\n // Use JCS canonicalization via wasm jcs_canonicalize (already exposed through jcsCanonicalize helper)\n const canonical = await jcsCanonicalize(normalized);\n const msg_b64u = b64uEncode(new TextEncoder().encode(canonical));\n return { canonical, msg_b64u, msgB64u: msg_b64u };\n}\n\nexport async function validateRoyalty(receiver: string, bps: number): Promise<boolean> {\n await initWasm();\n const raw = (wasmPkg as any).validate_royalty(receiver, bps);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) return false;\n return !!out.ok;\n}\n\nexport async function verifyAttestations(msgB64u: string, attestations: Array<{ alg: string; publicKeyB64u: string; signatureB64u: string }>, allowedPublicKeys?: string[]): Promise<number> {\n await initWasm();\n const raw = (wasmPkg as any).verify_attestations(msgB64u, JSON.stringify(attestations), allowedPublicKeys ? JSON.stringify(allowedPublicKeys) : undefined);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return Number(out.valid_count || 0);\n}\n\n// Utility functions\n// Cross-env base64url helpers (browser + Node)\nfunction _fromByteArray(bytes: Uint8Array): string {\n if (typeof btoa === 'function') {\n // Browser\n let s = '';\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return btoa(s);\n }\n // Node\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction _toByteArray(b64: string): Uint8Array {\n if (typeof atob === 'function') {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n }\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n\nexport function b64uEncode(data: Uint8Array): string {\n return _fromByteArray(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+/g, '');\n}\n\nexport function b64uDecode(str: string): Uint8Array {\n const b64 = str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '=');\n return _toByteArray(b64);\n}\n\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n// ============================================================================\n// THRESHOLD SIGNATURES & GOVERNANCE\n// ============================================================================\n\nexport interface GovernancePolicy {\n policyId: string;\n version: number;\n chainId: string;\n threshold: number;\n signers: Array<{\n publicKeyB64u: string;\n keyId: string;\n weight: number;\n role: 'owner' | 'guardian' | 'delegate' | 'recovery';\n }>;\n operations: Array<{\n action: string;\n requiredThreshold?: number;\n requiredRoles?: string[];\n maxValue?: string;\n timelock?: number;\n }>;\n validFrom: number;\n validUntil: number;\n createdAt: number;\n createdBy: string;\n policySignature: string;\n}\n\nexport interface Attestation {\n signerKeyId: string;\n signerPublicKeyB64u: string;\n operationHash: string;\n operationType: string;\n attestedAt: number;\n expiresAt: number;\n signatureAlg: 'dilithium2';\n signatureB64u: string;\n}\n\nexport interface AggregatedSignature {\n policyId: string;\n policyVersion: number;\n operationHash: string;\n attestations: Attestation[];\n totalWeight: number;\n thresholdMet: boolean;\n verifiedAt: number;\n}\n\n/**\n * Create an attestation for a threshold signature operation.\n */\nexport async function createAttestation(\n operation: { type: string; payload: unknown },\n signerKeys: { keyId: string; publicKeyB64u: string; secretKeyB64u: string },\n expiresInSeconds: number = 3600\n): Promise<Attestation> {\n await initWasm();\n \n // Build deterministic preimage for the operation\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const operationHash = await sha256B64u(preimageBytes);\n const msgB64u = b64uEncode(preimageBytes);\n \n // Sign the preimage\n const sig = await dilithiumSign(msgB64u, signerKeys.secretKeyB64u);\n \n return {\n signerKeyId: signerKeys.keyId,\n signerPublicKeyB64u: signerKeys.publicKeyB64u,\n operationHash,\n operationType: operation.type,\n attestedAt: Date.now(),\n expiresAt: Date.now() + expiresInSeconds * 1000,\n signatureAlg: 'dilithium2',\n signatureB64u: sig.signature_b64u\n };\n}\n\n/**\n * Verify an attestation signature.\n */\nexport async function verifyAttestation(\n attestation: Attestation,\n operation: { type: string; payload: unknown }\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Rebuild expected operation hash\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const expectedHash = await sha256B64u(preimageBytes);\n \n if (attestation.operationHash !== expectedHash) {\n return { valid: false, error: 'Operation hash mismatch' };\n }\n \n // Check expiry\n if (attestation.expiresAt < Date.now()) {\n return { valid: false, error: 'Attestation expired' };\n }\n \n // Verify signature\n const msgB64u = b64uEncode(preimageBytes);\n const result = await dilithiumVerify(msgB64u, attestation.signatureB64u, attestation.signerPublicKeyB64u);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that an aggregated signature meets the threshold policy.\n */\nexport async function verifyThreshold(\n aggregated: AggregatedSignature,\n operation: { type: string; payload: unknown },\n policy: GovernancePolicy\n): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n \n // Check policy match\n if (aggregated.policyId !== policy.policyId) {\n errors.push('Policy ID mismatch');\n }\n \n // Verify each attestation and compute weight\n let validWeight = 0;\n for (const attestation of aggregated.attestations) {\n const signer = policy.signers.find(s => s.publicKeyB64u === attestation.signerPublicKeyB64u);\n if (!signer) {\n errors.push(`Signer ${attestation.signerKeyId} not in policy`);\n continue;\n }\n \n const result = await verifyAttestation(attestation, operation);\n if (!result.valid) {\n errors.push(`Attestation from ${attestation.signerKeyId}: ${result.error}`);\n continue;\n }\n \n validWeight += signer.weight;\n }\n \n // Check threshold\n if (validWeight < policy.threshold) {\n errors.push(`Threshold not met: weight ${validWeight} < required ${policy.threshold}`);\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n// ============================================================================\n// PRE-REGISTRATION COMMITMENT SCHEME\n// ============================================================================\n\nexport interface ProvenanceCommitment {\n type: 'ProvenanceCommitment';\n version: 1;\n commitmentHash: string;\n creatorPublicKey: string;\n timestamp: number;\n signature: string;\n}\n\nexport interface CommitmentReveal {\n commitmentHash: string;\n salt: string;\n assetHash: string;\n}\n\n/**\n * Create a provenance commitment for an asset before public disclosure.\n * This establishes a timestamped claim without revealing the asset content.\n */\nexport async function createProvenanceCommitment(\n assetBytes: Uint8Array,\n keys: { publicKeyB64u: string; secretKeyB64u: string }\n): Promise<{ commitment: ProvenanceCommitment; reveal: CommitmentReveal }> {\n await initWasm();\n \n // Generate random salt\n const salt = crypto.getRandomValues(new Uint8Array(32));\n \n // Compute commitment hash = SHA256(asset || salt || publicKey)\n const publicKeyBytes = b64uDecode(keys.publicKeyB64u);\n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const commitmentHash = await sha256B64u(preimage);\n const assetHash = await sha256B64u(assetBytes);\n \n // Build commitment object (without signature)\n const commitmentData = {\n type: 'ProvenanceCommitment' as const,\n version: 1 as const,\n commitmentHash,\n creatorPublicKey: keys.publicKeyB64u,\n timestamp: Date.now()\n };\n \n // Sign the commitment\n const canonical = await jcsCanonicalize(commitmentData);\n const sig = await dilithiumSign(b64uEncode(new TextEncoder().encode(canonical)), keys.secretKeyB64u);\n \n const commitment: ProvenanceCommitment = {\n ...commitmentData,\n signature: sig.signature_b64u\n };\n \n const reveal: CommitmentReveal = {\n commitmentHash,\n salt: b64uEncode(salt),\n assetHash\n };\n \n return { commitment, reveal };\n}\n\n/**\n * Verify a provenance commitment signature.\n */\nexport async function verifyProvenanceCommitment(\n commitment: ProvenanceCommitment\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Reconstruct the signed data (without signature field)\n const commitmentData = {\n type: commitment.type,\n version: commitment.version,\n commitmentHash: commitment.commitmentHash,\n creatorPublicKey: commitment.creatorPublicKey,\n timestamp: commitment.timestamp\n };\n \n const canonical = await jcsCanonicalize(commitmentData);\n const msgB64u = b64uEncode(new TextEncoder().encode(canonical));\n \n const result = await dilithiumVerify(msgB64u, commitment.signature, commitment.creatorPublicKey);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid commitment signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that a revealed asset matches a commitment.\n */\nexport async function verifyCommitmentReveal(\n commitment: ProvenanceCommitment,\n assetBytes: Uint8Array,\n reveal: CommitmentReveal\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // First verify the commitment signature\n const sigResult = await verifyProvenanceCommitment(commitment);\n if (!sigResult.valid) {\n return { valid: false, error: `Commitment signature invalid: ${sigResult.error}` };\n }\n \n // Verify asset hash matches\n const computedAssetHash = await sha256B64u(assetBytes);\n if (computedAssetHash !== reveal.assetHash) {\n return { valid: false, error: 'Asset hash does not match reveal' };\n }\n \n // Reconstruct commitment hash\n const salt = b64uDecode(reveal.salt);\n const publicKeyBytes = b64uDecode(commitment.creatorPublicKey);\n \n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const computedCommitmentHash = await sha256B64u(preimage);\n \n if (computedCommitmentHash !== commitment.commitmentHash) {\n return { valid: false, error: 'Commitment hash does not match reveal' };\n }\n \n return { valid: true };\n}\n\n// ============================================================================\n// HELPER: SHA-256 with base64url output\n// ============================================================================\n\nasync function sha256B64u(data: Uint8Array): Promise<string> {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data as unknown as BufferSource);\n return b64uEncode(new Uint8Array(hashBuffer));\n}\n\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC1C,MAAM,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;AA4CjC,MAAM,iBAAiB,GAAI,OAAe,CAAC,YAA4B,CAAC;AACxE,MAAM,iBAAiB,GAAI,OAAe,CAAC,YAAqC,CAAC;AACjF,MAAM,iBAAiB,GAAI,OAAe,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tC,IAAA,QAAQ,CAAC,GAAG,CAAC,cAAc,EAAE,UAAU,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;AAE9D,IAAA,MAAM,sBAAsB,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,CAAC;AAE1D,IAAA,IAAI,sBAAsB,KAAK,UAAU,CAAC,cAAc,EAAE;QACxD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,uCAAuC,EAAE,CAAC;KACzE;AAED,IAAA,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;AACA;AACA;AAEA,eAAe,UAAU,CAAC,IAAgB,EAAA;AACxC,IAAA,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAA+B,CAAC,CAAC;IAC1F,OAAO,UAAU,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;AAChD;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../src/index.ts"],"sourcesContent":["// Ma'atara Core PQC Toolkit\n// Post-Quantum Cryptography for Browser and Node.js\n// \n// SECURITY NOTICE: This library implements FIPS 204 (ML-DSA) and FIPS 203 (ML-KEM)\n// post-quantum cryptographic algorithms. Key material should be:\n// 1. Stored securely (encrypted at rest)\n// 2. Transmitted only over secure channels\n// 3. Zeroized after use when possible\n// 4. Protected by hardware security modules for high-value operations\n//\n// See docs/WASM_SECURITY_MODEL.md for browser-specific security considerations.\n\n// ============================================================================\n// SECURITY CONSTANTS\n// ============================================================================\nconst MAX_MESSAGE_SIZE = 16 * 1024 * 1024; // 16MB - prevent memory exhaustion\nconst MAX_KEY_SIZE = 1024 * 1024; // 1MB - reasonable for PQC keys\nconst MAX_ATTESTATION_COUNT = 100; // Prevent DoS from large attestation arrays\n\nexport interface KyberKeypair {\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface KyberEncap {\n kem_ct_b64u: string;\n shared_b64u: string;\n}\n\nexport interface AesGcmWrap {\n iv_b64u: string;\n ct_b64u: string;\n}\n\nexport interface DilithiumKeypair {\n algorithm: string;\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface DilithiumSignResult {\n signature_b64u: string;\n algorithm: string;\n}\n\nexport interface DilithiumVerifyResult {\n is_valid: boolean;\n algorithm: string;\n}\n\nexport interface HkdfResult {\n key_b64u: string;\n}\n\nexport interface AesGcmUnwrapResult {\n dek_b64u: string;\n}\n\n// Import WASM functions (namespace import for better bundler compatibility)\nimport * as wasmPkg from '@maatara/core-pqc-wasm';\nconst wasm_kyber_keygen = (wasmPkg as any).kyber_keygen as () => string;\nconst wasm_kyber_encaps = (wasmPkg as any).kyber_encaps as (p: string) => string;\nconst wasm_kyber_decaps = (wasmPkg as any).kyber_decaps as (s: string, c: string) => string;\nconst wasm_hkdf_sha256 = (wasmPkg as any).hkdf_sha256 as (s: string, i: string, salt?: string, len?: number) => string;\nconst wasm_aes_gcm_wrap = (wasmPkg as any).aes_gcm_wrap as (k: string, d: string, a: string) => string;\nconst wasm_aes_gcm_unwrap = (wasmPkg as any).aes_gcm_unwrap as (k: string, iv: string, ct: string, a: string) => string;\nconst wasm_dilithium_keygen = (wasmPkg as any).dilithium_keygen as () => string;\nconst wasm_dilithium_sign = (wasmPkg as any).dilithium_sign as (m: string, s: string) => string;\nconst wasm_dilithium_verify = (wasmPkg as any).dilithium_verify as (m: string, sig: string, p: string) => string;\n\n// Deterministic/canonicalization and governance helpers\nexport interface CanonicalOut { canonical: string; msg_b64u?: string; msgB64u?: string }\n\n// Initialize WASM\nlet wasmReady = false;\n\n/**\n * Initialize the underlying WASM module.\n * - In browsers/bundlers where the glue knows how to fetch the .wasm, you can call without params.\n * - If your bundler provides a URL or Module for the .wasm, pass it as the first argument.\n */\nexport async function initWasm(wasmInput?: any): Promise<void> {\n if (wasmReady) return;\n const maybeInit = (wasmPkg as any).default;\n if (typeof maybeInit === 'function') {\n // Some environments require a URL/Module/bytes for initialization.\n // We forward the optional value if provided; otherwise let the glue resolve it.\n if (wasmInput !== undefined) {\n await maybeInit(wasmInput);\n } else {\n await maybeInit();\n }\n }\n wasmReady = true;\n}\n\n// Kyber functions\nexport async function kyberKeygen(): Promise<KyberKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberEncaps(publicB64u: string): Promise<KyberEncap> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_encaps(publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberDecaps(secretB64u: string, kemCtB64u: string): Promise<{ shared_b64u: string }> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_decaps(secretB64u, kemCtB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// HKDF functions\nexport async function hkdfSha256(\n secretB64u: string,\n infoB64u: string,\n saltB64u?: string,\n len: number = 32\n): Promise<HkdfResult> {\n await initWasm();\n const result = JSON.parse(wasm_hkdf_sha256(secretB64u, infoB64u, saltB64u, len));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// AES-GCM functions\nexport async function aesGcmWrap(\n keyB64u: string,\n dekB64u: string,\n aadB64u: string\n): Promise<AesGcmWrap> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_wrap(keyB64u, dekB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function aesGcmUnwrap(\n keyB64u: string,\n ivB64u: string,\n ctB64u: string,\n aadB64u: string\n): Promise<AesGcmUnwrapResult> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_unwrap(keyB64u, ivB64u, ctB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// Dilithium functions\n\n/**\n * Generate a new ML-DSA-65 (Dilithium) keypair.\n * SECURITY: Keys should be stored encrypted at rest.\n * For high-value operations, consider hardware security modules.\n */\nexport async function dilithiumKeygen(): Promise<DilithiumKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_dilithium_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Sign a message using ML-DSA-65 (Dilithium).\n * @param messageB64u - Base64url-encoded message to sign\n * @param secretB64u - Base64url-encoded secret key\n * SECURITY: Secret key should be zeroized after use if possible.\n */\nexport async function dilithiumSign(\n messageB64u: string,\n secretB64u: string\n): Promise<DilithiumSignResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (secretB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Secret key exceeds maximum size of ${MAX_KEY_SIZE} bytes`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_sign(messageB64u, secretB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Verify a ML-DSA-65 (Dilithium) signature.\n * @param messageB64u - Base64url-encoded message\n * @param signatureB64u - Base64url-encoded signature\n * @param publicB64u - Base64url-encoded public key\n */\nexport async function dilithiumVerify(\n messageB64u: string,\n signatureB64u: string,\n publicB64u: string\n): Promise<DilithiumVerifyResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (signatureB64u.length > MAX_KEY_SIZE || publicB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Signature or public key exceeds maximum size`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_verify(messageB64u, signatureB64u, publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// ---- Deterministic helpers (multisig/art token) ----\nexport async function jcsCanonicalize(json: unknown): Promise<string> {\n await initWasm();\n const raw = (wasmPkg as any).jcs_canonicalize(JSON.stringify(json));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return out.canonical as string;\n}\n\nexport async function buildPolicyPreimage(policy: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_governance(JSON.stringify(policy));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildMintPreimage(header: unknown, asset: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_mint(JSON.stringify(header), JSON.stringify(asset));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildTransferPreimage(header: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_transfer(JSON.stringify(header));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildAnchorPreimage(userId: string, rootHex: string, epoch: string, chains: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_anchor(userId, rootHex, epoch, JSON.stringify(chains));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\n// ---- Veritas Block Preimage (NEW v2 JCS canonical form) ----\n// We migrate block signing to a canonical (JCS) JSON similar to other preimages.\n// Legacy (v1) blocks used a hand-crafted JSON.stringify of a plain object with fixed insertion order.\n// This helper produces a canonical JSON string and msg_b64u = b64url(UTF-8(canonical JSON)).\n// NOTE: We intentionally EXCLUDE signature, encryptionKeyHash, and any runtime-only fields.\n// Fields included (ordered via JCS lexical ordering):\n// contentType, dataHash, index, metadataHash, ownerPublicKey, previousHash, signatureAlg, timestamp, version\n// index & timestamp MUST be strings representing decimal integers (BigInt safe) – caller responsibility.\nexport interface BlockPreimageInput {\n index: string | number | bigint;\n timestamp: string | number | bigint;\n previousHash: string;\n dataHash: string;\n metadataHash: string;\n signatureAlg: string; // e.g. 'dilithium2'\n ownerPublicKey: string; // Dilithium public key (base64url)\n contentType?: string; // default 'application/json'\n version: number; // block format / protocol version\n}\n\nexport async function buildBlockPreimage(block: BlockPreimageInput): Promise<CanonicalOut> {\n await initWasm();\n // Normalize fields per spec\n const normalized = {\n contentType: block.contentType || 'application/json',\n dataHash: block.dataHash,\n index: block.index.toString(),\n metadataHash: block.metadataHash,\n ownerPublicKey: block.ownerPublicKey,\n previousHash: block.previousHash,\n signatureAlg: block.signatureAlg,\n timestamp: block.timestamp.toString(),\n version: block.version,\n };\n // Use JCS canonicalization via wasm jcs_canonicalize (already exposed through jcsCanonicalize helper)\n const canonical = await jcsCanonicalize(normalized);\n const msg_b64u = b64uEncode(new TextEncoder().encode(canonical));\n return { canonical, msg_b64u, msgB64u: msg_b64u };\n}\n\nexport async function validateRoyalty(receiver: string, bps: number): Promise<boolean> {\n await initWasm();\n const raw = (wasmPkg as any).validate_royalty(receiver, bps);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) return false;\n return !!out.ok;\n}\n\nexport async function verifyAttestations(msgB64u: string, attestations: Array<{ alg: string; publicKeyB64u: string; signatureB64u: string }>, allowedPublicKeys?: string[]): Promise<number> {\n await initWasm();\n const raw = (wasmPkg as any).verify_attestations(msgB64u, JSON.stringify(attestations), allowedPublicKeys ? JSON.stringify(allowedPublicKeys) : undefined);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return Number(out.valid_count || 0);\n}\n\n// Utility functions\n// Cross-env base64url helpers (browser + Node)\nfunction _fromByteArray(bytes: Uint8Array): string {\n if (typeof btoa === 'function') {\n // Browser\n let s = '';\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return btoa(s);\n }\n // Node\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction _toByteArray(b64: string): Uint8Array {\n if (typeof atob === 'function') {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n }\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n\nexport function b64uEncode(data: Uint8Array): string {\n return _fromByteArray(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+/g, '');\n}\n\nexport function b64uDecode(str: string): Uint8Array {\n const b64 = str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '=');\n return _toByteArray(b64);\n}\n\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n// ============================================================================\n// THRESHOLD SIGNATURES & GOVERNANCE\n// ============================================================================\n\nexport interface GovernancePolicy {\n policyId: string;\n version: number;\n chainId: string;\n threshold: number;\n signers: Array<{\n publicKeyB64u: string;\n keyId: string;\n weight: number;\n role: 'owner' | 'guardian' | 'delegate' | 'recovery';\n }>;\n operations: Array<{\n action: string;\n requiredThreshold?: number;\n requiredRoles?: string[];\n maxValue?: string;\n timelock?: number;\n }>;\n validFrom: number;\n validUntil: number;\n createdAt: number;\n createdBy: string;\n policySignature: string;\n}\n\nexport interface Attestation {\n signerKeyId: string;\n signerPublicKeyB64u: string;\n operationHash: string;\n operationType: string;\n attestedAt: number;\n expiresAt: number;\n signatureAlg: 'dilithium2';\n signatureB64u: string;\n}\n\nexport interface AggregatedSignature {\n policyId: string;\n policyVersion: number;\n operationHash: string;\n attestations: Attestation[];\n totalWeight: number;\n thresholdMet: boolean;\n verifiedAt: number;\n}\n\n/**\n * Create an attestation for a threshold signature operation.\n */\nexport async function createAttestation(\n operation: { type: string; payload: unknown },\n signerKeys: { keyId: string; publicKeyB64u: string; secretKeyB64u: string },\n expiresInSeconds: number = 3600\n): Promise<Attestation> {\n await initWasm();\n \n // Build deterministic preimage for the operation\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const operationHash = await sha256B64u(preimageBytes);\n const msgB64u = b64uEncode(preimageBytes);\n \n // Sign the preimage\n const sig = await dilithiumSign(msgB64u, signerKeys.secretKeyB64u);\n \n return {\n signerKeyId: signerKeys.keyId,\n signerPublicKeyB64u: signerKeys.publicKeyB64u,\n operationHash,\n operationType: operation.type,\n attestedAt: Date.now(),\n expiresAt: Date.now() + expiresInSeconds * 1000,\n signatureAlg: 'dilithium2',\n signatureB64u: sig.signature_b64u\n };\n}\n\n/**\n * Verify an attestation signature.\n */\nexport async function verifyAttestation(\n attestation: Attestation,\n operation: { type: string; payload: unknown }\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Rebuild expected operation hash\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const expectedHash = await sha256B64u(preimageBytes);\n \n if (attestation.operationHash !== expectedHash) {\n return { valid: false, error: 'Operation hash mismatch' };\n }\n \n // Check expiry\n if (attestation.expiresAt < Date.now()) {\n return { valid: false, error: 'Attestation expired' };\n }\n \n // Verify signature\n const msgB64u = b64uEncode(preimageBytes);\n const result = await dilithiumVerify(msgB64u, attestation.signatureB64u, attestation.signerPublicKeyB64u);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that an aggregated signature meets the threshold policy.\n */\nexport async function verifyThreshold(\n aggregated: AggregatedSignature,\n operation: { type: string; payload: unknown },\n policy: GovernancePolicy\n): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n \n // Check policy match\n if (aggregated.policyId !== policy.policyId) {\n errors.push('Policy ID mismatch');\n }\n \n // Verify each attestation and compute weight\n let validWeight = 0;\n for (const attestation of aggregated.attestations) {\n const signer = policy.signers.find(s => s.publicKeyB64u === attestation.signerPublicKeyB64u);\n if (!signer) {\n errors.push(`Signer ${attestation.signerKeyId} not in policy`);\n continue;\n }\n \n const result = await verifyAttestation(attestation, operation);\n if (!result.valid) {\n errors.push(`Attestation from ${attestation.signerKeyId}: ${result.error}`);\n continue;\n }\n \n validWeight += signer.weight;\n }\n \n // Check threshold\n if (validWeight < policy.threshold) {\n errors.push(`Threshold not met: weight ${validWeight} < required ${policy.threshold}`);\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n// ============================================================================\n// PRE-REGISTRATION COMMITMENT SCHEME\n// ============================================================================\n\nexport interface ProvenanceCommitment {\n type: 'ProvenanceCommitment';\n version: 1;\n commitmentHash: string;\n creatorPublicKey: string;\n timestamp: number;\n signature: string;\n}\n\nexport interface CommitmentReveal {\n commitmentHash: string;\n salt: string;\n assetHash: string;\n}\n\n/**\n * Create a provenance commitment for an asset before public disclosure.\n * This establishes a timestamped claim without revealing the asset content.\n */\nexport async function createProvenanceCommitment(\n assetBytes: Uint8Array,\n keys: { publicKeyB64u: string; secretKeyB64u: string }\n): Promise<{ commitment: ProvenanceCommitment; reveal: CommitmentReveal }> {\n await initWasm();\n \n // Generate random salt\n const salt = crypto.getRandomValues(new Uint8Array(32));\n \n // Compute commitment hash = SHA256(asset || salt || publicKey)\n const publicKeyBytes = b64uDecode(keys.publicKeyB64u);\n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const commitmentHash = await sha256B64u(preimage);\n const assetHash = await sha256B64u(assetBytes);\n \n // Build commitment object (without signature)\n const commitmentData = {\n type: 'ProvenanceCommitment' as const,\n version: 1 as const,\n commitmentHash,\n creatorPublicKey: keys.publicKeyB64u,\n timestamp: Date.now()\n };\n \n // Sign the commitment\n const canonical = await jcsCanonicalize(commitmentData);\n const sig = await dilithiumSign(b64uEncode(new TextEncoder().encode(canonical)), keys.secretKeyB64u);\n \n const commitment: ProvenanceCommitment = {\n ...commitmentData,\n signature: sig.signature_b64u\n };\n \n const reveal: CommitmentReveal = {\n commitmentHash,\n salt: b64uEncode(salt),\n assetHash\n };\n \n return { commitment, reveal };\n}\n\n/**\n * Verify a provenance commitment signature.\n */\nexport async function verifyProvenanceCommitment(\n commitment: ProvenanceCommitment\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Reconstruct the signed data (without signature field)\n const commitmentData = {\n type: commitment.type,\n version: commitment.version,\n commitmentHash: commitment.commitmentHash,\n creatorPublicKey: commitment.creatorPublicKey,\n timestamp: commitment.timestamp\n };\n \n const canonical = await jcsCanonicalize(commitmentData);\n const msgB64u = b64uEncode(new TextEncoder().encode(canonical));\n \n const result = await dilithiumVerify(msgB64u, commitment.signature, commitment.creatorPublicKey);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid commitment signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that a revealed asset matches a commitment.\n */\nexport async function verifyCommitmentReveal(\n commitment: ProvenanceCommitment,\n assetBytes: Uint8Array,\n reveal: CommitmentReveal\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // First verify the commitment signature\n const sigResult = await verifyProvenanceCommitment(commitment);\n if (!sigResult.valid) {\n return { valid: false, error: `Commitment signature invalid: ${sigResult.error}` };\n }\n \n // Verify asset hash matches\n const computedAssetHash = await sha256B64u(assetBytes);\n if (computedAssetHash !== reveal.assetHash) {\n return { valid: false, error: 'Asset hash does not match reveal' };\n }\n \n // Reconstruct commitment hash\n const salt = b64uDecode(reveal.salt);\n const publicKeyBytes = b64uDecode(commitment.creatorPublicKey);\n \n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const computedCommitmentHash = await sha256B64u(preimage);\n \n if (computedCommitmentHash !== commitment.commitmentHash) {\n return { valid: false, error: 'Commitment hash does not match reveal' };\n }\n \n return { valid: true };\n}\n\n// ============================================================================\n// HELPER: SHA-256 with base64url output\n// ============================================================================\n\nasync function sha256B64u(data: Uint8Array): Promise<string> {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data as unknown as BufferSource);\n return b64uEncode(new Uint8Array(hashBuffer));\n}\n\n// ============================================================================\n// ALGORITHMIC OPTIMIZATIONS (arXiv:2501.02305, arXiv:2504.17033)\n// ============================================================================\n// High-performance data structures for verification operations\n\n// WASM bindings for algorithm functions\nconst wasm_create_nonce_cache = (wasmPkg as any).create_nonce_cache as (capacity: number, ttl_ms: number) => string;\nconst wasm_nonce_cache_info = (wasmPkg as any).nonce_cache_info as () => string;\nconst wasm_sssp_config = (wasmPkg as any).sssp_config as (nodes: number) => string;\nconst wasm_provenance_path_config = (wasmPkg as any).provenance_path_config as (chain_length: number, branches: number) => string;\nconst wasm_elastic_hash_config = (wasmPkg as any).elastic_hash_config as (capacity: number, load_factor: number) => string;\n\n/**\n * Nonce Cache Configuration\n * Uses Elastic Hashing (arXiv:2501.02305) for O(1) amortized lookup\n */\nexport interface NonceCacheConfig {\n type: string;\n capacity: number;\n ttl_ms: number;\n algorithm: string;\n complexity: string;\n}\n\n/**\n * Create a nonce cache configuration for replay attack prevention.\n * Based on Elastic Hashing - O(1) amortized, O(log(1/δ)) worst-case.\n * \n * @param capacity - Maximum number of nonces to track\n * @param ttlMs - Time-to-live in milliseconds before nonces expire\n */\nexport async function createNonceCacheConfig(capacity: number, ttlMs: number): Promise<NonceCacheConfig> {\n await initWasm();\n return JSON.parse(wasm_create_nonce_cache(capacity, ttlMs));\n}\n\n/**\n * Get information about the nonce cache algorithm.\n */\nexport async function getNonceCacheInfo(): Promise<{\n name: string;\n paper: string;\n probe_complexity: string;\n load_factor: number;\n features: string[];\n}> {\n await initWasm();\n return JSON.parse(wasm_nonce_cache_info());\n}\n\n/**\n * SSSP (Single-Source Shortest Path) Configuration\n * Uses Frontier-Reduced algorithm (arXiv:2504.17033)\n */\nexport interface SSSPConfig {\n name: string;\n paper: string;\n complexity: string;\n nodes: number;\n pivots_k: number;\n batch_t: number;\n use_cases: string[];\n}\n\n/**\n * Get optimal SSSP configuration for graph verification.\n * Uses Frontier-Reduced SSSP - O(m × log^(2/3)(n)) complexity.\n * \n * @param nodes - Expected number of nodes in the graph\n */\nexport async function getSSSPConfig(nodes: number): Promise<SSSPConfig> {\n await initWasm();\n return JSON.parse(wasm_sssp_config(nodes));\n}\n\n/**\n * Provenance Path Configuration\n * Optimized parameters for chain of custody verification\n */\nexport interface ProvenancePathConfig {\n algorithm: string;\n chain_length: number;\n branches: number;\n estimated_nodes: number;\n estimated_edges: number;\n pivots_k: number;\n batch_t: number;\n complexity: string;\n verification_mode: string;\n}\n\n/**\n * Get optimized configuration for provenance chain verification.\n * \n * @param chainLength - Number of blocks in the provenance chain\n * @param branches - Average number of branches per block\n */\nexport async function getProvenancePathConfig(chainLength: number, branches: number): Promise<ProvenancePathConfig> {\n await initWasm();\n return JSON.parse(wasm_provenance_path_config(chainLength, branches));\n}\n\n/**\n * Elastic Hash Configuration\n * High-performance hash table for key caching\n */\nexport interface ElasticHashConfig {\n algorithm: string;\n paper: string;\n capacity: number;\n load_factor: number;\n levels: number;\n probe_complexity: {\n amortized: string;\n worst_case: string;\n };\n use_cases: string[];\n}\n\n/**\n * Get elastic hash table configuration for key caching.\n * Optimal for PQC public key caching with O(1) amortized lookups.\n * \n * @param capacity - Maximum number of entries\n * @param loadFactor - Target load factor (0.0 to 1.0, recommend 0.95)\n */\nexport async function getElasticHashConfig(capacity: number, loadFactor: number = 0.95): Promise<ElasticHashConfig> {\n await initWasm();\n return JSON.parse(wasm_elastic_hash_config(capacity, loadFactor));\n}\n"],"names":[],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;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,KAAK,CAAC,CAAC;AAC7D;AAEA;;AAEG;AACI,eAAe,iBAAiB,GAAA;IAOrC,MAAM,QAAQ,EAAE;AAChB,IAAA,OAAO,IAAI,CAAC,KAAK,CAAC,qBAAqB,EAAE,CAAC;AAC5C;AAgBA;;;;;AAKG;AACI,eAAe,aAAa,CAAC,KAAa,EAAA;IAC/C,MAAM,QAAQ,EAAE;IAChB,OAAO,IAAI,CAAC,KAAK,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;AAC5C;AAkBA;;;;;AAKG;AACI,eAAe,uBAAuB,CAAC,WAAmB,EAAE,QAAgB,EAAA;IACjF,MAAM,QAAQ,EAAE;IAChB,OAAO,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;AACvE;AAmBA;;;;;;AAMG;AACI,eAAe,oBAAoB,CAAC,QAAgB,EAAE,aAAqB,IAAI,EAAA;IACpF,MAAM,QAAQ,EAAE;IAChB,OAAO,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;AACnE;;;;"}
@@ -206,4 +206,99 @@ export declare function verifyCommitmentReveal(commitment: ProvenanceCommitment,
206
206
  valid: boolean;
207
207
  error?: string;
208
208
  }>;
209
+ /**
210
+ * Nonce Cache Configuration
211
+ * Uses Elastic Hashing (arXiv:2501.02305) for O(1) amortized lookup
212
+ */
213
+ export interface NonceCacheConfig {
214
+ type: string;
215
+ capacity: number;
216
+ ttl_ms: number;
217
+ algorithm: string;
218
+ complexity: string;
219
+ }
220
+ /**
221
+ * Create a nonce cache configuration for replay attack prevention.
222
+ * Based on Elastic Hashing - O(1) amortized, O(log(1/δ)) worst-case.
223
+ *
224
+ * @param capacity - Maximum number of nonces to track
225
+ * @param ttlMs - Time-to-live in milliseconds before nonces expire
226
+ */
227
+ export declare function createNonceCacheConfig(capacity: number, ttlMs: number): Promise<NonceCacheConfig>;
228
+ /**
229
+ * Get information about the nonce cache algorithm.
230
+ */
231
+ export declare function getNonceCacheInfo(): Promise<{
232
+ name: string;
233
+ paper: string;
234
+ probe_complexity: string;
235
+ load_factor: number;
236
+ features: string[];
237
+ }>;
238
+ /**
239
+ * SSSP (Single-Source Shortest Path) Configuration
240
+ * Uses Frontier-Reduced algorithm (arXiv:2504.17033)
241
+ */
242
+ export interface SSSPConfig {
243
+ name: string;
244
+ paper: string;
245
+ complexity: string;
246
+ nodes: number;
247
+ pivots_k: number;
248
+ batch_t: number;
249
+ use_cases: string[];
250
+ }
251
+ /**
252
+ * Get optimal SSSP configuration for graph verification.
253
+ * Uses Frontier-Reduced SSSP - O(m × log^(2/3)(n)) complexity.
254
+ *
255
+ * @param nodes - Expected number of nodes in the graph
256
+ */
257
+ export declare function getSSSPConfig(nodes: number): Promise<SSSPConfig>;
258
+ /**
259
+ * Provenance Path Configuration
260
+ * Optimized parameters for chain of custody verification
261
+ */
262
+ export interface ProvenancePathConfig {
263
+ algorithm: string;
264
+ chain_length: number;
265
+ branches: number;
266
+ estimated_nodes: number;
267
+ estimated_edges: number;
268
+ pivots_k: number;
269
+ batch_t: number;
270
+ complexity: string;
271
+ verification_mode: string;
272
+ }
273
+ /**
274
+ * Get optimized configuration for provenance chain verification.
275
+ *
276
+ * @param chainLength - Number of blocks in the provenance chain
277
+ * @param branches - Average number of branches per block
278
+ */
279
+ export declare function getProvenancePathConfig(chainLength: number, branches: number): Promise<ProvenancePathConfig>;
280
+ /**
281
+ * Elastic Hash Configuration
282
+ * High-performance hash table for key caching
283
+ */
284
+ export interface ElasticHashConfig {
285
+ algorithm: string;
286
+ paper: string;
287
+ capacity: number;
288
+ load_factor: number;
289
+ levels: number;
290
+ probe_complexity: {
291
+ amortized: string;
292
+ worst_case: string;
293
+ };
294
+ use_cases: string[];
295
+ }
296
+ /**
297
+ * Get elastic hash table configuration for key caching.
298
+ * Optimal for PQC public key caching with O(1) amortized lookups.
299
+ *
300
+ * @param capacity - Maximum number of entries
301
+ * @param loadFactor - Target load factor (0.0 to 1.0, recommend 0.95)
302
+ */
303
+ export declare function getElasticHashConfig(capacity: number, loadFactor?: number): Promise<ElasticHashConfig>;
209
304
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAmBA,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,mBAAmB;IAClC,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAeD,MAAM,WAAW,YAAY;IAAG,SAAS,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE;AAKxF;;;;GAIG;AACH,wBAAsB,QAAQ,CAAC,SAAS,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAa7D;AAGD,wBAAsB,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,CAKzD;AAED,wBAAsB,WAAW,CAAC,UAAU,E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CAGlH;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE;QAChB,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;IACF,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,GAAE,MAAa,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAGlH"}
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@maatara/core-pqc",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Ma'atara Post-Quantum Cryptography Toolkit for Browser and Node.js",
5
5
  "type": "module",
6
- "main": "dist/index.js",
6
+ "main": "dist/index.cjs",
7
7
  "module": "dist/index.mjs",
8
8
  "types": "dist/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.mjs",
13
- "require": "./dist/index.js"
13
+ "require": "./dist/index.cjs"
14
14
  }
15
15
  },
16
16
  "files": [
@@ -35,14 +35,14 @@
35
35
  "author": "Ma'atara",
36
36
  "license": "Apache-2.0",
37
37
  "devDependencies": {
38
- "@rollup/plugin-node-resolve": "^15.0.0",
39
- "@rollup/plugin-typescript": "^11.0.0",
38
+ "@rollup/plugin-node-resolve": "^16.0.0",
39
+ "@rollup/plugin-typescript": "^12.0.0",
40
40
  "@types/jest": "^29.0.0",
41
- "ts-jest": "^29.1.1",
41
+ "ts-jest": "^29.4.6",
42
42
  "jest": "^29.0.0",
43
- "rollup": "^3.0.0",
43
+ "rollup": "^4.30.0",
44
44
  "tslib": "^2.0.0",
45
- "typescript": "^5.0.0"
45
+ "typescript": "^5.9.3"
46
46
  },
47
47
  "dependencies": {
48
48
  "@maatara/core-pqc-wasm": "^0.3.0"
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["// Ma'atara Core PQC Toolkit\n// Post-Quantum Cryptography for Browser and Node.js\n// \n// SECURITY NOTICE: This library implements FIPS 204 (ML-DSA) and FIPS 203 (ML-KEM)\n// post-quantum cryptographic algorithms. Key material should be:\n// 1. Stored securely (encrypted at rest)\n// 2. Transmitted only over secure channels\n// 3. Zeroized after use when possible\n// 4. Protected by hardware security modules for high-value operations\n//\n// See docs/WASM_SECURITY_MODEL.md for browser-specific security considerations.\n\n// ============================================================================\n// SECURITY CONSTANTS\n// ============================================================================\nconst MAX_MESSAGE_SIZE = 16 * 1024 * 1024; // 16MB - prevent memory exhaustion\nconst MAX_KEY_SIZE = 1024 * 1024; // 1MB - reasonable for PQC keys\nconst MAX_ATTESTATION_COUNT = 100; // Prevent DoS from large attestation arrays\n\nexport interface KyberKeypair {\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface KyberEncap {\n kem_ct_b64u: string;\n shared_b64u: string;\n}\n\nexport interface AesGcmWrap {\n iv_b64u: string;\n ct_b64u: string;\n}\n\nexport interface DilithiumKeypair {\n algorithm: string;\n public_b64u: string;\n secret_b64u: string;\n}\n\nexport interface DilithiumSignResult {\n signature_b64u: string;\n algorithm: string;\n}\n\nexport interface DilithiumVerifyResult {\n is_valid: boolean;\n algorithm: string;\n}\n\nexport interface HkdfResult {\n key_b64u: string;\n}\n\nexport interface AesGcmUnwrapResult {\n dek_b64u: string;\n}\n\n// Import WASM functions (namespace import for better bundler compatibility)\nimport * as wasmPkg from '@maatara/core-pqc-wasm';\nconst wasm_kyber_keygen = (wasmPkg as any).kyber_keygen as () => string;\nconst wasm_kyber_encaps = (wasmPkg as any).kyber_encaps as (p: string) => string;\nconst wasm_kyber_decaps = (wasmPkg as any).kyber_decaps as (s: string, c: string) => string;\nconst wasm_hkdf_sha256 = (wasmPkg as any).hkdf_sha256 as (s: string, i: string, salt?: string, len?: number) => string;\nconst wasm_aes_gcm_wrap = (wasmPkg as any).aes_gcm_wrap as (k: string, d: string, a: string) => string;\nconst wasm_aes_gcm_unwrap = (wasmPkg as any).aes_gcm_unwrap as (k: string, iv: string, ct: string, a: string) => string;\nconst wasm_dilithium_keygen = (wasmPkg as any).dilithium_keygen as () => string;\nconst wasm_dilithium_sign = (wasmPkg as any).dilithium_sign as (m: string, s: string) => string;\nconst wasm_dilithium_verify = (wasmPkg as any).dilithium_verify as (m: string, sig: string, p: string) => string;\n\n// Deterministic/canonicalization and governance helpers\nexport interface CanonicalOut { canonical: string; msg_b64u?: string; msgB64u?: string }\n\n// Initialize WASM\nlet wasmReady = false;\n\n/**\n * Initialize the underlying WASM module.\n * - In browsers/bundlers where the glue knows how to fetch the .wasm, you can call without params.\n * - If your bundler provides a URL or Module for the .wasm, pass it as the first argument.\n */\nexport async function initWasm(wasmInput?: any): Promise<void> {\n if (wasmReady) return;\n const maybeInit = (wasmPkg as any).default;\n if (typeof maybeInit === 'function') {\n // Some environments require a URL/Module/bytes for initialization.\n // We forward the optional value if provided; otherwise let the glue resolve it.\n if (wasmInput !== undefined) {\n await maybeInit(wasmInput);\n } else {\n await maybeInit();\n }\n }\n wasmReady = true;\n}\n\n// Kyber functions\nexport async function kyberKeygen(): Promise<KyberKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberEncaps(publicB64u: string): Promise<KyberEncap> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_encaps(publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function kyberDecaps(secretB64u: string, kemCtB64u: string): Promise<{ shared_b64u: string }> {\n await initWasm();\n const result = JSON.parse(wasm_kyber_decaps(secretB64u, kemCtB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// HKDF functions\nexport async function hkdfSha256(\n secretB64u: string,\n infoB64u: string,\n saltB64u?: string,\n len: number = 32\n): Promise<HkdfResult> {\n await initWasm();\n const result = JSON.parse(wasm_hkdf_sha256(secretB64u, infoB64u, saltB64u, len));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// AES-GCM functions\nexport async function aesGcmWrap(\n keyB64u: string,\n dekB64u: string,\n aadB64u: string\n): Promise<AesGcmWrap> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_wrap(keyB64u, dekB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\nexport async function aesGcmUnwrap(\n keyB64u: string,\n ivB64u: string,\n ctB64u: string,\n aadB64u: string\n): Promise<AesGcmUnwrapResult> {\n await initWasm();\n const result = JSON.parse(wasm_aes_gcm_unwrap(keyB64u, ivB64u, ctB64u, aadB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// Dilithium functions\n\n/**\n * Generate a new ML-DSA-65 (Dilithium) keypair.\n * SECURITY: Keys should be stored encrypted at rest.\n * For high-value operations, consider hardware security modules.\n */\nexport async function dilithiumKeygen(): Promise<DilithiumKeypair> {\n await initWasm();\n const result = JSON.parse(wasm_dilithium_keygen());\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Sign a message using ML-DSA-65 (Dilithium).\n * @param messageB64u - Base64url-encoded message to sign\n * @param secretB64u - Base64url-encoded secret key\n * SECURITY: Secret key should be zeroized after use if possible.\n */\nexport async function dilithiumSign(\n messageB64u: string,\n secretB64u: string\n): Promise<DilithiumSignResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (secretB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Secret key exceeds maximum size of ${MAX_KEY_SIZE} bytes`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_sign(messageB64u, secretB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n/**\n * Verify a ML-DSA-65 (Dilithium) signature.\n * @param messageB64u - Base64url-encoded message\n * @param signatureB64u - Base64url-encoded signature\n * @param publicB64u - Base64url-encoded public key\n */\nexport async function dilithiumVerify(\n messageB64u: string,\n signatureB64u: string,\n publicB64u: string\n): Promise<DilithiumVerifyResult> {\n // Input validation - prevent memory exhaustion attacks\n if (messageB64u.length > MAX_MESSAGE_SIZE) {\n throw new Error(`Message exceeds maximum size of ${MAX_MESSAGE_SIZE} bytes`);\n }\n if (signatureB64u.length > MAX_KEY_SIZE || publicB64u.length > MAX_KEY_SIZE) {\n throw new Error(`Signature or public key exceeds maximum size`);\n }\n \n await initWasm();\n const result = JSON.parse(wasm_dilithium_verify(messageB64u, signatureB64u, publicB64u));\n if (result.error) throw new Error(result.error);\n return result;\n}\n\n// ---- Deterministic helpers (multisig/art token) ----\nexport async function jcsCanonicalize(json: unknown): Promise<string> {\n await initWasm();\n const raw = (wasmPkg as any).jcs_canonicalize(JSON.stringify(json));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return out.canonical as string;\n}\n\nexport async function buildPolicyPreimage(policy: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_governance(JSON.stringify(policy));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildMintPreimage(header: unknown, asset: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_mint(JSON.stringify(header), JSON.stringify(asset));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildTransferPreimage(header: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_asset_transfer(JSON.stringify(header));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\nexport async function buildAnchorPreimage(userId: string, rootHex: string, epoch: string, chains: unknown): Promise<CanonicalOut> {\n await initWasm();\n const raw = (wasmPkg as any).preimage_anchor(userId, rootHex, epoch, JSON.stringify(chains));\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return { canonical: out.canonical, msg_b64u: out.msg_b64u, msgB64u: out.msg_b64u };\n}\n\n// ---- Veritas Block Preimage (NEW v2 JCS canonical form) ----\n// We migrate block signing to a canonical (JCS) JSON similar to other preimages.\n// Legacy (v1) blocks used a hand-crafted JSON.stringify of a plain object with fixed insertion order.\n// This helper produces a canonical JSON string and msg_b64u = b64url(UTF-8(canonical JSON)).\n// NOTE: We intentionally EXCLUDE signature, encryptionKeyHash, and any runtime-only fields.\n// Fields included (ordered via JCS lexical ordering):\n// contentType, dataHash, index, metadataHash, ownerPublicKey, previousHash, signatureAlg, timestamp, version\n// index & timestamp MUST be strings representing decimal integers (BigInt safe) – caller responsibility.\nexport interface BlockPreimageInput {\n index: string | number | bigint;\n timestamp: string | number | bigint;\n previousHash: string;\n dataHash: string;\n metadataHash: string;\n signatureAlg: string; // e.g. 'dilithium2'\n ownerPublicKey: string; // Dilithium public key (base64url)\n contentType?: string; // default 'application/json'\n version: number; // block format / protocol version\n}\n\nexport async function buildBlockPreimage(block: BlockPreimageInput): Promise<CanonicalOut> {\n await initWasm();\n // Normalize fields per spec\n const normalized = {\n contentType: block.contentType || 'application/json',\n dataHash: block.dataHash,\n index: block.index.toString(),\n metadataHash: block.metadataHash,\n ownerPublicKey: block.ownerPublicKey,\n previousHash: block.previousHash,\n signatureAlg: block.signatureAlg,\n timestamp: block.timestamp.toString(),\n version: block.version,\n };\n // Use JCS canonicalization via wasm jcs_canonicalize (already exposed through jcsCanonicalize helper)\n const canonical = await jcsCanonicalize(normalized);\n const msg_b64u = b64uEncode(new TextEncoder().encode(canonical));\n return { canonical, msg_b64u, msgB64u: msg_b64u };\n}\n\nexport async function validateRoyalty(receiver: string, bps: number): Promise<boolean> {\n await initWasm();\n const raw = (wasmPkg as any).validate_royalty(receiver, bps);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) return false;\n return !!out.ok;\n}\n\nexport async function verifyAttestations(msgB64u: string, attestations: Array<{ alg: string; publicKeyB64u: string; signatureB64u: string }>, allowedPublicKeys?: string[]): Promise<number> {\n await initWasm();\n const raw = (wasmPkg as any).verify_attestations(msgB64u, JSON.stringify(attestations), allowedPublicKeys ? JSON.stringify(allowedPublicKeys) : undefined);\n const out = typeof raw === 'string' ? JSON.parse(raw) : raw;\n if (out?.error) throw new Error(out.error);\n return Number(out.valid_count || 0);\n}\n\n// Utility functions\n// Cross-env base64url helpers (browser + Node)\nfunction _fromByteArray(bytes: Uint8Array): string {\n if (typeof btoa === 'function') {\n // Browser\n let s = '';\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return btoa(s);\n }\n // Node\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction _toByteArray(b64: string): Uint8Array {\n if (typeof atob === 'function') {\n const binary = atob(b64);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);\n return out;\n }\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n\nexport function b64uEncode(data: Uint8Array): string {\n return _fromByteArray(data)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+/g, '');\n}\n\nexport function b64uDecode(str: string): Uint8Array {\n const b64 = str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '=');\n return _toByteArray(b64);\n}\n\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n// ============================================================================\n// THRESHOLD SIGNATURES & GOVERNANCE\n// ============================================================================\n\nexport interface GovernancePolicy {\n policyId: string;\n version: number;\n chainId: string;\n threshold: number;\n signers: Array<{\n publicKeyB64u: string;\n keyId: string;\n weight: number;\n role: 'owner' | 'guardian' | 'delegate' | 'recovery';\n }>;\n operations: Array<{\n action: string;\n requiredThreshold?: number;\n requiredRoles?: string[];\n maxValue?: string;\n timelock?: number;\n }>;\n validFrom: number;\n validUntil: number;\n createdAt: number;\n createdBy: string;\n policySignature: string;\n}\n\nexport interface Attestation {\n signerKeyId: string;\n signerPublicKeyB64u: string;\n operationHash: string;\n operationType: string;\n attestedAt: number;\n expiresAt: number;\n signatureAlg: 'dilithium2';\n signatureB64u: string;\n}\n\nexport interface AggregatedSignature {\n policyId: string;\n policyVersion: number;\n operationHash: string;\n attestations: Attestation[];\n totalWeight: number;\n thresholdMet: boolean;\n verifiedAt: number;\n}\n\n/**\n * Create an attestation for a threshold signature operation.\n */\nexport async function createAttestation(\n operation: { type: string; payload: unknown },\n signerKeys: { keyId: string; publicKeyB64u: string; secretKeyB64u: string },\n expiresInSeconds: number = 3600\n): Promise<Attestation> {\n await initWasm();\n \n // Build deterministic preimage for the operation\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const operationHash = await sha256B64u(preimageBytes);\n const msgB64u = b64uEncode(preimageBytes);\n \n // Sign the preimage\n const sig = await dilithiumSign(msgB64u, signerKeys.secretKeyB64u);\n \n return {\n signerKeyId: signerKeys.keyId,\n signerPublicKeyB64u: signerKeys.publicKeyB64u,\n operationHash,\n operationType: operation.type,\n attestedAt: Date.now(),\n expiresAt: Date.now() + expiresInSeconds * 1000,\n signatureAlg: 'dilithium2',\n signatureB64u: sig.signature_b64u\n };\n}\n\n/**\n * Verify an attestation signature.\n */\nexport async function verifyAttestation(\n attestation: Attestation,\n operation: { type: string; payload: unknown }\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Rebuild expected operation hash\n const preimage = await jcsCanonicalize({ type: operation.type, payload: operation.payload });\n const preimageBytes = new TextEncoder().encode(preimage);\n const expectedHash = await sha256B64u(preimageBytes);\n \n if (attestation.operationHash !== expectedHash) {\n return { valid: false, error: 'Operation hash mismatch' };\n }\n \n // Check expiry\n if (attestation.expiresAt < Date.now()) {\n return { valid: false, error: 'Attestation expired' };\n }\n \n // Verify signature\n const msgB64u = b64uEncode(preimageBytes);\n const result = await dilithiumVerify(msgB64u, attestation.signatureB64u, attestation.signerPublicKeyB64u);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that an aggregated signature meets the threshold policy.\n */\nexport async function verifyThreshold(\n aggregated: AggregatedSignature,\n operation: { type: string; payload: unknown },\n policy: GovernancePolicy\n): Promise<{ valid: boolean; errors: string[] }> {\n const errors: string[] = [];\n \n // Check policy match\n if (aggregated.policyId !== policy.policyId) {\n errors.push('Policy ID mismatch');\n }\n \n // Verify each attestation and compute weight\n let validWeight = 0;\n for (const attestation of aggregated.attestations) {\n const signer = policy.signers.find(s => s.publicKeyB64u === attestation.signerPublicKeyB64u);\n if (!signer) {\n errors.push(`Signer ${attestation.signerKeyId} not in policy`);\n continue;\n }\n \n const result = await verifyAttestation(attestation, operation);\n if (!result.valid) {\n errors.push(`Attestation from ${attestation.signerKeyId}: ${result.error}`);\n continue;\n }\n \n validWeight += signer.weight;\n }\n \n // Check threshold\n if (validWeight < policy.threshold) {\n errors.push(`Threshold not met: weight ${validWeight} < required ${policy.threshold}`);\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n// ============================================================================\n// PRE-REGISTRATION COMMITMENT SCHEME\n// ============================================================================\n\nexport interface ProvenanceCommitment {\n type: 'ProvenanceCommitment';\n version: 1;\n commitmentHash: string;\n creatorPublicKey: string;\n timestamp: number;\n signature: string;\n}\n\nexport interface CommitmentReveal {\n commitmentHash: string;\n salt: string;\n assetHash: string;\n}\n\n/**\n * Create a provenance commitment for an asset before public disclosure.\n * This establishes a timestamped claim without revealing the asset content.\n */\nexport async function createProvenanceCommitment(\n assetBytes: Uint8Array,\n keys: { publicKeyB64u: string; secretKeyB64u: string }\n): Promise<{ commitment: ProvenanceCommitment; reveal: CommitmentReveal }> {\n await initWasm();\n \n // Generate random salt\n const salt = crypto.getRandomValues(new Uint8Array(32));\n \n // Compute commitment hash = SHA256(asset || salt || publicKey)\n const publicKeyBytes = b64uDecode(keys.publicKeyB64u);\n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const commitmentHash = await sha256B64u(preimage);\n const assetHash = await sha256B64u(assetBytes);\n \n // Build commitment object (without signature)\n const commitmentData = {\n type: 'ProvenanceCommitment' as const,\n version: 1 as const,\n commitmentHash,\n creatorPublicKey: keys.publicKeyB64u,\n timestamp: Date.now()\n };\n \n // Sign the commitment\n const canonical = await jcsCanonicalize(commitmentData);\n const sig = await dilithiumSign(b64uEncode(new TextEncoder().encode(canonical)), keys.secretKeyB64u);\n \n const commitment: ProvenanceCommitment = {\n ...commitmentData,\n signature: sig.signature_b64u\n };\n \n const reveal: CommitmentReveal = {\n commitmentHash,\n salt: b64uEncode(salt),\n assetHash\n };\n \n return { commitment, reveal };\n}\n\n/**\n * Verify a provenance commitment signature.\n */\nexport async function verifyProvenanceCommitment(\n commitment: ProvenanceCommitment\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // Reconstruct the signed data (without signature field)\n const commitmentData = {\n type: commitment.type,\n version: commitment.version,\n commitmentHash: commitment.commitmentHash,\n creatorPublicKey: commitment.creatorPublicKey,\n timestamp: commitment.timestamp\n };\n \n const canonical = await jcsCanonicalize(commitmentData);\n const msgB64u = b64uEncode(new TextEncoder().encode(canonical));\n \n const result = await dilithiumVerify(msgB64u, commitment.signature, commitment.creatorPublicKey);\n \n if (!result.is_valid) {\n return { valid: false, error: 'Invalid commitment signature' };\n }\n \n return { valid: true };\n}\n\n/**\n * Verify that a revealed asset matches a commitment.\n */\nexport async function verifyCommitmentReveal(\n commitment: ProvenanceCommitment,\n assetBytes: Uint8Array,\n reveal: CommitmentReveal\n): Promise<{ valid: boolean; error?: string }> {\n await initWasm();\n \n // First verify the commitment signature\n const sigResult = await verifyProvenanceCommitment(commitment);\n if (!sigResult.valid) {\n return { valid: false, error: `Commitment signature invalid: ${sigResult.error}` };\n }\n \n // Verify asset hash matches\n const computedAssetHash = await sha256B64u(assetBytes);\n if (computedAssetHash !== reveal.assetHash) {\n return { valid: false, error: 'Asset hash does not match reveal' };\n }\n \n // Reconstruct commitment hash\n const salt = b64uDecode(reveal.salt);\n const publicKeyBytes = b64uDecode(commitment.creatorPublicKey);\n \n const preimage = new Uint8Array(assetBytes.length + salt.length + publicKeyBytes.length);\n preimage.set(assetBytes, 0);\n preimage.set(salt, assetBytes.length);\n preimage.set(publicKeyBytes, assetBytes.length + salt.length);\n \n const computedCommitmentHash = await sha256B64u(preimage);\n \n if (computedCommitmentHash !== commitment.commitmentHash) {\n return { valid: false, error: 'Commitment hash does not match reveal' };\n }\n \n return { valid: true };\n}\n\n// ============================================================================\n// HELPER: SHA-256 with base64url output\n// ============================================================================\n\nasync function sha256B64u(data: Uint8Array): Promise<string> {\n const hashBuffer = await crypto.subtle.digest('SHA-256', data as unknown as BufferSource);\n return b64uEncode(new Uint8Array(hashBuffer));\n}\n\n"],"names":["wasmPkg"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC1C,MAAM,YAA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