@ocap/tx-pipeline 1.30.25 → 1.31.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.
Files changed (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +43 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +53 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +34 -0
  32. package/esm/pipes/pre-flight-waf.mjs +603 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +43 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +52 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +616 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +34 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,458 @@
1
+ import { assertNotOfacSanctioned, normalizeScreeningAddress } from "./ofac-screening.mjs";
2
+ import { Signer } from "@ocap/mcrypto";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "node:crypto";
5
+ import elliptic from "elliptic";
6
+
7
+ //#region src/encrypted-nft-envelope.ts
8
+ const secp256k1Curve = new elliptic.ec("secp256k1");
9
+ const SECP256K1_ORDER = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
10
+ const RawCustomError = CustomError;
11
+ function createEncryptedNftError(code, message) {
12
+ return new RawCustomError(code, `${code}: ${message}`);
13
+ }
14
+ const ENCRYPTED_NFT_SCHEMA_VERSION = "ocap.nft.encrypted.v1";
15
+ const MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS = 8192;
16
+ const MAX_ENCRYPTED_NFT_TAGS = 16;
17
+ const MAX_ENCRYPTED_NFT_TAG_LENGTH = 64;
18
+ const MAX_ENCRYPTED_NFT_CATEGORY_LENGTH = 64;
19
+ const MAX_ENCRYPTED_NFT_SUMMARY_LENGTH = 512;
20
+ const MAX_ENCRYPTED_NFT_URI_LENGTH = 512;
21
+ const VALID_ENCRYPTED_NFT_ALGORITHMS = new Set([
22
+ "X25519-XSalsa20-Poly1305",
23
+ "ECIES-Secp256k1-AES256GCM",
24
+ "OCAP-ECDH-HKDF-SHA256"
25
+ ]);
26
+ const HEX_64_REGEX = /^[0-9a-f]{64}$/i;
27
+ const HEX_24_REGEX = /^[0-9a-f]{24}$/i;
28
+ const HEX_32_REGEX = /^[0-9a-f]{32}$/i;
29
+ const HEX_EVEN_REGEX = /^(?:[0-9a-f]{2})+$/i;
30
+ const FORBIDDEN_CONTROL_CHAR_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
31
+ const DANGEROUS_URI_REGEX = /^\s*(?:(?:javascript|vbscript|file|blob)\s*:|data\s*:\s*(?:text\/html|application\/javascript|application\/x-javascript|text\/javascript))/i;
32
+ const FORBIDDEN_OBJECT_KEYS = new Set([
33
+ "__proto__",
34
+ "constructor",
35
+ "prototype"
36
+ ]);
37
+ function assertNoPrototypePollution(value, path = "root", depth = 0) {
38
+ if (depth > 8) throw createEncryptedNftError("ENCRYPTED_NFT_DEPTH_EXCEEDED", `Nesting depth at ${path} exceeds limit 8`);
39
+ if (!value || typeof value !== "object") return;
40
+ if (Array.isArray(value)) {
41
+ for (let i = 0; i < value.length; i++) assertNoPrototypePollution(value[i], `${path}[${i}]`, depth + 1);
42
+ return;
43
+ }
44
+ const proto = Object.getPrototypeOf(value);
45
+ if (proto !== null && proto !== Object.prototype) throw createEncryptedNftError("ENCRYPTED_NFT_FORBIDDEN_PROTOTYPE", `Invalid object prototype at ${path}`);
46
+ for (const key of Object.keys(value)) {
47
+ if (FORBIDDEN_OBJECT_KEYS.has(key)) throw createEncryptedNftError("ENCRYPTED_NFT_FORBIDDEN_KEY", `Forbidden object key "${key}" at ${path}`);
48
+ assertNoPrototypePollution(value[key], `${path}.${key}`, depth + 1);
49
+ }
50
+ }
51
+ function canonicalizeJsonValue(value) {
52
+ if (value === null || value === void 0 || typeof value !== "object") return value;
53
+ if (Array.isArray(value)) return value.map((item) => canonicalizeJsonValue(item));
54
+ const record = value;
55
+ const sortedKeys = Object.keys(record).sort();
56
+ const out = {};
57
+ for (const k of sortedKeys) if (record[k] !== void 0) out[k] = canonicalizeJsonValue(record[k]);
58
+ return out;
59
+ }
60
+ function canonicalizeEncryptedNftMetadata(metadata) {
61
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata must be a non-null object");
62
+ assertNoPrototypePollution(metadata, "privateMetadata");
63
+ if (typeof metadata.title !== "string" || !metadata.title.trim() || metadata.title.length > 256) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.title must be a non-empty string <= 256 chars");
64
+ if (FORBIDDEN_CONTROL_CHAR_REGEX.test(metadata.title)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.title contains control chars");
65
+ if (metadata.description !== void 0) {
66
+ if (typeof metadata.description !== "string" || metadata.description.length > 2048) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.description must be a string <= 2048 chars");
67
+ if (FORBIDDEN_CONTROL_CHAR_REGEX.test(metadata.description)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.description contains control chars");
68
+ }
69
+ if (metadata.arcSpaceAccessCredential !== void 0) {
70
+ if (typeof metadata.arcSpaceAccessCredential !== "string" || !metadata.arcSpaceAccessCredential.trim() || metadata.arcSpaceAccessCredential.length > 512 || FORBIDDEN_CONTROL_CHAR_REGEX.test(metadata.arcSpaceAccessCredential)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.arcSpaceAccessCredential must be a valid non-empty string <= 512 chars");
71
+ }
72
+ if (metadata.arcSpaceDeliverablePath !== void 0) {
73
+ if (typeof metadata.arcSpaceDeliverablePath !== "string" || !metadata.arcSpaceDeliverablePath.trim() || metadata.arcSpaceDeliverablePath.length > 512 || FORBIDDEN_CONTROL_CHAR_REGEX.test(metadata.arcSpaceDeliverablePath) || DANGEROUS_URI_REGEX.test(metadata.arcSpaceDeliverablePath)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "privateMetadata.arcSpaceDeliverablePath is invalid or uses a forbidden URI scheme");
74
+ }
75
+ return JSON.stringify(canonicalizeJsonValue(metadata));
76
+ }
77
+ function normalizeHex32Bytes(rawHex, fieldName) {
78
+ if (typeof rawHex !== "string") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", `${fieldName} must be a 64-character hex string`);
79
+ const stripped = rawHex.trim().replace(/^0x/i, "").toLowerCase();
80
+ if (!HEX_64_REGEX.test(stripped) || /^0+$/.test(stripped)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", `${fieldName} must be a non-zero 32-byte (64-hex) string`);
81
+ return stripped;
82
+ }
83
+ const SECP256K1_COMPRESSED_PK_HEX_REGEX = /^(?:02|03)[0-9a-f]{64}$/i;
84
+ function normalizeSecp256k1PublicKeyHex(rawHex, fieldName) {
85
+ if (typeof rawHex !== "string") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", `${fieldName} must be a 66-character compressed secp256k1 public key hex string`);
86
+ const stripped = rawHex.trim().replace(/^0x/i, "").toLowerCase();
87
+ if (!SECP256K1_COMPRESSED_PK_HEX_REGEX.test(stripped)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", `${fieldName} must be a valid 33-byte (66-hex) compressed secp256k1 public key`);
88
+ return stripped;
89
+ }
90
+ /**
91
+ * Deterministic Owner Public Key derivation from a 32-byte hex secret key for `ocap.nft.encrypted.v1` envelopes.
92
+ * Uses `elliptic` `secp256k1` to derive the compressed 33-byte (66-hex) secp256k1 public key.
93
+ */
94
+ function deriveOwnerPublicKeyHexFromSecretKey(secretKeyHex) {
95
+ const normalizedSk = normalizeHex32Bytes(secretKeyHex, "secretKeyHex");
96
+ const scalar = BigInt(`0x${normalizedSk}`);
97
+ if (scalar <= 0n || scalar >= SECP256K1_ORDER) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", "secretKeyHex is out of range for secp256k1 scalar");
98
+ try {
99
+ return secp256k1Curve.keyFromPrivate(normalizedSk, "hex").getPublic(true, "hex").toLowerCase();
100
+ } catch {
101
+ throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", "secretKeyHex is out of range for secp256k1 scalar");
102
+ }
103
+ }
104
+ function computeSecp256k1EcdhSharedSecret(privateKeyHex, peerPublicKeyHex, fieldName) {
105
+ const normalizedSk = normalizeHex32Bytes(privateKeyHex, "privateKeyHex");
106
+ const scalar = BigInt(`0x${normalizedSk}`);
107
+ if (scalar <= 0n || scalar >= SECP256K1_ORDER) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", "privateKeyHex is out of range for secp256k1 scalar");
108
+ const normalizedPeerPk = normalizeSecp256k1PublicKeyHex(peerPublicKeyHex, fieldName);
109
+ try {
110
+ const privKey = secp256k1Curve.keyFromPrivate(normalizedSk, "hex");
111
+ const peerKey = secp256k1Curve.keyFromPublic(normalizedPeerPk, "hex");
112
+ const validation = peerKey.validate();
113
+ if (!validation || !validation.result) throw new Error("Invalid curve point");
114
+ const sharedBn = privKey.derive(peerKey.getPublic());
115
+ const secret = Buffer.from(sharedBn.toArrayLike(Buffer, "be", 32));
116
+ if (secret.byteLength !== 32 || secret.every((b) => b === 0)) throw new Error("Zero ECDH shared secret");
117
+ return secret;
118
+ } catch {
119
+ throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_KEY", `${fieldName} is not a valid secp256k1 curve point for ECDH key agreement`);
120
+ }
121
+ }
122
+ function computeEncryptedNftPlaintextHash(metadata) {
123
+ const canonicalJson = typeof metadata === "string" ? metadata : canonicalizeEncryptedNftMetadata(metadata);
124
+ return createHash("sha256").update(`OCAP_ENCRYPTED_NFT_PLAINTEXT_V1:${canonicalJson}`, "utf8").digest("hex");
125
+ }
126
+ function computeEncryptedNftCekCommitmentHash(cekHex) {
127
+ const normalizedCek = normalizeHex32Bytes(cekHex, "cekHex");
128
+ return createHash("sha256").update(`OCAP_ENCRYPTED_NFT_CEK_V1:${normalizedCek}`, "utf8").digest("hex");
129
+ }
130
+ function computeEncryptedNftPublicHeaderAad(header) {
131
+ const canonicalHeader = JSON.stringify({
132
+ schemaVersion: header.schemaVersion,
133
+ category: header.category,
134
+ tags: header.tags,
135
+ publicSummary: header.publicSummary,
136
+ plaintextHash: header.plaintextHash.toLowerCase(),
137
+ cekCommitmentHash: header.cekCommitmentHash.toLowerCase(),
138
+ cekPublicKeyHex: header.cekPublicKeyHex.toLowerCase(),
139
+ arcSpaceUri: header.arcSpaceUri || ""
140
+ });
141
+ return Buffer.from(`OCAP_ENCRYPTED_NFT_AAD_V1:${canonicalHeader}`, "utf8");
142
+ }
143
+ function computeKeyWrapStreamAndTag(params) {
144
+ const recipientPk = normalizeSecp256k1PublicKeyHex(params.recipientPkHex, "recipientPkHex");
145
+ const ephemeralPk = normalizeSecp256k1PublicKeyHex(params.ephemeralPkHex, "ephemeralPkHex");
146
+ const normalizedCekHex = normalizeHex32Bytes(params.cekHex, "cekHex");
147
+ const cekBytes = Buffer.from(normalizedCekHex, "hex");
148
+ const cekPk = normalizeSecp256k1PublicKeyHex(params.cekPublicKeyHex, "cekPublicKeyHex");
149
+ const wrapKey = createHmac("sha256", computeSecp256k1EcdhSharedSecret(params.ephemeralSkHex, recipientPk, "recipientPkHex")).update(`OCAP_ENCRYPTED_NFT_KW_STREAM_V1:${recipientPk}:${ephemeralPk}:${params.ownerDid}:${params.nonceHex}`, "utf8").digest();
150
+ const encryptedBytes = Buffer.alloc(32);
151
+ for (let i = 0; i < 32; i++) encryptedBytes[i] = cekBytes[i] ^ wrapKey[i];
152
+ const encryptedCek = encryptedBytes.toString("hex");
153
+ const cekWrapTag = createHmac("sha256", wrapKey).update(`OCAP_ENCRYPTED_NFT_KW_TAG_V1:${params.ownerDid}:${recipientPk}:${ephemeralPk}:${params.nonceHex}:${encryptedCek}:${params.cekCommitmentHash.toLowerCase()}`, "utf8").digest("hex").slice(0, 32);
154
+ const handoverProofHash = createHash("sha256").update(`OCAP_ENCRYPTED_NFT_HANDOVER_PROOF_V1:${params.ownerDid}:${recipientPk}:${ephemeralPk}:${params.nonceHex}:${encryptedCek}:${params.cekCommitmentHash.toLowerCase()}:${cekPk}:${cekWrapTag}:${params.handoverCount}`, "utf8").digest("hex");
155
+ return {
156
+ encryptedCek,
157
+ cekWrapTag,
158
+ handoverProofHash,
159
+ handoverSignature: String(Signer.Secp256k1.sign(Buffer.from(handoverProofHash, "hex"), `0x${normalizedCekHex}`)).replace(/^0x/i, "").toLowerCase()
160
+ };
161
+ }
162
+ function unwrapCekInternal(params) {
163
+ const derivedPk = deriveOwnerPublicKeyHexFromSecretKey(params.ownerSecretKeyHex);
164
+ const recipientPk = normalizeSecp256k1PublicKeyHex(params.envelope.encrypted.recipientPk, "recipientPk");
165
+ if (derivedPk !== recipientPk) throw createEncryptedNftError("ENCRYPTED_NFT_KEY_MISMATCH", `Provided ownerSecretKeyHex does not correspond to envelope recipientPk (${recipientPk})`);
166
+ const ownerDid = normalizeScreeningAddress(params.expectedOwnerDid);
167
+ if (normalizeScreeningAddress(params.envelope.encrypted.ownerDid) !== ownerDid) throw createEncryptedNftError("ENCRYPTED_NFT_OWNER_MISMATCH", `Viewer/caller ${ownerDid} is not the envelope owner (${params.envelope.encrypted.ownerDid})`);
168
+ const ephemeralPk = normalizeSecp256k1PublicKeyHex(params.envelope.encrypted.ephemeralPk, "ephemeralPk");
169
+ const nonceHex = params.envelope.encrypted.nonce.toLowerCase();
170
+ const encryptedCekHex = normalizeHex32Bytes(params.envelope.encrypted.encryptedCek, "encryptedCek");
171
+ const wrapKey = createHmac("sha256", computeSecp256k1EcdhSharedSecret(params.ownerSecretKeyHex, ephemeralPk, "ephemeralPk")).update(`OCAP_ENCRYPTED_NFT_KW_STREAM_V1:${recipientPk}:${ephemeralPk}:${ownerDid}:${nonceHex}`, "utf8").digest();
172
+ if (createHmac("sha256", wrapKey).update(`OCAP_ENCRYPTED_NFT_KW_TAG_V1:${ownerDid}:${recipientPk}:${ephemeralPk}:${nonceHex}:${encryptedCekHex}:${params.envelope.public.cekCommitmentHash.toLowerCase()}`, "utf8").digest("hex").slice(0, 32) !== params.envelope.encrypted.cekWrapTag.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_WRAP_TAG_INVALID", "CEK key-wrap authentication tag verification failed");
173
+ const encryptedBytes = Buffer.from(encryptedCekHex, "hex");
174
+ const cekBytes = Buffer.alloc(32);
175
+ for (let i = 0; i < 32; i++) cekBytes[i] = encryptedBytes[i] ^ wrapKey[i];
176
+ const cekHex = cekBytes.toString("hex");
177
+ const recomputedCekCommitment = computeEncryptedNftCekCommitmentHash(cekHex);
178
+ if (recomputedCekCommitment !== params.envelope.public.cekCommitmentHash.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_CEK_COMMITMENT_MISMATCH", `Unwrapped CEK commitment (${recomputedCekCommitment}) does not match public.cekCommitmentHash (${params.envelope.public.cekCommitmentHash})`);
179
+ const recomputedCekPk = deriveOwnerPublicKeyHexFromSecretKey(cekHex);
180
+ if (recomputedCekPk !== params.envelope.public.cekPublicKeyHex.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_CEK_PK_MISMATCH", `Unwrapped CEK public key (${recomputedCekPk}) does not match public.cekPublicKeyHex (${params.envelope.public.cekPublicKeyHex})`);
181
+ return cekHex;
182
+ }
183
+ function validateEncryptedAssetEnvelope(envelope) {
184
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ENVELOPE", "Envelope must be a non-null object");
185
+ assertNoPrototypePollution(envelope, "envelope");
186
+ const env = envelope;
187
+ if (!env.public || typeof env.public !== "object" || Array.isArray(env.public)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ENVELOPE", "Missing envelope.public header");
188
+ if (!env.encrypted || typeof env.encrypted !== "object" || Array.isArray(env.encrypted)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ENVELOPE", "Missing envelope.encrypted payload");
189
+ const pub = env.public;
190
+ if (pub.schemaVersion !== ENCRYPTED_NFT_SCHEMA_VERSION) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_SCHEMA", `Unsupported schemaVersion "${String(pub.schemaVersion)}"; expected "${ENCRYPTED_NFT_SCHEMA_VERSION}"`);
191
+ if (typeof pub.category !== "string" || !pub.category.trim() || pub.category.length > MAX_ENCRYPTED_NFT_CATEGORY_LENGTH || FORBIDDEN_CONTROL_CHAR_REGEX.test(pub.category)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_CATEGORY", "Invalid public.category");
192
+ if (!Array.isArray(pub.tags) || pub.tags.length > MAX_ENCRYPTED_NFT_TAGS) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_TAGS", `public.tags must be an array of at most ${MAX_ENCRYPTED_NFT_TAGS} tags`);
193
+ for (const tag of pub.tags) if (typeof tag !== "string" || !tag.trim() || tag.length > MAX_ENCRYPTED_NFT_TAG_LENGTH || FORBIDDEN_CONTROL_CHAR_REGEX.test(tag)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_TAGS", `Invalid tag in public.tags: "${String(tag)}"`);
194
+ if (typeof pub.publicSummary !== "string" || !pub.publicSummary.trim() || pub.publicSummary.length > MAX_ENCRYPTED_NFT_SUMMARY_LENGTH || FORBIDDEN_CONTROL_CHAR_REGEX.test(pub.publicSummary) || DANGEROUS_URI_REGEX.test(pub.publicSummary)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_SUMMARY", "Invalid public.publicSummary");
195
+ if (typeof pub.plaintextHash !== "string" || !HEX_64_REGEX.test(pub.plaintextHash)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HASH", "public.plaintextHash must be a 64-hex SHA-256 digest");
196
+ if (typeof pub.cekCommitmentHash !== "string" || !HEX_64_REGEX.test(pub.cekCommitmentHash)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HASH", "public.cekCommitmentHash must be a 64-hex SHA-256 digest");
197
+ const normalizedCekPk = normalizeSecp256k1PublicKeyHex(pub.cekPublicKeyHex, "public.cekPublicKeyHex");
198
+ if (pub.arcSpaceUri !== void 0) {
199
+ if (typeof pub.arcSpaceUri !== "string" || !pub.arcSpaceUri.trim() || pub.arcSpaceUri.length > MAX_ENCRYPTED_NFT_URI_LENGTH || FORBIDDEN_CONTROL_CHAR_REGEX.test(pub.arcSpaceUri) || DANGEROUS_URI_REGEX.test(pub.arcSpaceUri) || !/^(?:arcspace:\/\/|https:\/\/|did:abt:)/i.test(pub.arcSpaceUri)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ARCSPACE_URI", "public.arcSpaceUri must be a valid arcspace://, https://, or did:abt: reference");
200
+ }
201
+ const enc = env.encrypted;
202
+ if (!VALID_ENCRYPTED_NFT_ALGORITHMS.has(enc.alg)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ALG", `Unsupported encryption algorithm "${String(enc.alg)}"`);
203
+ if (typeof enc.ownerDid !== "string" || !enc.ownerDid.trim()) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_OWNER", "encrypted.ownerDid must be a non-empty DID");
204
+ normalizeSecp256k1PublicKeyHex(enc.recipientPk, "encrypted.recipientPk");
205
+ normalizeSecp256k1PublicKeyHex(enc.ephemeralPk, "encrypted.ephemeralPk");
206
+ normalizeHex32Bytes(enc.encryptedCek, "encrypted.encryptedCek");
207
+ if (typeof enc.nonce !== "string" || !HEX_24_REGEX.test(enc.nonce)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_NONCE", "encrypted.nonce must be a 24-hex (12-byte) IV");
208
+ if (typeof enc.cekWrapTag !== "string" || !HEX_32_REGEX.test(enc.cekWrapTag)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_TAG", "encrypted.cekWrapTag must be a 32-hex (16-byte) tag");
209
+ if (typeof enc.ciphertextMetadata !== "string" || !enc.ciphertextMetadata || enc.ciphertextMetadata.length > MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS || !HEX_EVEN_REGEX.test(enc.ciphertextMetadata)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_CIPHERTEXT", `encrypted.ciphertextMetadata must be even-length hex <= ${MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS} chars`);
210
+ if (typeof enc.ciphertextTag !== "string" || !HEX_32_REGEX.test(enc.ciphertextTag)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_TAG", "encrypted.ciphertextTag must be a 32-hex (16-byte) AES-GCM authentication tag");
211
+ if (typeof enc.handoverProofHash !== "string" || !HEX_64_REGEX.test(enc.handoverProofHash)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_PROOF", "encrypted.handoverProofHash must be a 64-hex SHA-256 digest");
212
+ if (typeof enc.handoverSignature !== "string" || !enc.handoverSignature.trim() || !HEX_EVEN_REGEX.test(enc.handoverSignature.replace(/^0x/i, ""))) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_SIG", "encrypted.handoverSignature must be a valid hex-encoded secp256k1 signature");
213
+ if (!Number.isSafeInteger(enc.handoverCount) || enc.handoverCount < 0 || enc.handoverCount > 1e5) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_COUNT", "encrypted.handoverCount must be a non-negative safe integer");
214
+ const normalizedOwnerDid = normalizeScreeningAddress(enc.ownerDid);
215
+ const expectedHandoverProof = createHash("sha256").update(`OCAP_ENCRYPTED_NFT_HANDOVER_PROOF_V1:${normalizedOwnerDid}:${enc.recipientPk.toLowerCase()}:${enc.ephemeralPk.toLowerCase()}:${enc.nonce.toLowerCase()}:${enc.encryptedCek.toLowerCase()}:${pub.cekCommitmentHash.toLowerCase()}:${normalizedCekPk}:${enc.cekWrapTag.toLowerCase()}:${enc.handoverCount}`, "utf8").digest("hex");
216
+ if (expectedHandoverProof !== enc.handoverProofHash.toLowerCase()) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_PROOF", "encrypted.handoverProofHash does not match canonical envelope binding");
217
+ let validHandoverSig = false;
218
+ try {
219
+ const cekKeyObj = secp256k1Curve.keyFromPublic(normalizedCekPk, "hex");
220
+ if (cekKeyObj.validate().result) {
221
+ const uncompressedCekPk = `0x${cekKeyObj.getPublic(false, "hex")}`;
222
+ const cleanSig = enc.handoverSignature.replace(/^0x/i, "").toLowerCase();
223
+ validHandoverSig = Boolean(Signer.Secp256k1.verify(Buffer.from(expectedHandoverProof, "hex"), `0x${cleanSig}`, uncompressedCekPk));
224
+ }
225
+ } catch {
226
+ validHandoverSig = false;
227
+ }
228
+ if (!validHandoverSig) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_SIG", "encrypted.handoverSignature failed secp256k1 verification against public.cekPublicKeyHex");
229
+ return env;
230
+ }
231
+ /**
232
+ * 1. Direct-to-Buyer Encrypted Mint / Primary SKU Purchase (`sealEncryptedNftForOwner`):
233
+ * - Encrypts `privateMetadata` under a 32-byte symmetric `CEK` using AES-256-GCM with `public` header bound as AAD;
234
+ * - Wraps `CEK` exclusively to `recipientPublicKeyHex` (`buyerPk`);
235
+ * - Commits `plaintextHash`, `cekCommitmentHash`, and `cekPublicKeyHex` in `public`.
236
+ */
237
+ function sealEncryptedNftForOwner(input) {
238
+ if (!input || typeof input !== "object") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_INPUT", "Missing SealEncryptedNftForOwnerInput");
239
+ const ownerDid = normalizeScreeningAddress(input.ownerDid);
240
+ if (input.ofacSanctionedSet) assertNotOfacSanctioned([ownerDid], input.ofacSanctionedSet);
241
+ const recipientPk = normalizeSecp256k1PublicKeyHex(input.recipientPublicKeyHex, "recipientPublicKeyHex");
242
+ const alg = input.alg ?? "X25519-XSalsa20-Poly1305";
243
+ if (!VALID_ENCRYPTED_NFT_ALGORITHMS.has(alg)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_ALG", `Unsupported algorithm "${String(alg)}"`);
244
+ const category = (input.category || "").trim();
245
+ const tags = (input.tags ?? []).map((t) => String(t).trim());
246
+ const publicSummary = (input.publicSummary || "").trim();
247
+ const canonicalPlaintext = canonicalizeEncryptedNftMetadata(input.privateMetadata);
248
+ const plaintextHash = computeEncryptedNftPlaintextHash(canonicalPlaintext);
249
+ const cekHex = input.cekHex ? normalizeHex32Bytes(input.cekHex, "cekHex") : randomBytes(32).toString("hex");
250
+ const cekCommitmentHash = computeEncryptedNftCekCommitmentHash(cekHex);
251
+ const cekPublicKeyHex = deriveOwnerPublicKeyHexFromSecretKey(cekHex);
252
+ const ephemeralSkHex = input.ephemeralSecretKeyHex ? normalizeHex32Bytes(input.ephemeralSecretKeyHex, "ephemeralSecretKeyHex") : randomBytes(32).toString("hex");
253
+ const ephemeralPk = deriveOwnerPublicKeyHexFromSecretKey(ephemeralSkHex);
254
+ const nonceHex = input.nonceHex ? input.nonceHex.trim().replace(/^0x/i, "").toLowerCase() : randomBytes(12).toString("hex");
255
+ if (!HEX_24_REGEX.test(nonceHex)) throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_NONCE", "nonceHex must be a 12-byte (24-hex) IV");
256
+ const publicHeader = {
257
+ schemaVersion: ENCRYPTED_NFT_SCHEMA_VERSION,
258
+ category,
259
+ tags,
260
+ publicSummary,
261
+ plaintextHash,
262
+ cekCommitmentHash,
263
+ cekPublicKeyHex,
264
+ ...input.arcSpaceUri !== void 0 ? { arcSpaceUri: input.arcSpaceUri.trim() } : {}
265
+ };
266
+ const aad = computeEncryptedNftPublicHeaderAad(publicHeader);
267
+ const cipher = createCipheriv("aes-256-gcm", Buffer.from(cekHex, "hex"), Buffer.from(nonceHex, "hex"));
268
+ cipher.setAAD(aad);
269
+ const ciphertextMetadata = Buffer.concat([cipher.update(Buffer.from(canonicalPlaintext, "utf8")), cipher.final()]).toString("hex");
270
+ const ciphertextTag = cipher.getAuthTag().toString("hex");
271
+ if (ciphertextMetadata.length > MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS) throw createEncryptedNftError("ENCRYPTED_NFT_CIPHERTEXT_TOO_LARGE", `Inline ciphertextMetadata (${ciphertextMetadata.length} hex chars) exceeds max ${MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS} — store large payloads in ArcSpace`);
272
+ const { encryptedCek, cekWrapTag, handoverProofHash, handoverSignature } = computeKeyWrapStreamAndTag({
273
+ ephemeralSkHex,
274
+ recipientPkHex: recipientPk,
275
+ ephemeralPkHex: ephemeralPk,
276
+ ownerDid,
277
+ nonceHex,
278
+ cekHex,
279
+ cekCommitmentHash,
280
+ cekPublicKeyHex,
281
+ handoverCount: 0
282
+ });
283
+ return validateEncryptedAssetEnvelope({
284
+ public: publicHeader,
285
+ encrypted: {
286
+ alg,
287
+ ownerDid,
288
+ recipientPk,
289
+ ephemeralPk,
290
+ nonce: nonceHex,
291
+ encryptedCek,
292
+ cekWrapTag,
293
+ ciphertextMetadata,
294
+ ciphertextTag,
295
+ handoverProofHash,
296
+ handoverSignature,
297
+ handoverCount: 0
298
+ }
299
+ });
300
+ }
301
+ /**
302
+ * 2. DID Wallet / AI Agent Owner Auto-Decryption (`openEncryptedNftAsOwner`):
303
+ * - Verifies viewer is the current NFT owner (`viewerDid === envelope.encrypted.ownerDid` and `currentAssetOwnerDid`);
304
+ * - Unwraps `CEK` using `ownerSecretKeyHex` and verifies `cekCommitmentHash` and `cekPublicKeyHex`;
305
+ * - Decrypts `ciphertextMetadata` with AES-256-GCM + `public` header AAD and verifies `plaintextHash`.
306
+ */
307
+ function openEncryptedNftAsOwner(input) {
308
+ if (!input || typeof input !== "object") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_OPEN_INPUT", "Missing OpenEncryptedNftAsOwnerInput");
309
+ const envelope = validateEncryptedAssetEnvelope(input.envelope);
310
+ const viewerDid = normalizeScreeningAddress(input.viewerDid);
311
+ const envelopeOwnerDid = normalizeScreeningAddress(envelope.encrypted.ownerDid);
312
+ if (input.currentAssetOwnerDid !== void 0) {
313
+ const assetOwnerDid = normalizeScreeningAddress(input.currentAssetOwnerDid);
314
+ if (viewerDid !== assetOwnerDid || envelopeOwnerDid !== assetOwnerDid) throw createEncryptedNftError("ENCRYPTED_NFT_OWNER_MISMATCH", `Viewer ${viewerDid} does not match current on-chain asset.owner (${assetOwnerDid})`);
315
+ }
316
+ const cekHex = unwrapCekInternal({
317
+ envelope,
318
+ ownerSecretKeyHex: input.ownerSecretKeyHex,
319
+ expectedOwnerDid: viewerDid
320
+ });
321
+ const aad = computeEncryptedNftPublicHeaderAad(envelope.public);
322
+ let decryptedBuf;
323
+ try {
324
+ const decipher = createDecipheriv("aes-256-gcm", Buffer.from(cekHex, "hex"), Buffer.from(envelope.encrypted.nonce, "hex"));
325
+ decipher.setAAD(aad);
326
+ decipher.setAuthTag(Buffer.from(envelope.encrypted.ciphertextTag, "hex"));
327
+ decryptedBuf = Buffer.concat([decipher.update(Buffer.from(envelope.encrypted.ciphertextMetadata, "hex")), decipher.final()]);
328
+ } catch {
329
+ throw createEncryptedNftError("ENCRYPTED_NFT_DECRYPTION_FAILED", "AES-256-GCM authentication or decryption failed (tampered ciphertext or AAD header)");
330
+ }
331
+ const plaintextStr = decryptedBuf.toString("utf8");
332
+ const recomputedPlaintextHash = computeEncryptedNftPlaintextHash(plaintextStr);
333
+ if (recomputedPlaintextHash !== envelope.public.plaintextHash.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_PLAINTEXT_HASH_MISMATCH", `Decrypted plaintext hash (${recomputedPlaintextHash}) does not match committed public.plaintextHash (${envelope.public.plaintextHash})`);
334
+ let privateMetadata;
335
+ try {
336
+ privateMetadata = JSON.parse(plaintextStr);
337
+ } catch {
338
+ throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_METADATA", "Decrypted plaintext is not valid JSON privateMetadata");
339
+ }
340
+ assertNoPrototypePollution(privateMetadata, "decryptedPrivateMetadata");
341
+ canonicalizeEncryptedNftMetadata(privateMetadata);
342
+ return {
343
+ ownerDid: envelopeOwnerDid,
344
+ recipientPk: envelope.encrypted.recipientPk,
345
+ cekHex,
346
+ plaintextHash: recomputedPlaintextHash,
347
+ cekCommitmentHash: envelope.public.cekCommitmentHash.toLowerCase(),
348
+ privateMetadata,
349
+ publicHeader: {
350
+ ...envelope.public,
351
+ tags: [...envelope.public.tags]
352
+ }
353
+ };
354
+ }
355
+ /**
356
+ * 3. Secondary Market Transfer / Sale Key-Wrap Handover (`rewrapEncryptedNftForNewOwner`):
357
+ * - Decrypts and verifies the existing `CEK` and `ciphertextMetadata` with `currentOwnerSecretKeyHex`
358
+ * (preventing garbage-key swap attacks);
359
+ * - Re-wraps the exact same `CEK` to `newOwnerPublicKeyHex` without re-encrypting `ciphertextMetadata`
360
+ * or re-uploading `ArcSpace` blobs.
361
+ */
362
+ function rewrapEncryptedNftForNewOwner(input) {
363
+ if (!input || typeof input !== "object") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_REWRAP_INPUT", "Missing RewrapEncryptedNftForNewOwnerInput");
364
+ const currentOwnerDid = normalizeScreeningAddress(input.currentOwnerDid);
365
+ const newOwnerDid = normalizeScreeningAddress(input.newOwnerDid);
366
+ if (currentOwnerDid === newOwnerDid) throw createEncryptedNftError("ENCRYPTED_NFT_SELF_REWRAP_FORBIDDEN", "newOwnerDid must be distinct from currentOwnerDid during key-wrap handover");
367
+ if (input.ofacSanctionedSet) assertNotOfacSanctioned([currentOwnerDid, newOwnerDid], input.ofacSanctionedSet);
368
+ const opened = openEncryptedNftAsOwner({
369
+ envelope: input.envelope,
370
+ viewerDid: currentOwnerDid,
371
+ ownerSecretKeyHex: input.currentOwnerSecretKeyHex,
372
+ currentAssetOwnerDid: currentOwnerDid
373
+ });
374
+ const newRecipientPk = normalizeSecp256k1PublicKeyHex(input.newOwnerPublicKeyHex, "newOwnerPublicKeyHex");
375
+ const ephemeralSkHex = input.ephemeralSecretKeyHex ? normalizeHex32Bytes(input.ephemeralSecretKeyHex, "ephemeralSecretKeyHex") : randomBytes(32).toString("hex");
376
+ const ephemeralPk = deriveOwnerPublicKeyHexFromSecretKey(ephemeralSkHex);
377
+ const nonceHex = input.envelope.encrypted.nonce.toLowerCase();
378
+ const nextHandoverCount = input.envelope.encrypted.handoverCount + 1;
379
+ const { encryptedCek, cekWrapTag, handoverProofHash, handoverSignature } = computeKeyWrapStreamAndTag({
380
+ ephemeralSkHex,
381
+ recipientPkHex: newRecipientPk,
382
+ ephemeralPkHex: ephemeralPk,
383
+ ownerDid: newOwnerDid,
384
+ nonceHex,
385
+ cekHex: opened.cekHex,
386
+ cekCommitmentHash: opened.cekCommitmentHash,
387
+ cekPublicKeyHex: input.envelope.public.cekPublicKeyHex,
388
+ handoverCount: nextHandoverCount
389
+ });
390
+ return validateEncryptedAssetEnvelope({
391
+ public: {
392
+ ...input.envelope.public,
393
+ tags: [...input.envelope.public.tags]
394
+ },
395
+ encrypted: {
396
+ ...input.envelope.encrypted,
397
+ ownerDid: newOwnerDid,
398
+ recipientPk: newRecipientPk,
399
+ ephemeralPk,
400
+ encryptedCek,
401
+ cekWrapTag,
402
+ handoverProofHash,
403
+ handoverSignature,
404
+ handoverCount: nextHandoverCount
405
+ }
406
+ });
407
+ }
408
+ /**
409
+ * Deterministic On-Chain Handover Verifier (`verifyEncryptedNftHandover`):
410
+ * - Verifies on-chain that a secondary transfer / sale handover:
411
+ * 1. Preserved `public` discovery headers (`plaintextHash`, `cekCommitmentHash`, `cekPublicKeyHex`, `arcSpaceUri`, `category`, `tags`, `publicSummary`) 100% unchanged;
412
+ * 2. Preserved `ciphertextMetadata`, `ciphertextTag`, and `nonce` 100% unchanged;
413
+ * 3. Transitioned `ownerDid` from `expectedPreviousOwnerDid` to `expectedNewOwnerDid` and bound `recipientPk = expectedNewOwnerPublicKeyHex`;
414
+ * 4. Incremented `handoverCount` by exactly `+1` with a valid `handoverProofHash` and `handoverSignature` verified against `public.cekPublicKeyHex`;
415
+ * 5. When `newOwnerSecretKeyHex` or `ephemeralSecretKeyHex` is provided (interactive/atomic buyer verification), unwraps `encryptedCek` and verifies `computeEncryptedNftCekCommitmentHash(unwrappedCek) === after.public.cekCommitmentHash`.
416
+ */
417
+ function verifyEncryptedNftHandover(input) {
418
+ if (!input || typeof input !== "object") throw createEncryptedNftError("INVALID_ENCRYPTED_NFT_HANDOVER_INPUT", "Missing VerifyEncryptedNftHandoverInput");
419
+ const before = validateEncryptedAssetEnvelope(input.beforeEnvelope);
420
+ const after = validateEncryptedAssetEnvelope(input.afterEnvelope);
421
+ const prevOwnerDid = normalizeScreeningAddress(input.expectedPreviousOwnerDid);
422
+ const nextOwnerDid = normalizeScreeningAddress(input.expectedNewOwnerDid);
423
+ const nextRecipientPk = normalizeSecp256k1PublicKeyHex(input.expectedNewOwnerPublicKeyHex, "expectedNewOwnerPublicKeyHex");
424
+ if (normalizeScreeningAddress(before.encrypted.ownerDid) !== prevOwnerDid) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_PREV_OWNER_MISMATCH", `beforeEnvelope.ownerDid (${before.encrypted.ownerDid}) does not match expectedPreviousOwnerDid (${prevOwnerDid})`);
425
+ if (normalizeScreeningAddress(after.encrypted.ownerDid) !== nextOwnerDid) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_NEXT_OWNER_MISMATCH", `afterEnvelope.ownerDid (${after.encrypted.ownerDid}) does not match expectedNewOwnerDid (${nextOwnerDid})`);
426
+ if (after.encrypted.recipientPk.toLowerCase() !== nextRecipientPk) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_PK_MISMATCH", `afterEnvelope.recipientPk (${after.encrypted.recipientPk}) does not match expectedNewOwnerPublicKeyHex (${nextRecipientPk})`);
427
+ const beforeAad = computeEncryptedNftPublicHeaderAad(before.public);
428
+ const afterAad = computeEncryptedNftPublicHeaderAad(after.public);
429
+ if (!beforeAad.equals(afterAad)) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_PUBLIC_HEADER_MUTATED", "public discovery header (including plaintextHash, cekCommitmentHash, cekPublicKeyHex, and arcSpaceUri) cannot be mutated during ownership handover");
430
+ if (before.encrypted.alg !== after.encrypted.alg || before.encrypted.nonce.toLowerCase() !== after.encrypted.nonce.toLowerCase() || before.encrypted.ciphertextMetadata.toLowerCase() !== after.encrypted.ciphertextMetadata.toLowerCase() || before.encrypted.ciphertextTag.toLowerCase() !== after.encrypted.ciphertextTag.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_CIPHERTEXT_MUTATED", "encrypted.ciphertextMetadata, ciphertextTag, alg, and nonce must remain immutable during key-wrap handover");
431
+ if (after.encrypted.handoverCount !== before.encrypted.handoverCount + 1) throw createEncryptedNftError("ENCRYPTED_NFT_HANDOVER_COUNT_MISMATCH", `Expected handoverCount ${before.encrypted.handoverCount + 1}, got ${after.encrypted.handoverCount}`);
432
+ if (input.newOwnerSecretKeyHex !== void 0) unwrapCekInternal({
433
+ envelope: after,
434
+ ownerSecretKeyHex: input.newOwnerSecretKeyHex,
435
+ expectedOwnerDid: nextOwnerDid
436
+ });
437
+ else if (input.ephemeralSecretKeyHex !== void 0) {
438
+ const ephPk = deriveOwnerPublicKeyHexFromSecretKey(input.ephemeralSecretKeyHex);
439
+ if (ephPk !== after.encrypted.ephemeralPk.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_KEY_MISMATCH", `Provided ephemeralSecretKeyHex does not correspond to afterEnvelope.encrypted.ephemeralPk (${after.encrypted.ephemeralPk})`);
440
+ const ecdhSecret = computeSecp256k1EcdhSharedSecret(input.ephemeralSecretKeyHex, nextRecipientPk, "expectedNewOwnerPublicKeyHex");
441
+ const nonceHex = after.encrypted.nonce.toLowerCase();
442
+ const encryptedCekHex = normalizeHex32Bytes(after.encrypted.encryptedCek, "encryptedCek");
443
+ const wrapKey = createHmac("sha256", ecdhSecret).update(`OCAP_ENCRYPTED_NFT_KW_STREAM_V1:${nextRecipientPk}:${ephPk}:${nextOwnerDid}:${nonceHex}`, "utf8").digest();
444
+ if (createHmac("sha256", wrapKey).update(`OCAP_ENCRYPTED_NFT_KW_TAG_V1:${nextOwnerDid}:${nextRecipientPk}:${ephPk}:${nonceHex}:${encryptedCekHex}:${after.public.cekCommitmentHash.toLowerCase()}`, "utf8").digest("hex").slice(0, 32) !== after.encrypted.cekWrapTag.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_WRAP_TAG_INVALID", "CEK key-wrap authentication tag verification failed");
445
+ const encryptedBytes = Buffer.from(encryptedCekHex, "hex");
446
+ const cekBytes = Buffer.alloc(32);
447
+ for (let i = 0; i < 32; i++) cekBytes[i] = encryptedBytes[i] ^ wrapKey[i];
448
+ const unwrappedCekHex = cekBytes.toString("hex");
449
+ const recomputedCekCommitment = computeEncryptedNftCekCommitmentHash(unwrappedCekHex);
450
+ if (recomputedCekCommitment !== after.public.cekCommitmentHash.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_CEK_COMMITMENT_MISMATCH", `Unwrapped CEK commitment (${recomputedCekCommitment}) does not match public.cekCommitmentHash (${after.public.cekCommitmentHash})`);
451
+ const recomputedCekPk = deriveOwnerPublicKeyHexFromSecretKey(unwrappedCekHex);
452
+ if (recomputedCekPk !== after.public.cekPublicKeyHex.toLowerCase()) throw createEncryptedNftError("ENCRYPTED_NFT_CEK_PK_MISMATCH", `Unwrapped CEK public key (${recomputedCekPk}) does not match public.cekPublicKeyHex (${after.public.cekPublicKeyHex})`);
453
+ }
454
+ return true;
455
+ }
456
+
457
+ //#endregion
458
+ export { ENCRYPTED_NFT_SCHEMA_VERSION, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, VALID_ENCRYPTED_NFT_ALGORITHMS, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, deriveOwnerPublicKeyHexFromSecretKey, openEncryptedNftAsOwner, rewrapEncryptedNftForNewOwner, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyEncryptedNftHandover };