@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,34 @@
1
+ import { CustomError } from "@ocap/util/lib/error";
2
+ import { IBaseContext, IChainConfig, IDecodedContext } from "@ocap/types";
3
+
4
+ //#region src/pipes/pre-flight-waf.d.ts
5
+ declare const MAX_PREFLIGHT_JSON_DEPTH = 16;
6
+ declare const MAX_PREFLIGHT_JSON_KEYS = 512;
7
+ declare const MAX_PREFLIGHT_STRING_FIELD_BYTES: number;
8
+ declare const MAX_PREFLIGHT_WIRE_BYTES_FALLBACK: number;
9
+ declare const MAX_ROLLUP_TXS_LIST_SIZE = 512;
10
+ declare const MAX_DELEGATE_TYPE_URLS_LIST_SIZE = 128;
11
+ /**
12
+ * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
13
+ */
14
+ declare function assertRawWireEnvelope(txBase64: string, config?: IChainConfig): void;
15
+ /**
16
+ * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
17
+ * stripped by `createMessage()` or `vStripUnknown()`.
18
+ */
19
+ declare function assertKnownItxFields(typeUrl: string, rawInner: Record<string, unknown>): void;
20
+ /**
21
+ * Deep structural & anomaly scanner over decoded `itx` and raw `tx.itx`.
22
+ */
23
+ declare function scanItxPayloadAnomalies(itx: unknown, txType: string | undefined, config?: IChainConfig, rawTxItx?: unknown, txSignatures?: unknown): void;
24
+ /**
25
+ * Pipeline pipe that runs the Pre-Flight WAF structural & anomaly checks.
26
+ */
27
+ declare function PreFlightWaf(context: IDecodedContext, next: (err?: CustomError) => void): void;
28
+ /**
29
+ * Stateless, zero-DB-I/O Pre-Flight inspection runner for `OCAPResolver.sendTx`
30
+ * BEFORE enqueuing into the single-writer queue (`this.queue`) or acquiring the SQLite write lock.
31
+ */
32
+ declare function inspectTransactionPreFlight(context: IBaseContext): Promise<IDecodedContext>;
33
+ //#endregion
34
+ export { MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, assertKnownItxFields, assertRawWireEnvelope, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies };
@@ -0,0 +1,603 @@
1
+ import { ENCRYPTED_NFT_SCHEMA_VERSION, validateEncryptedAssetEnvelope } from "../encrypted-nft-envelope.mjs";
2
+ import DecodeItx from "./decode-itx.mjs";
3
+ import DecodeTx from "./decode-tx.mjs";
4
+ import runner_default from "../runner.mjs";
5
+ import CreatedVerifyBlockedPipe from "./verify-blocked.mjs";
6
+ import VerifyServiceFee from "./verify-service-fee.mjs";
7
+ import VerifySignature from "./verify-signature.mjs";
8
+ import VerifyTx from "./verify-tx.mjs";
9
+ import VerifyTxSize from "./verify-tx-size.mjs";
10
+ import { CustomError } from "@ocap/util/lib/error";
11
+ import get from "lodash/get.js";
12
+ import { createMessage, decodeAny, encodeAny, fromTypeUrl, toTypeUrl } from "@ocap/message";
13
+ import { getListField } from "@ocap/util/lib/get-list-field";
14
+
15
+ //#region src/pipes/pre-flight-waf.ts
16
+ const MAX_PREFLIGHT_JSON_DEPTH = 16;
17
+ const MAX_PREFLIGHT_JSON_KEYS = 512;
18
+ const MAX_PREFLIGHT_STRING_FIELD_BYTES = 16 * 1024;
19
+ const MAX_PREFLIGHT_WIRE_BYTES_FALLBACK = 256 * 1024;
20
+ const MAX_ROLLUP_TXS_LIST_SIZE = 512;
21
+ const MAX_DELEGATE_TYPE_URLS_LIST_SIZE = 128;
22
+ const FORBIDDEN_OBJECT_KEYS = new Set([
23
+ "__proto__",
24
+ "constructor",
25
+ "prototype"
26
+ ]);
27
+ const DANGEROUS_URI_PATTERN = /^\s*(?:javascript\s*:|vbscript\s*:|data\s*:\s*(?:text\/html|application\/javascript|application\/x-javascript|text\/javascript))/i;
28
+ const FORBIDDEN_STORAGE_DATA_URI_PATTERN = /^\s*data\s*:\s*(?:image\/|audio\/|video\/|application\/(?:octet-stream|wasm|pdf|zip|x-msdownload|x-executable|x-mach-binary))/i;
29
+ const FORBIDDEN_BINARY_MAGIC_BASE64_PATTERN = /^(?:AGFzbQ|f0VMRg|JVBERi0|UEsDB|H4sIA|iVBORw0KGgo|(?:\/9j\/|_9j_)4AAQ|R0lGOD(?:lh|dh))/;
30
+ const FORBIDDEN_BINARY_MAGIC_RAW_PATTERN = /^(?:\x00asm|\x7fELF|%PDF-|PK\x03\x04|\x1f\x8b\x08[\x00-\x1f]|\x89PNG\r\n\x1a\n|\xff\xd8\xff[\xdb\xe0\xe1\xe2\xee]|GIF8[79]a)/;
31
+ const FORBIDDEN_CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
32
+ const BASE64_WIRE_PATTERN = /^[A-Za-z0-9+/=_-]+$/;
33
+ const STANDARD_BOUNDED_LIST_KEYS = [
34
+ "inputs",
35
+ "outputs",
36
+ "assets",
37
+ "tokens",
38
+ "slashers",
39
+ "ops",
40
+ "validators",
41
+ "trustedIssuers",
42
+ "hooks",
43
+ "variables",
44
+ "spenders",
45
+ "minters"
46
+ ];
47
+ const URI_LIKE_FIELD_KEYS = new Set([
48
+ "endpoint",
49
+ "website",
50
+ "icon",
51
+ "url",
52
+ "uri",
53
+ "communityUrl"
54
+ ]);
55
+ const DELEGATE_TOKEN_EXT_KEYS = new Set([
56
+ "address",
57
+ "value",
58
+ "decimal",
59
+ "unit",
60
+ "symbol",
61
+ "to",
62
+ "toList",
63
+ "txCount",
64
+ "txAllowance",
65
+ "totalAllowance",
66
+ "allowance",
67
+ "validUntil",
68
+ "rate",
69
+ "txSent",
70
+ "spentAllowance",
71
+ "lastTx",
72
+ "maxPerTx",
73
+ "windowLimit",
74
+ "windowSeconds",
75
+ "windowStart",
76
+ "windowSpent",
77
+ "coSignAllowance",
78
+ "coSignRequired",
79
+ "requirePinnedPayee",
80
+ "notifyBeforeDebit",
81
+ "notifyLeadSeconds"
82
+ ]);
83
+ const MULTI_IO_ITEM_ALLOWED_KEYS = new Set([
84
+ "owner",
85
+ "tokens",
86
+ "tokensList",
87
+ "assets",
88
+ "assetsList",
89
+ "value"
90
+ ]);
91
+ const protoAllowedKeysCache = /* @__PURE__ */ new Map();
92
+ function getAllowedTopLevelItxKeys(typeUrl) {
93
+ if (protoAllowedKeysCache.has(typeUrl)) return protoAllowedKeysCache.get(typeUrl);
94
+ try {
95
+ const typeName = fromTypeUrl(typeUrl);
96
+ if (!typeName) {
97
+ protoAllowedKeysCache.set(typeUrl, null);
98
+ return null;
99
+ }
100
+ const msg = createMessage(typeName, {});
101
+ if (!msg || typeof msg.toObject !== "function") {
102
+ protoAllowedKeysCache.set(typeUrl, null);
103
+ return null;
104
+ }
105
+ const protoObj = msg.toObject();
106
+ const allowed = new Set([
107
+ "typeUrl",
108
+ "type_url",
109
+ "type"
110
+ ]);
111
+ for (const key of Object.keys(protoObj)) {
112
+ allowed.add(key);
113
+ if (key.endsWith("List") && key.length > 4) allowed.add(key.slice(0, -4));
114
+ if (key.endsWith("Map") && key.length > 3) allowed.add(key.slice(0, -3));
115
+ }
116
+ protoAllowedKeysCache.set(typeUrl, allowed);
117
+ return allowed;
118
+ } catch {
119
+ protoAllowedKeysCache.set(typeUrl, null);
120
+ return null;
121
+ }
122
+ }
123
+ /**
124
+ * Fast O(1) wire-size and base64 character validation before allocating buffers or decoding.
125
+ */
126
+ function assertRawWireEnvelope(txBase64, config) {
127
+ if (!txBase64 || typeof txBase64 !== "string" || txBase64.length < 20) throw new CustomError("INVALID_TX", "Transaction data is empty or too short");
128
+ const trimmed = txBase64.trim();
129
+ if (!BASE64_WIRE_PATTERN.test(trimmed)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction wire data contains invalid non-base64 characters");
130
+ const maxTxSizeMap = get(config, "transaction.maxTxSize") || {};
131
+ const configuredLimits = Object.values(maxTxSizeMap).filter((v) => typeof v === "number" && v > 0);
132
+ const maxAssetSize = get(config, "transaction.maxAssetSize", 65536) || 65536;
133
+ const maxExtraSize = get(config, "transaction.maxExtraSize", 8192) || 8192;
134
+ const maxConfiguredTxBytes = configuredLimits.length > 0 ? Math.max(...configuredLimits, maxAssetSize) + maxExtraSize : MAX_PREFLIGHT_WIRE_BYTES_FALLBACK;
135
+ const estimatedWireBytes = Math.floor(trimmed.length * 3 / 4);
136
+ if (estimatedWireBytes > maxConfiguredTxBytes) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: raw transaction wire size (${estimatedWireBytes} bytes) exceeds maximum ceiling (${maxConfiguredTxBytes} bytes)`);
137
+ }
138
+ /**
139
+ * Reject unknown / alien fields in raw or CBOR `tx.itx` payloads that would otherwise be silently
140
+ * stripped by `createMessage()` or `vStripUnknown()`.
141
+ */
142
+ function assertKnownItxFields(typeUrl, rawInner) {
143
+ if (!rawInner || typeof rawInner !== "object" || Array.isArray(rawInner)) return;
144
+ for (const key of Object.keys(rawInner)) if (FORBIDDEN_OBJECT_KEYS.has(key)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: forbidden key "${key}" in ${typeUrl}`);
145
+ const allowedKeys = getAllowedTopLevelItxKeys(typeUrl);
146
+ if (allowedKeys) {
147
+ for (const key of Object.keys(rawInner)) if (!allowedKeys.has(key)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: unexpected unknown field "${key}" in ${typeUrl}`);
148
+ }
149
+ for (const ioField of [
150
+ "inputs",
151
+ "inputsList",
152
+ "outputs",
153
+ "outputsList"
154
+ ]) {
155
+ const items = rawInner[ioField];
156
+ if (Array.isArray(items)) {
157
+ for (const item of items) if (item && typeof item === "object" && !Array.isArray(item)) {
158
+ for (const itemKey of Object.keys(item)) if (!MULTI_IO_ITEM_ALLOWED_KEYS.has(itemKey)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: unexpected unknown field "${itemKey}" in ${typeUrl}.${ioField}`);
159
+ }
160
+ }
161
+ }
162
+ if (typeUrl === "fg:t:delegate") {
163
+ const ops = Array.isArray(rawInner.opsList) ? rawInner.opsList : Array.isArray(rawInner.ops) ? rawInner.ops : [];
164
+ for (const op of ops) {
165
+ const limit = op?.limit;
166
+ if (limit && typeof limit === "object") {
167
+ const tokens = Array.isArray(limit.tokensList) ? limit.tokensList : Array.isArray(limit.tokens) ? limit.tokens : [];
168
+ for (const tok of tokens) if (tok && typeof tok === "object") {
169
+ for (const tk of Object.keys(tok)) if (!DELEGATE_TOKEN_EXT_KEYS.has(tk)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: unexpected unknown field "${tk}" in fg:t:delegate token limit`);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ }
175
+ function isAllowedAnyDataTypeUrl(typeUrl) {
176
+ if (!typeUrl) return true;
177
+ if (typeUrl === "json" || typeUrl === "vc" || typeUrl === "fg:x:address" || typeUrl === ENCRYPTED_NFT_SCHEMA_VERSION) return true;
178
+ const directTypeName = fromTypeUrl(typeUrl);
179
+ if (directTypeName && directTypeName !== typeUrl) try {
180
+ if (createMessage(directTypeName, {})) return true;
181
+ } catch {}
182
+ const mappedTypeUrl = toTypeUrl(typeUrl);
183
+ if (mappedTypeUrl?.startsWith("fg:")) {
184
+ const mappedName = fromTypeUrl(mappedTypeUrl);
185
+ if (mappedName && mappedName !== mappedTypeUrl) try {
186
+ if (createMessage(mappedName, {})) return true;
187
+ } catch {}
188
+ }
189
+ return false;
190
+ }
191
+ function assertNotBinaryOrBlobString(str, fieldName = "value", allowTokenCharterIcon = false, peelDepth = 0) {
192
+ const trimmed = str.trim();
193
+ if (!trimmed) return;
194
+ if (FORBIDDEN_BINARY_MAGIC_RAW_PATTERN.test(str) || FORBIDDEN_BINARY_MAGIC_BASE64_PATTERN.test(trimmed)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: binary/executable/media blob detected in "${fieldName}" — store binary files in ArcSpace and keep only structured metadata/proofs on-chain`);
195
+ if (FORBIDDEN_STORAGE_DATA_URI_PATTERN.test(trimmed)) {
196
+ if (allowTokenCharterIcon && fieldName === "icon" && /^data:image\//i.test(trimmed) && trimmed.length <= 20480) return;
197
+ throw new CustomError("INVALID_TX", `Pre-Flight WAF: inline binary/media Data URI forbidden in "${fieldName}" — store media in ArcSpace and reference via URL/DID + cryptographic hash`);
198
+ }
199
+ if (peelDepth >= 2) return;
200
+ if (trimmed.length >= 4 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
201
+ let unquoted;
202
+ try {
203
+ unquoted = JSON.parse(trimmed);
204
+ } catch {
205
+ unquoted = void 0;
206
+ }
207
+ if (typeof unquoted === "string" && unquoted !== str) assertNotBinaryOrBlobString(unquoted, fieldName, allowTokenCharterIcon, peelDepth + 1);
208
+ }
209
+ if (trimmed.length >= 12 && trimmed.length <= MAX_PREFLIGHT_STRING_FIELD_BYTES && /^[A-Za-z0-9+/_-]+={0,2}$/.test(trimmed)) try {
210
+ const normalizedB64 = trimmed.replace(/-/g, "+").replace(/_/g, "/");
211
+ const decodedBytes = Buffer.from(normalizedB64, "base64");
212
+ if (decodedBytes.byteLength >= 4) {
213
+ const preview = Buffer.from(decodedBytes.subarray(0, 16)).toString("latin1");
214
+ if (FORBIDDEN_BINARY_MAGIC_RAW_PATTERN.test(preview)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: binary/executable/media blob detected in "${fieldName}" — store binary files in ArcSpace and keep only structured metadata/proofs on-chain`);
215
+ const decodedUtf8 = decodedBytes.toString("utf8");
216
+ if (decodedUtf8 && decodedUtf8 !== trimmed) assertNotBinaryOrBlobString(decodedUtf8, fieldName, allowTokenCharterIcon, peelDepth + 1);
217
+ }
218
+ } catch (err) {
219
+ if (err?.code === "INVALID_TX" || err?.code === "INVALID_TX_SIZE") throw err;
220
+ }
221
+ }
222
+ function isAnyEnvelopeCandidate(node, fieldName) {
223
+ if (fieldName === "ops" || fieldName === "opsList") return false;
224
+ const hasValue = Object.prototype.hasOwnProperty.call(node, "value");
225
+ if (typeof node.typeUrl === "string" || typeof node.type_url === "string") return hasValue || fieldName === "data" || fieldName === "metadata";
226
+ if ((fieldName === "data" || fieldName === "metadata") && typeof node.type === "string" && hasValue) return true;
227
+ return false;
228
+ }
229
+ function inspectJsonStructure(root, options) {
230
+ let totalKeys = 0;
231
+ const activeAncestors = /* @__PURE__ */ new WeakSet();
232
+ const isTokenCharterRoot = Boolean(root && typeof root === "object" && !Array.isArray(root) && root.kind === "ocap.token.charter.v1");
233
+ const visit = (node, depth, fieldName, peelCount = 0, inTokenCharter = isTokenCharterRoot) => {
234
+ if (depth > options.maxDepth) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: payload nesting depth exceeds maximum allowed depth of ${options.maxDepth}`);
235
+ if (node === null || node === void 0) return;
236
+ if (typeof node === "string") {
237
+ if (options.checkStrings) {
238
+ if (FORBIDDEN_CONTROL_CHAR_PATTERN.test(node)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: string field "${fieldName || "value"}" contains forbidden control characters`);
239
+ if (fieldName && URI_LIKE_FIELD_KEYS.has(fieldName) && DANGEROUS_URI_PATTERN.test(node)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: dangerous URI scheme in field "${fieldName}"`);
240
+ if (options.enforceAntiBlobStorage && !(fieldName && options.skipAntiBlobFieldNames?.has(fieldName) && depth <= 2)) {
241
+ const byteLen = Buffer.byteLength(node, "utf8");
242
+ const maxFieldBytes = inTokenCharter && fieldName === "icon" ? 20480 : MAX_PREFLIGHT_STRING_FIELD_BYTES;
243
+ if (byteLen > maxFieldBytes) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: string field "${fieldName || "value"}" (${byteLen} bytes) exceeds per-field cap (${maxFieldBytes} bytes) — offload large blobs to ArcSpace`);
244
+ assertNotBinaryOrBlobString(node, fieldName || "value", inTokenCharter);
245
+ if (peelCount < 3) {
246
+ const trimmed = node.trim();
247
+ if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
248
+ let nestedParsed;
249
+ let parsedOk = false;
250
+ try {
251
+ nestedParsed = JSON.parse(trimmed);
252
+ parsedOk = true;
253
+ } catch {}
254
+ if (parsedOk && nestedParsed !== null && nestedParsed !== void 0 && nestedParsed !== node) visit(nestedParsed, depth + 1, fieldName, peelCount + 1, inTokenCharter);
255
+ } else if (trimmed.length >= 16 && /^[A-Za-z0-9+/_-]+={0,2}$/.test(trimmed)) try {
256
+ const normalizedB64 = trimmed.replace(/-/g, "+").replace(/_/g, "/");
257
+ const decodedUtf8 = Buffer.from(normalizedB64, "base64").toString("utf8").trim();
258
+ if (decodedUtf8.startsWith("{") && decodedUtf8.endsWith("}") || decodedUtf8.startsWith("[") && decodedUtf8.endsWith("]") || decodedUtf8.startsWith("\"") && decodedUtf8.endsWith("\"")) {
259
+ const nestedParsed = JSON.parse(decodedUtf8);
260
+ if (nestedParsed !== null && nestedParsed !== void 0) visit(nestedParsed, depth + 1, fieldName, peelCount + 1, inTokenCharter);
261
+ }
262
+ } catch (err) {
263
+ if (err?.code === "INVALID_TX" || err?.code === "INVALID_TX_SIZE") throw err;
264
+ }
265
+ }
266
+ }
267
+ }
268
+ return;
269
+ }
270
+ if (typeof node !== "object" || node instanceof Uint8Array || Buffer.isBuffer(node)) return;
271
+ if (activeAncestors.has(node)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: circular reference detected in payload");
272
+ activeAncestors.add(node);
273
+ try {
274
+ if (Array.isArray(node)) {
275
+ totalKeys += node.length;
276
+ if (totalKeys > options.maxKeys) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: payload complexity (${totalKeys} elements/keys) exceeds maximum allowed (${options.maxKeys})`);
277
+ for (let i = 0; i < node.length; i++) visit(node[i], depth + 1, fieldName, peelCount, inTokenCharter);
278
+ return;
279
+ }
280
+ const recordNode = node;
281
+ const nextInTokenCharter = inTokenCharter || recordNode.kind === "ocap.token.charter.v1";
282
+ if (depth > 0 && options.maxAssetSize && isAnyEnvelopeCandidate(recordNode, fieldName)) {
283
+ for (const k of Object.keys(recordNode)) if (FORBIDDEN_OBJECT_KEYS.has(k)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: forbidden key "${k}" detected in payload`);
284
+ inspectAnyDataEnvelope(recordNode, options.maxAssetSize);
285
+ return;
286
+ }
287
+ const keys = Object.keys(recordNode);
288
+ totalKeys += keys.length;
289
+ if (totalKeys > options.maxKeys) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: payload key count (${totalKeys}) exceeds maximum allowed (${options.maxKeys})`);
290
+ for (const k of keys) {
291
+ if (FORBIDDEN_OBJECT_KEYS.has(k)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: forbidden key "${k}" detected in payload`);
292
+ visit(recordNode[k], depth + 1, k, peelCount, nextInTokenCharter);
293
+ }
294
+ } finally {
295
+ activeAncestors.delete(node);
296
+ }
297
+ };
298
+ visit(root, 0);
299
+ }
300
+ function inspectDecodedJsonOrVcString(rawStr, maxAssetSize, requireEncryptedNftSchema = false) {
301
+ const byteLen = Buffer.byteLength(rawStr, "utf8");
302
+ if (byteLen > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: embedded data payload (${byteLen} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
303
+ assertNotBinaryOrBlobString(rawStr, "data.value", false);
304
+ let parsed = null;
305
+ let fallbackDecodedStr = rawStr;
306
+ const trimmed = rawStr.trim();
307
+ if (trimmed.startsWith("{") || trimmed.startsWith("[") || trimmed.startsWith("\"")) try {
308
+ parsed = JSON.parse(trimmed);
309
+ } catch {}
310
+ else if (trimmed && trimmed !== "empty") try {
311
+ const normalizedB64 = trimmed.replace(/-/g, "+").replace(/_/g, "/");
312
+ const decodedBytes = Buffer.from(normalizedB64, "base64");
313
+ if (decodedBytes.byteLength > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: decoded data payload (${decodedBytes.byteLength} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
314
+ const preview = Buffer.from(decodedBytes.subarray(0, 16)).toString("latin1");
315
+ if (FORBIDDEN_BINARY_MAGIC_RAW_PATTERN.test(preview)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: binary/executable/media blob detected in data.value — store binary files in ArcSpace and keep only structured metadata/proofs on-chain");
316
+ const utf8 = decodedBytes.toString("utf8");
317
+ fallbackDecodedStr = utf8;
318
+ assertNotBinaryOrBlobString(utf8, "data.value", false);
319
+ if (utf8.trim().startsWith("{") || utf8.trim().startsWith("[") || utf8.trim().startsWith("\"")) parsed = JSON.parse(utf8);
320
+ } catch (err) {
321
+ if (err?.code === "INVALID_TX_SIZE" || err?.code === "INVALID_TX") throw err;
322
+ }
323
+ for (let i = 0; i < 4 && typeof parsed === "string"; i++) {
324
+ assertNotBinaryOrBlobString(parsed, "data.value", false);
325
+ const innerTrimmed = parsed.trim();
326
+ if (innerTrimmed.startsWith("{") || innerTrimmed.startsWith("[") || innerTrimmed.startsWith("\"")) try {
327
+ parsed = JSON.parse(innerTrimmed);
328
+ } catch {
329
+ break;
330
+ }
331
+ else if (innerTrimmed.length >= 4 && /^[A-Za-z0-9+/_-]+={0,2}$/.test(innerTrimmed)) try {
332
+ const normalizedB64 = innerTrimmed.replace(/-/g, "+").replace(/_/g, "/");
333
+ const innerBytes = Buffer.from(normalizedB64, "base64");
334
+ if (innerBytes.byteLength > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: decoded data payload (${innerBytes.byteLength} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
335
+ const preview = Buffer.from(innerBytes.subarray(0, 16)).toString("latin1");
336
+ if (FORBIDDEN_BINARY_MAGIC_RAW_PATTERN.test(preview)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: binary/executable/media blob detected in data.value — store binary files in ArcSpace and keep only structured metadata/proofs on-chain");
337
+ const innerUtf8 = innerBytes.toString("utf8");
338
+ fallbackDecodedStr = innerUtf8;
339
+ assertNotBinaryOrBlobString(innerUtf8, "data.value", false);
340
+ if (innerUtf8.trim().startsWith("{") || innerUtf8.trim().startsWith("[") || innerUtf8.trim().startsWith("\"")) parsed = JSON.parse(innerUtf8);
341
+ else break;
342
+ } catch (err) {
343
+ if (err?.code === "INVALID_TX_SIZE" || err?.code === "INVALID_TX") throw err;
344
+ break;
345
+ }
346
+ else break;
347
+ }
348
+ const targetToInspect = parsed !== null && parsed !== void 0 ? parsed : trimmed && trimmed !== "empty" ? fallbackDecodedStr : null;
349
+ if (targetToInspect !== null && targetToInspect !== void 0) {
350
+ inspectJsonStructure(targetToInspect, {
351
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
352
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
353
+ checkStrings: true,
354
+ enforceAntiBlobStorage: true,
355
+ maxAssetSize
356
+ });
357
+ if (typeof targetToInspect === "object" && !Array.isArray(targetToInspect) && (targetToInspect.public?.schemaVersion === ENCRYPTED_NFT_SCHEMA_VERSION || requireEncryptedNftSchema) || requireEncryptedNftSchema) validateEncryptedAssetEnvelope(targetToInspect);
358
+ } else if (requireEncryptedNftSchema) throw new CustomError("INVALID_TX", `Pre-Flight WAF: empty or unparseable ${ENCRYPTED_NFT_SCHEMA_VERSION} envelope`);
359
+ }
360
+ function inspectAnyDataEnvelope(anyField, maxAssetSize) {
361
+ if (!anyField || typeof anyField !== "object") return;
362
+ const dataObj = anyField;
363
+ const typeUrl = dataObj.typeUrl || dataObj.type_url || dataObj.type || "";
364
+ const rawVal = dataObj.value;
365
+ if (typeUrl && !isAllowedAnyDataTypeUrl(typeUrl)) throw new CustomError("INVALID_TX", `Pre-Flight WAF: unsupported or binary data.typeUrl "${typeUrl}" — on-chain data must be structured metadata/proofs (json, vc, or registered fg:* schema), not raw storage`);
366
+ const isEncryptedNftTypeUrl = typeUrl === ENCRYPTED_NFT_SCHEMA_VERSION;
367
+ if (rawVal instanceof Uint8Array || Buffer.isBuffer(rawVal)) {
368
+ if (rawVal.byteLength > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: embedded data payload (${rawVal.byteLength} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
369
+ const preview = Buffer.from(rawVal.subarray(0, 16)).toString("latin1");
370
+ if (FORBIDDEN_BINARY_MAGIC_RAW_PATTERN.test(preview)) throw new CustomError("INVALID_TX", "Pre-Flight WAF: binary/executable/media blob detected in data.value — store binary files in ArcSpace and keep only structured metadata/proofs on-chain");
371
+ const utf8 = Buffer.from(rawVal).toString("utf8");
372
+ if (typeUrl === "json" || typeUrl === "vc" || isEncryptedNftTypeUrl || !typeUrl) inspectDecodedJsonOrVcString(utf8, maxAssetSize, isEncryptedNftTypeUrl);
373
+ else assertNotBinaryOrBlobString(utf8, "data.value", false);
374
+ } else if (typeof rawVal === "string") if (typeUrl === "json" || typeUrl === "vc" || isEncryptedNftTypeUrl || !typeUrl) inspectDecodedJsonOrVcString(rawVal, maxAssetSize, isEncryptedNftTypeUrl);
375
+ else {
376
+ const byteLen = Buffer.byteLength(rawVal, "utf8");
377
+ if (byteLen > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: embedded data payload (${byteLen} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
378
+ assertNotBinaryOrBlobString(rawVal, "data.value", false);
379
+ if (typeUrl === "fg:x:address") inspectJsonStructure(rawVal, {
380
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
381
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
382
+ checkStrings: true,
383
+ enforceAntiBlobStorage: true,
384
+ maxAssetSize
385
+ });
386
+ else if (rawVal.length > 0 && rawVal !== "empty") {
387
+ let decoded;
388
+ try {
389
+ decoded = decodeAny({
390
+ typeUrl,
391
+ value: rawVal
392
+ });
393
+ } catch {
394
+ throw new CustomError("INVALID_TX", `Pre-Flight WAF: failed to decode Any data payload for typeUrl "${typeUrl}"`);
395
+ }
396
+ if (decoded?.type && decoded.type !== "Unknown") {
397
+ const reencoded = encodeAny(decoded)?.toObject();
398
+ if (!reencoded || reencoded.value !== rawVal) throw new CustomError("INVALID_TX", `Pre-Flight WAF: non-canonical or unknown trailing bytes in Any data payload for typeUrl "${typeUrl}"`);
399
+ }
400
+ if (decoded?.value !== void 0 && decoded?.value !== null) inspectJsonStructure(decoded.value, {
401
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
402
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
403
+ checkStrings: true,
404
+ enforceAntiBlobStorage: true,
405
+ maxAssetSize
406
+ });
407
+ }
408
+ }
409
+ else if (rawVal && typeof rawVal === "object" && !(rawVal instanceof Uint8Array) && !Buffer.isBuffer(rawVal)) {
410
+ inspectJsonStructure(rawVal, {
411
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
412
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
413
+ checkStrings: true,
414
+ enforceAntiBlobStorage: true,
415
+ maxAssetSize
416
+ });
417
+ const serializedLen = Buffer.byteLength(JSON.stringify(rawVal), "utf8");
418
+ if (serializedLen > maxAssetSize) throw new CustomError("INVALID_TX_SIZE", `Pre-Flight WAF: embedded data payload (${serializedLen} bytes) exceeds maxAssetSize (${maxAssetSize} bytes)`);
419
+ if (isEncryptedNftTypeUrl || !Array.isArray(rawVal) && rawVal.public?.schemaVersion === ENCRYPTED_NFT_SCHEMA_VERSION) validateEncryptedAssetEnvelope(rawVal);
420
+ } else if (rawVal === void 0) {
421
+ const flatCopy = {};
422
+ for (const [k, v] of Object.entries(dataObj)) {
423
+ if (k === "typeUrl" || k === "type_url") continue;
424
+ flatCopy[k] = v;
425
+ }
426
+ inspectJsonStructure(flatCopy, {
427
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
428
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
429
+ checkStrings: true,
430
+ enforceAntiBlobStorage: true,
431
+ maxAssetSize
432
+ });
433
+ if (isEncryptedNftTypeUrl || flatCopy.public?.schemaVersion === ENCRYPTED_NFT_SCHEMA_VERSION) validateEncryptedAssetEnvelope(flatCopy);
434
+ } else if (isEncryptedNftTypeUrl) throw new CustomError("INVALID_TX", `Pre-Flight WAF: ${ENCRYPTED_NFT_SCHEMA_VERSION} data.value must be a valid EncryptedAssetEnvelope`);
435
+ }
436
+ /**
437
+ * Deep structural & anomaly scanner over decoded `itx` and raw `tx.itx`.
438
+ */
439
+ function scanItxPayloadAnomalies(itx, txType, config, rawTxItx, txSignatures) {
440
+ if (!itx || typeof itx !== "object") throw new CustomError("INVALID_TX", "Pre-Flight WAF: transaction itx must be a valid object");
441
+ const maxListSize = get(config, "transaction.maxListSize", 64) || 64;
442
+ const maxMultisig = get(config, "transaction.maxMultisig", 32) || 32;
443
+ const maxAssetSize = get(config, "transaction.maxAssetSize", 65536) || 65536;
444
+ if (rawTxItx && typeof rawTxItx === "object") {
445
+ const rawShape = rawTxItx;
446
+ const resolvedTypeUrl = txType || rawShape.typeUrl || rawShape.type_url || (rawShape.type ? toTypeUrl(rawShape.type) : void 0);
447
+ if (resolvedTypeUrl) {
448
+ const rawKeys = Object.keys(rawShape);
449
+ const isPureProtoAnyWrapper = Boolean(rawShape.typeUrl || rawShape.type_url) && typeof rawShape.value === "string" && rawKeys.every((k) => k === "typeUrl" || k === "type_url" || k === "value");
450
+ if (rawShape.type && rawShape.value && typeof rawShape.value === "object" && !Array.isArray(rawShape.value)) {
451
+ for (const k of rawKeys) if (k !== "type" && k !== "typeUrl" && k !== "type_url" && k !== "value") throw new CustomError("INVALID_TX", `Pre-Flight WAF: unexpected unknown field "${k}" in ${resolvedTypeUrl}`);
452
+ assertKnownItxFields(resolvedTypeUrl, rawShape.value);
453
+ } else if (!isPureProtoAnyWrapper) assertKnownItxFields(resolvedTypeUrl, rawShape);
454
+ }
455
+ }
456
+ if (txType) assertKnownItxFields(txType, itx);
457
+ const itxObj = itx;
458
+ for (const field of STANDARD_BOUNDED_LIST_KEYS) {
459
+ const list = getListField(itxObj, field);
460
+ if (Array.isArray(list) && list.length > maxListSize) throw new CustomError("INVALID_TX_SIZE", `Size of ${field} can not exceeded ${maxListSize} items`);
461
+ }
462
+ let totalNestedTokens = 0;
463
+ let totalNestedAssets = 0;
464
+ for (const ioField of ["inputs", "outputs"]) {
465
+ const ioList = getListField(itxObj, ioField);
466
+ if (Array.isArray(ioList)) {
467
+ for (const item of ioList) if (item && typeof item === "object") {
468
+ const itemTokens = getListField(item, "tokens");
469
+ const itemAssets = getListField(item, "assets");
470
+ if (Array.isArray(itemTokens)) {
471
+ if (itemTokens.length > maxListSize) throw new CustomError("INVALID_TX_SIZE", `Size of tokens can not exceeded ${maxListSize} items`);
472
+ totalNestedTokens += itemTokens.length;
473
+ }
474
+ if (Array.isArray(itemAssets)) {
475
+ if (itemAssets.length > maxListSize) throw new CustomError("INVALID_TX_SIZE", `Size of assets can not exceeded ${maxListSize} items`);
476
+ totalNestedAssets += itemAssets.length;
477
+ }
478
+ }
479
+ }
480
+ }
481
+ if (totalNestedTokens > maxListSize * 2) throw new CustomError("INVALID_TX_SIZE", `Total nested token entries (${totalNestedTokens}) exceeds safe envelope`);
482
+ if (totalNestedAssets > maxListSize * 2) throw new CustomError("INVALID_TX_SIZE", `Total nested asset entries (${totalNestedAssets}) exceeds safe envelope`);
483
+ const itxSignatures = getListField(itxObj, "signatures");
484
+ if (Array.isArray(itxSignatures) && itxSignatures.length > maxMultisig) throw new CustomError("INVALID_TX", `Too many signatures in itx: maximum allowed is ${maxMultisig}`);
485
+ const txsList = getListField(itxObj, "txs");
486
+ const maxTxsLimit = Math.max(maxListSize, MAX_ROLLUP_TXS_LIST_SIZE);
487
+ if (Array.isArray(txsList) && txsList.length > maxTxsLimit) throw new CustomError("INVALID_TX_SIZE", `Size of txs can not exceeded ${maxTxsLimit} items`);
488
+ for (const urlListField of ["typeUrls", "deny"]) {
489
+ const list = getListField(itxObj, urlListField);
490
+ const limit = Math.max(maxListSize, MAX_DELEGATE_TYPE_URLS_LIST_SIZE);
491
+ if (Array.isArray(list) && list.length > limit) throw new CustomError("INVALID_TX_SIZE", `Size of ${urlListField} can not exceeded ${limit} items`);
492
+ }
493
+ inspectJsonStructure(itxObj, {
494
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
495
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
496
+ checkStrings: true,
497
+ enforceAntiBlobStorage: true,
498
+ maxAssetSize,
499
+ skipAntiBlobFieldNames: txType === "fg:t:create_token" || txType === "fg:t:create_token_factory" || txType === "fg:t:update_token_factory" ? new Set(["icon"]) : void 0
500
+ });
501
+ if (itxObj.data) inspectAnyDataEnvelope(itxObj.data, maxAssetSize);
502
+ const outputObj = itxObj.output;
503
+ if (outputObj && typeof outputObj === "object" && outputObj.data) inspectAnyDataEnvelope(outputObj.data, maxAssetSize);
504
+ const tokenObj = itxObj.token;
505
+ if (tokenObj && typeof tokenObj === "object" && tokenObj.metadata) inspectAnyDataEnvelope(tokenObj.metadata, maxAssetSize);
506
+ if (Array.isArray(txSignatures)) {
507
+ for (const sig of txSignatures) if (sig && typeof sig === "object") {
508
+ const sigRecord = sig;
509
+ if (typeof sigRecord.extra === "string" && sigRecord.extra.length > 0) inspectJsonStructure(sigRecord.extra, {
510
+ maxDepth: MAX_PREFLIGHT_JSON_DEPTH,
511
+ maxKeys: MAX_PREFLIGHT_JSON_KEYS,
512
+ checkStrings: true,
513
+ enforceAntiBlobStorage: true,
514
+ maxAssetSize
515
+ });
516
+ if (sigRecord.data) inspectAnyDataEnvelope(sigRecord.data, maxAssetSize);
517
+ }
518
+ }
519
+ }
520
+ /**
521
+ * Pipeline pipe that runs the Pre-Flight WAF structural & anomaly checks.
522
+ */
523
+ function PreFlightWaf(context, next) {
524
+ if (context._preFlightWafScanned) return next();
525
+ try {
526
+ if (context.txBase64 && typeof context.txBase64 === "string") assertRawWireEnvelope(context.txBase64, context.config);
527
+ const txSigs = context.tx ? getListField(context.tx, "signatures") : void 0;
528
+ scanItxPayloadAnomalies(context.itx, context.txType, context.config, context.tx?.itx, txSigs);
529
+ context._preFlightWafScanned = true;
530
+ return next();
531
+ } catch (err) {
532
+ return next(err);
533
+ }
534
+ }
535
+ /**
536
+ * Stateless, zero-DB-I/O Pre-Flight inspection runner for `OCAPResolver.sendTx`
537
+ * BEFORE enqueuing into the single-writer queue (`this.queue`) or acquiring the SQLite write lock.
538
+ */
539
+ async function inspectTransactionPreFlight(context) {
540
+ if (context.txBase64 && typeof context.txBase64 === "string") assertRawWireEnvelope(context.txBase64, context.config);
541
+ const rawTxBeforeDecode = context.tx?.itx;
542
+ const preFlightCtx = {
543
+ ...context,
544
+ timer: void 0,
545
+ logger: void 0
546
+ };
547
+ const runner = new runner_default("pre-flight-waf");
548
+ runner.use(DecodeTx);
549
+ if (context.filter) runner.use(CreatedVerifyBlockedPipe({
550
+ filter: context.filter,
551
+ stateKeys: ["tx.from"]
552
+ }));
553
+ runner.use((ctx, next) => {
554
+ ctx._rawTxItxBeforeNormalize = rawTxBeforeDecode ?? ctx.tx?.itx;
555
+ next();
556
+ });
557
+ runner.use(DecodeItx);
558
+ runner.use(VerifyTx);
559
+ runner.use(VerifyServiceFee);
560
+ runner.use(VerifyTxSize);
561
+ runner.use((ctx, next) => {
562
+ try {
563
+ const txSigs = ctx.tx ? getListField(ctx.tx, "signatures") : void 0;
564
+ scanItxPayloadAnomalies(ctx.itx, ctx.txType, ctx.config, ctx._rawTxItxBeforeNormalize ?? ctx.tx?.itx, txSigs);
565
+ ctx._preFlightWafScanned = true;
566
+ return next();
567
+ } catch (err) {
568
+ return next(err);
569
+ }
570
+ });
571
+ runner.use(VerifySignature);
572
+ return new Promise((resolve, reject) => {
573
+ runner.run(preFlightCtx, (err) => {
574
+ if (err) {
575
+ err._preFlightCtx = preFlightCtx;
576
+ return reject(err);
577
+ }
578
+ for (const key of [
579
+ "tx",
580
+ "txEncoding",
581
+ "txSize",
582
+ "txHash",
583
+ "unsignedTxHash",
584
+ "txTime",
585
+ "txBaseGas",
586
+ "itx",
587
+ "txType"
588
+ ]) if (preFlightCtx[key] !== void 0) Object.defineProperty(context, key, {
589
+ value: preFlightCtx[key],
590
+ enumerable: true,
591
+ configurable: true,
592
+ writable: true
593
+ });
594
+ context._extraSizeCounted = Boolean(preFlightCtx._extraSizeCounted);
595
+ context._preFlightWafScanned = true;
596
+ context._preFlightVerified = true;
597
+ resolve(context);
598
+ });
599
+ });
600
+ }
601
+
602
+ //#endregion
603
+ export { MAX_DELEGATE_TYPE_URLS_LIST_SIZE, MAX_PREFLIGHT_JSON_DEPTH, MAX_PREFLIGHT_JSON_KEYS, MAX_PREFLIGHT_STRING_FIELD_BYTES, MAX_PREFLIGHT_WIRE_BYTES_FALLBACK, MAX_ROLLUP_TXS_LIST_SIZE, assertKnownItxFields, assertRawWireEnvelope, PreFlightWaf as default, inspectTransactionPreFlight, scanItxPayloadAnomalies };
@@ -15,8 +15,9 @@ function CreateTakeStateSnapshotPipe({ key = "stateSnapshot" } = {}) {
15
15
  const ctx = context;
16
16
  if (ctx.tx?.from && ctx.senderState?.address && ctx.senderState.address !== ctx.tx.from && !isSameDid(ctx.senderState.address, ctx.tx.from)) return next(new CustomError("ACCOUNT_MIGRATED", "Cannot send tx from migrated account"));
17
17
  if (ctx.tx && !context.txType?.startsWith("fg:x:")) {
18
- if (ctx.tx.delegator && !ctx.delegationState && !ctx.isImplicitDelegation) return next(new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction"));
19
- if (getListField(ctx.tx, "signatures").some((s) => Boolean(s?.delegator)) && !ctx.delegationStates && !Array.isArray(ctx.delegationState)) return next(new CustomError("INVALID_DELEGATION", "Multisig delegation is not supported for this transaction"));
18
+ const isSelfDelegationProtocol = context.txType === "fg:t:delegate" || context.txType === "fg:t:revoke_delegate";
19
+ if (ctx.tx.delegator && (isSelfDelegationProtocol || !ctx.isDelegationVerified && !ctx.delegationState && !ctx.isImplicitDelegation)) return next(new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction"));
20
+ if (getListField(ctx.tx, "signatures").some((s) => Boolean(s?.delegator)) && (isSelfDelegationProtocol || !ctx.isMultiSigDelegationVerified && !ctx.delegationStates && !Array.isArray(ctx.delegationState))) return next(new CustomError("INVALID_DELEGATION", "Multisig delegation is not supported for this transaction"));
20
21
  }
21
22
  const [feeVaultState, gasVaultState] = await Promise.all([context.feeVault && !ctx.feeVaultState ? statedb.account.get(context.feeVault, context) : null, context.gasVault && !ctx.gasVaultState ? statedb.account.get(context.gasVault, context) : null]);
22
23
  if (feeVaultState) ctx.feeVaultState = feeVaultState;