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