@blockrun/franklin 3.49.6 → 3.49.8

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.
@@ -0,0 +1,821 @@
1
+ /**
2
+ * Payment hold — the code half of the "Ambiguous payment outcomes" rule.
3
+ *
4
+ * The system prompt tells the model that a timeout or 5xx after a send means
5
+ * UNKNOWN, not failed. An external audit (EmberTail, Franklin 3.49.6, 37
6
+ * sessions) showed the model does not reliably apply it: after a timeout or
7
+ * a 502 it rewrote the payment script and sent again (three double payments),
8
+ * or recorded the invoice as unpaid without checking. The exact-command dedup
9
+ * caught one resend out of four because it compares command text, and a
10
+ * rewritten script is different text.
11
+ *
12
+ * This module keys on what a Bash run DOES, not what it says:
13
+ * 1. A Bash run whose command — or the script file it runs — sends a
14
+ * transaction or payment is a payment attempt.
15
+ * 2. If that attempt ends in a timeout, a 5xx, a dropped connection, a
16
+ * missing receipt, an error after a tx hash was printed, or detaches to
17
+ * the background, its outcome is UNKNOWN. The tool result is annotated
18
+ * so the model sees that before it decides anything.
19
+ * 3. While an attempt is unknown, any new send that could pay the same
20
+ * recipient is held and goes to the user for an explicit decision; no
21
+ * approval surface (headless) = held. Rewording the script cannot get
22
+ * around this.
23
+ * 4. While an attempt is unknown and no read-only reconciliation (receipt,
24
+ * nonce, balance, status lookup) has run since, recording it as
25
+ * failed/unpaid is refused: the outcome has not been established.
26
+ *
27
+ * Pure detection helpers are exported for tests; SessionToolGuard owns the
28
+ * per-session state.
29
+ */
30
+ import fs from 'node:fs';
31
+ import path from 'node:path';
32
+ import { BLOCKRUN_DIR } from '../config.js';
33
+ // ─── Detection ─────────────────────────────────────────────────────────────
34
+ /**
35
+ * Code that signs-and-sends a transaction or pays for a request. Matched on
36
+ * the Bash command and on the script files it runs. Deliberately broad on
37
+ * the send side: a false positive costs one user prompt after an ambiguous
38
+ * failure; a false negative costs a second settlement.
39
+ */
40
+ const SEND_PATTERNS = [
41
+ // viem / ethers / web3.js / solana-web3
42
+ /\bsend(?:Raw)?Transaction\s*\(/,
43
+ /\bwriteContract\s*\(/,
44
+ /\bsendAndConfirm(?:Raw)?Transaction\s*\(/,
45
+ /\bsendUserOperation\s*\(/,
46
+ /\beth_send(?:Raw)?Transaction\b/,
47
+ // ERC-20 transfer through a contract object or a writeContract call
48
+ /\.\s*(?:transfer|transferFrom)\s*\(/,
49
+ /functionName\s*:\s*['"`](?:transfer|transferFrom|approve)['"`]/,
50
+ // web3.py
51
+ /\bsend_(?:raw_)?transaction\s*\(/,
52
+ /\.transact\s*\(/,
53
+ // CLIs
54
+ /\bcast\s+(?:send|publish)\b/,
55
+ /\bspl-token\s+transfer\b/,
56
+ /\bsolana\s+(?:transfer|pay)\b/,
57
+ // x402 / paid HTTP
58
+ /\bwrapFetchWithPayment\b/,
59
+ /\bwithPaymentInterceptor\b/,
60
+ /\bcreatePaymentHeader\b/,
61
+ /['"`]x-payment['"`]/i,
62
+ /\bx-payment\s*:/i,
63
+ ];
64
+ /** Read-only chain lookups that count as an attempt to reconcile. */
65
+ const RECONCILE_PATTERNS = [
66
+ /\bgetTransactionReceipt\b/,
67
+ /\bwaitForTransactionReceipt\b/,
68
+ /\bgetTransaction\s*\(/,
69
+ /\bgetTransactionCount\b/,
70
+ /\bgetBalance\b/,
71
+ /\bbalanceOf\b/,
72
+ /\bgetSignatureStatus(?:es)?\b/,
73
+ /\bgetParsedTransaction\b/,
74
+ /\beth_getTransaction(?:Receipt|ByHash|Count)\b/,
75
+ /\bget_transaction(?:_receipt|_count)?\s*\(/,
76
+ /\bcast\s+(?:receipt|tx|nonce|balance|call)\b/,
77
+ /\bspl-token\s+balance\b/,
78
+ /\bsolana\s+(?:balance|confirm)\b/,
79
+ ];
80
+ /**
81
+ * Outcome text that means "the response was lost", not "it failed". Kept
82
+ * specific: a bare `\b5\d\d\b` would fire on "500 USDC".
83
+ */
84
+ const AMBIGUOUS_OUTCOME_RE = new RegExp([
85
+ 'TimeoutError',
86
+ '\\btim(?:ed|e)\\s*out\\b',
87
+ '\\btimeout\\b',
88
+ 'ETIMEDOUT',
89
+ 'ESOCKETTIMEDOUT',
90
+ 'ECONNRESET',
91
+ 'ECONNABORTED',
92
+ 'ECONNREFUSED',
93
+ 'EPIPE',
94
+ 'EAI_AGAIN',
95
+ 'UND_ERR_\\w+',
96
+ 'socket hang up',
97
+ 'other side closed',
98
+ 'fetch failed',
99
+ 'network error',
100
+ 'HTTP\\s*/?\\s*(?:\\d(?:\\.\\d)?\\s+)?5\\d\\d',
101
+ 'status(?:\\s*code)?\\s*[:=]?\\s*5\\d\\d',
102
+ '\\b5\\d\\d\\s+(?:Bad Gateway|Internal Server Error|Service Unavailable|Gateway Time-?out)',
103
+ 'Bad Gateway',
104
+ 'Service Unavailable',
105
+ 'Gateway Time-?out',
106
+ 'upstream response lost',
107
+ 'response (?:was )?(?:unavailable|lost)',
108
+ 'TransactionReceiptNotFound',
109
+ 'WaitForTransactionReceiptTimeout',
110
+ 'receipt (?:not found|unavailable)',
111
+ 'command killed',
112
+ ].join('|'), 'i');
113
+ const TX_HASH_RE = /\b0x[0-9a-fA-F]{64}\b/g;
114
+ const EVM_ADDRESS_RE = /\b0x[0-9a-fA-F]{40}\b/g;
115
+ const QUOTED_BASE58_RE = /['"`]([1-9A-HJ-NP-Za-km-z]{32,44})['"`]/g;
116
+ /**
117
+ * Token / program contracts. They appear in nearly every payment script, so
118
+ * they say nothing about WHO is being paid and must not make two unrelated
119
+ * payments look like the same obligation.
120
+ */
121
+ const NON_RECIPIENT_ADDRESSES = new Set([
122
+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', // USDC (Base)
123
+ '0x036cbd53842c5426634e7929541ec2318f3dcf7e', // USDC (Base Sepolia)
124
+ '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', // USDT (Base)
125
+ '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359', // USDC (Polygon)
126
+ '0x2791bca1f2de4661ed88a30c99a7a9449aa84174', // USDC.e (Polygon)
127
+ '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC (Ethereum)
128
+ '0x4200000000000000000000000000000000000006', // WETH (Base)
129
+ '0x0000000000000000000000000000000000000000',
130
+ 'epjfwdd5aufqssqem2qn1xzybapc8g4wegggkzwytdt1v', // USDC (Solana)
131
+ 'es9vmfrzacerbmjfrf4h2fyd4kconky11mcce8benwnyb', // USDT (Solana)
132
+ 'tokenkegqfezyinwajbnbgkpfxcwubvf9ss623vq5da', // SPL Token program
133
+ '11111111111111111111111111111111', // System program
134
+ ]);
135
+ const SCRIPT_EXT_RE = /\.(?:m?[jt]s|cjs|cts|py|sh|bash)$/;
136
+ const SHELL_SCRIPT_RE = /\.(?:sh|bash)$/;
137
+ const MAX_SCRIPT_BYTES = 256 * 1024;
138
+ const MAX_SHELL_DEPTH = 3;
139
+ /** Commands that run the script file (or stdin) they are given. */
140
+ const INTERPRETERS = new Set([
141
+ 'node', 'nodejs', 'bun', 'deno', 'tsx', 'ts-node', 'ts-node-esm', 'esno', 'vite-node',
142
+ 'python', 'python2', 'python3', 'py', 'pypy', 'pypy3',
143
+ 'sh', 'bash', 'zsh', 'dash', 'ksh', 'source', '.',
144
+ ]);
145
+ const SHELL_INTERPRETERS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'source', '.']);
146
+ /** Prefixes that run the command after them: `timeout 30 node pay.mjs`. */
147
+ const WRAPPERS = new Set([
148
+ 'env', 'sudo', 'doas', 'exec', 'time', 'nohup', 'setsid', 'daemonize', 'nice', 'ionice', 'stdbuf',
149
+ 'timeout', 'npx', 'bunx', 'xargs', 'command',
150
+ ]);
151
+ /**
152
+ * Wrapper options that take a value (`env -u NAME`, `timeout --signal TERM`),
153
+ * so the value is not mistaken for the wrapped program.
154
+ */
155
+ const WRAPPER_VALUE_FLAGS = {
156
+ env: new Set(['-u', '--unset', '-C', '--chdir']),
157
+ timeout: new Set(['-s', '--signal', '-k', '--kill-after']),
158
+ nice: new Set(['-n', '--adjustment']),
159
+ ionice: new Set(['-c', '--class', '-n', '--classdata', '-p', '--pid', '-P', '--pgid', '-u', '--uid']),
160
+ stdbuf: new Set(['-i', '--input', '-o', '--output', '-e', '--error']),
161
+ sudo: new Set(['-u', '--user', '-g', '--group', '-C', '--close-from', '-D', '--chdir', '-h', '--host', '-p', '--prompt', '-U', '--other-user', '-r', '--role', '-t', '--type', '-T', '--command-timeout']),
162
+ doas: new Set(['-u', '-C']),
163
+ xargs: new Set(['-I', '-i', '-n', '--max-args', '-P', '--max-procs', '-L', '-l', '--max-lines', '-d', '--delimiter', '-E', '-e', '-s', '--max-chars', '-a', '--arg-file']),
164
+ npx: new Set(['-p', '--package']),
165
+ bunx: new Set(['-p', '--package']),
166
+ };
167
+ /** Wrapper options that change directory before running the program. */
168
+ const CHDIR_FLAGS = {
169
+ env: new Set(['-C', '--chdir']),
170
+ sudo: new Set(['-D', '--chdir']),
171
+ };
172
+ /** Wrapper options whose value is itself a shell command: `env -S "node pay.mjs"`, `npx -c "…"`. */
173
+ const WRAPPER_COMMAND_FLAGS = {
174
+ env: new Set(['-S', '--split-string']),
175
+ npx: new Set(['-c', '--call']),
176
+ };
177
+ /** Two-word prefixes: `pnpm dlx tsx pay.ts`, `uv run python pay.py`. */
178
+ const WRAPPER_PAIRS = new Set(['pnpm dlx', 'pnpm exec', 'npm exec', 'yarn dlx', 'yarn exec', 'uv run', 'poetry run', 'pipenv run', 'bun run', 'deno run']);
179
+ function isInterpreter(word) {
180
+ const base = path.basename(word);
181
+ return INTERPRETERS.has(base) || /^python\d+(?:\.\d+)?$/.test(base);
182
+ }
183
+ function expandHome(p) {
184
+ return p.replace(/^~(?=\/|$)/, process.env.HOME ?? '~');
185
+ }
186
+ /**
187
+ * Split shell text into simple commands, honoring single/double quotes and
188
+ * backslash escapes. Separators: newline ; & && | || ( ) $( ` . Output
189
+ * redirects drop their target word (`> pay.mjs` writes the file, it does not
190
+ * run it); input redirects and pipes are kept, because an interpreter reading
191
+ * stdin runs whatever arrives there.
192
+ */
193
+ export function splitShellCommands(text) {
194
+ const commands = [];
195
+ const fresh = (pipedFrom = null) => ({ words: [], stdinFiles: [], hereStrings: [], pipedFrom, background: false, writesFile: false, outFiles: [] });
196
+ let current = fresh();
197
+ let word = '';
198
+ let inWord = false;
199
+ let target = 'word';
200
+ const endWord = () => {
201
+ if (inWord) {
202
+ if (target === 'word')
203
+ current.words.push(word);
204
+ else if (target === 'stdin')
205
+ current.stdinFiles.push(word);
206
+ else if (target === 'herestring')
207
+ current.hereStrings.push(word);
208
+ else if (target === 'outfile')
209
+ current.outFiles.push(word);
210
+ target = 'word';
211
+ }
212
+ word = '';
213
+ inWord = false;
214
+ };
215
+ const endCommand = (opts = {}) => {
216
+ endWord();
217
+ target = 'word';
218
+ current.background = Boolean(opts.background);
219
+ const done = current.words.length || current.stdinFiles.length || current.hereStrings.length ? current : null;
220
+ if (done)
221
+ commands.push(done);
222
+ current = fresh(opts.pipe ? done : null);
223
+ };
224
+ for (let i = 0; i < text.length; i++) {
225
+ const c = text[i];
226
+ if (c === '\\' && i + 1 < text.length) {
227
+ if (text[i + 1] !== '\n')
228
+ word += text[i + 1];
229
+ inWord = true;
230
+ i++;
231
+ }
232
+ else if (c === "'") {
233
+ const close = text.indexOf("'", i + 1);
234
+ const end = close === -1 ? text.length : close;
235
+ word += text.slice(i + 1, end);
236
+ inWord = true;
237
+ i = end;
238
+ }
239
+ else if (c === '"') {
240
+ i++;
241
+ while (i < text.length && text[i] !== '"') {
242
+ if (text[i] === '\\' && i + 1 < text.length && '"\\$`'.includes(text[i + 1]))
243
+ i++;
244
+ word += text[i];
245
+ i++;
246
+ }
247
+ inWord = true;
248
+ }
249
+ else if (c === ' ' || c === '\t') {
250
+ endWord();
251
+ }
252
+ else if (c === '|') {
253
+ if (text[i + 1] === '|') {
254
+ i++;
255
+ endCommand();
256
+ }
257
+ else {
258
+ if (text[i + 1] === '&')
259
+ i++;
260
+ endCommand({ pipe: true });
261
+ }
262
+ }
263
+ else if (c === '&') {
264
+ if (text[i + 1] === '&') {
265
+ i++;
266
+ endCommand();
267
+ }
268
+ else if (text[i + 1] === '>') {
269
+ // `&>file` / `&>>file`: redirect both streams to a file.
270
+ endWord();
271
+ while (text[i + 1] === '>')
272
+ i++;
273
+ target = 'outfile';
274
+ current.writesFile = true;
275
+ }
276
+ else {
277
+ endCommand({ background: true });
278
+ }
279
+ }
280
+ else if (c === '\n' || c === ';' || c === '(' || c === ')' || c === '`') {
281
+ endCommand();
282
+ }
283
+ else if (c === '$' && text[i + 1] === '(') {
284
+ endCommand();
285
+ i++;
286
+ }
287
+ else if (c === '>' || c === '<') {
288
+ // `2>` / `0<`: a bare fd number glued to the operator is not a word.
289
+ if (inWord && /^\d+$/.test(word)) {
290
+ word = '';
291
+ inWord = false;
292
+ }
293
+ endWord();
294
+ let run = 1;
295
+ while (text[i + 1] === c) {
296
+ i++;
297
+ run++;
298
+ }
299
+ if (text[i + 1] === '&') {
300
+ // `>&2` duplicates a descriptor; there is no file target.
301
+ i++;
302
+ while (/\d/.test(text[i + 1] ?? ''))
303
+ i++;
304
+ }
305
+ else if (c === '<') {
306
+ // `<` stdin file, `<<` heredoc delimiter (body handled separately), `<<<` here-string.
307
+ target = run === 1 ? 'stdin' : run === 2 ? 'skip' : 'herestring';
308
+ }
309
+ else {
310
+ target = 'outfile';
311
+ current.writesFile = true;
312
+ }
313
+ }
314
+ else {
315
+ word += c;
316
+ inWord = true;
317
+ }
318
+ }
319
+ endCommand();
320
+ return commands;
321
+ }
322
+ /** Files a command writes or replaces through its own arguments. */
323
+ function filesWrittenBy(words) {
324
+ const base = path.basename(words[0] ?? '');
325
+ const args = words.slice(1);
326
+ const positional = args.filter(w => !w.startsWith('-'));
327
+ if (base === 'tee')
328
+ return positional;
329
+ if (base === 'cp' || base === 'mv' || base === 'install' || base === 'ln' || base === 'rsync')
330
+ return positional.slice(-1);
331
+ if (base === 'sed' && args.some(w => /^-i/.test(w) || w === '--in-place'))
332
+ return positional.slice(1);
333
+ if (base === 'curl' || base === 'wget') {
334
+ const out = [];
335
+ args.forEach((w, k) => {
336
+ if ((w === '-o' || w === '--output' || w === '-O' || w === '--output-document') && args[k + 1])
337
+ out.push(args[k + 1]);
338
+ });
339
+ return out;
340
+ }
341
+ return [];
342
+ }
343
+ /** An HTTP CLI call that sends a body or uses a write method. */
344
+ function isHttpWrite(words) {
345
+ const base = path.basename(words[0] ?? '');
346
+ if (base === 'curl') {
347
+ return words.some((w, k) => /^(?:-d|--data(?:-raw|-binary|-urlencode)?|--json|-F|--form|-T|--upload-file)$/.test(w) ||
348
+ /^--(?:data|json)/.test(w) ||
349
+ ((w === '-X' || w === '--request') && /^(?:POST|PUT|PATCH)$/i.test(words[k + 1] ?? '')) ||
350
+ /^-X(?:POST|PUT|PATCH)$/i.test(w));
351
+ }
352
+ if (base === 'wget')
353
+ return words.some(w => /^--(?:post|body)-(?:data|file)/.test(w) || /^--method=(?:POST|PUT|PATCH)$/i.test(w));
354
+ if (base === 'http' || base === 'https' || base === 'xh')
355
+ return words.some(w => /^(?:POST|PUT|PATCH)$/i.test(w) || /[:=]=?/.test(w) && !/^https?:/.test(w));
356
+ return false;
357
+ }
358
+ /** Commands that pass a file's contents through to stdout unchanged. */
359
+ const FILE_PASSTHROUGH = new Set(['cat', 'head', 'tail', 'tac', 'less', 'more']);
360
+ /**
361
+ * Commands that only read or print. Their arguments are not a record unless
362
+ * the output is redirected into a file: `grep unpaid ledger.json` reads,
363
+ * `echo unpaid > ledger.txt` writes.
364
+ */
365
+ const NON_RECORDING = new Set([
366
+ 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'cat', 'head', 'tail', 'less', 'more', 'wc', 'ls', 'find',
367
+ 'jq', 'yq', 'sort', 'uniq', 'cut', 'diff', 'file', 'stat', 'echo', 'printf', 'test', '[', 'true',
368
+ 'false', 'pwd', 'which', 'type', 'date', 'git',
369
+ ]);
370
+ /** Commands that detach what they run from the shell call. */
371
+ const DETACHERS = new Set(['nohup', 'setsid', 'disown', 'daemonize']);
372
+ /** Subcommands of chain CLIs that sign and send. */
373
+ const CLI_SEND_SUBCOMMANDS = {
374
+ cast: ['send', 'publish'],
375
+ solana: ['transfer', 'pay'],
376
+ 'spl-token': ['transfer'],
377
+ };
378
+ /** CLIs whose arguments are a chain or RPC lookup in their own right. */
379
+ const CHAIN_CLIS = new Set(['cast', 'solana', 'spl-token', 'curl', 'wget', 'http', 'https', 'xh']);
380
+ /** Interpreter flags whose next word is a value, not the script. */
381
+ const VALUE_FLAGS = new Set([
382
+ '-r', '--require', '--import', '--loader', '--experimental-loader', '--input-type', '--conditions', '-C',
383
+ '-W', '-X', '--env-file',
384
+ ]);
385
+ /** Interpreter flags whose next word is inline code. */
386
+ const INLINE_CODE_FLAGS = new Set(['-e', '--eval', '-p', '--print', '-c']);
387
+ /** What one simple command runs, after env assignments and wrappers like `timeout` or `npx`. */
388
+ function analyzeCommand(words) {
389
+ const run = { scripts: [], interpreter: null, inlineCode: [], inlineShell: [], cli: null, chdir: null };
390
+ let i = 0;
391
+ const skipAssignmentsAndFlags = () => {
392
+ while (i < words.length && (/^[A-Za-z_]\w*=/.test(words[i]) || words[i].startsWith('-')))
393
+ i++;
394
+ };
395
+ while (i < words.length && /^[A-Za-z_]\w*=/.test(words[i]))
396
+ i++;
397
+ for (let guard = 0; guard < 8 && i < words.length; guard++) {
398
+ const base = path.basename(words[i]);
399
+ if (WRAPPER_PAIRS.has(`${base} ${words[i + 1] ?? ''}`)) {
400
+ i += 2;
401
+ skipAssignmentsAndFlags();
402
+ continue;
403
+ }
404
+ if (WRAPPERS.has(base)) {
405
+ i++;
406
+ // Options (and their values), assignments and bare numbers:
407
+ // `timeout --signal TERM 30`, `nice -n 5`, `env -u X FOO=1`, `sudo -u bob --`.
408
+ const valueFlags = WRAPPER_VALUE_FLAGS[base];
409
+ const commandFlags = WRAPPER_COMMAND_FLAGS[base];
410
+ while (i < words.length) {
411
+ const w = words[i];
412
+ if (w === '--') {
413
+ i++;
414
+ break;
415
+ }
416
+ if (commandFlags?.has(w)) {
417
+ if (words[i + 1] !== undefined)
418
+ run.inlineShell.push(words[i + 1]);
419
+ return run;
420
+ }
421
+ const eq = /^(--?[\w-]+)=([\s\S]*)$/.exec(w);
422
+ if (eq && commandFlags?.has(eq[1])) {
423
+ run.inlineShell.push(eq[2]);
424
+ return run;
425
+ }
426
+ if (eq && CHDIR_FLAGS[base]?.has(eq[1])) {
427
+ run.chdir = eq[2];
428
+ i++;
429
+ continue;
430
+ }
431
+ if (valueFlags?.has(w)) {
432
+ if (CHDIR_FLAGS[base]?.has(w) && words[i + 1] !== undefined)
433
+ run.chdir = words[i + 1];
434
+ i += 2;
435
+ continue;
436
+ }
437
+ // Glued short option with value: `-uNODE_OPTIONS`, `-n5`, `-oL`.
438
+ if (/^[A-Za-z_]\w*=/.test(w) || w.startsWith('-') || /^\d+(?:\.\d+)?[smhd]?$/.test(w)) {
439
+ i++;
440
+ continue;
441
+ }
442
+ break;
443
+ }
444
+ continue;
445
+ }
446
+ break;
447
+ }
448
+ const cmd = words[i];
449
+ if (!cmd)
450
+ return run;
451
+ const base = path.basename(cmd);
452
+ if (base === 'eval') {
453
+ run.inlineShell.push(words.slice(i + 1).join(' '));
454
+ return run;
455
+ }
456
+ if (CHAIN_CLIS.has(base)) {
457
+ // Global options can sit between the CLI and its subcommand
458
+ // (`solana --url mainnet-beta transfer …`). Name the money-moving
459
+ // subcommand explicitly so the send patterns see `solana transfer`.
460
+ const args = words.slice(i + 1);
461
+ const sub = CLI_SEND_SUBCOMMANDS[base]?.find(name => args.includes(name));
462
+ run.cli = (sub ? `${base} ${sub}\n` : '') + words.slice(i).join(' ');
463
+ return run;
464
+ }
465
+ if (SCRIPT_EXT_RE.test(cmd)) {
466
+ run.scripts.push(cmd);
467
+ return run;
468
+ }
469
+ if (!isInterpreter(cmd))
470
+ return run;
471
+ run.interpreter = base;
472
+ const isShell = SHELL_INTERPRETERS.has(base);
473
+ for (let j = i + 1; j < words.length; j++) {
474
+ const w = words[j];
475
+ // `bash -lc CMD`, `sh -ec CMD`: a short-flag cluster ending in c.
476
+ const shellInline = isShell && /^-[a-zA-Z]*c$/.test(w);
477
+ if (shellInline || INLINE_CODE_FLAGS.has(w)) {
478
+ const code = words[j + 1];
479
+ if (code !== undefined)
480
+ (isShell ? run.inlineShell : run.inlineCode).push(code);
481
+ return run;
482
+ }
483
+ const eq = /^(--eval|--print)=([\s\S]*)$/.exec(w);
484
+ if (eq) {
485
+ run.inlineCode.push(eq[2]);
486
+ return run;
487
+ }
488
+ // `python3 -m pkg`: a module, not a file.
489
+ if (w === '-m')
490
+ return run;
491
+ if (VALUE_FLAGS.has(w)) {
492
+ j++;
493
+ continue;
494
+ }
495
+ if (w.startsWith('-'))
496
+ continue;
497
+ // The first positional is the program; later ones are its arguments.
498
+ if (SCRIPT_EXT_RE.test(w) || isShell)
499
+ run.scripts.push(w);
500
+ return run;
501
+ }
502
+ return run;
503
+ }
504
+ /** Pull heredoc bodies out so their contents are not mistaken for shell. */
505
+ function extractHeredocs(text) {
506
+ const lines = text.split('\n');
507
+ const out = [];
508
+ const heredocs = [];
509
+ for (let i = 0; i < lines.length; i++) {
510
+ const line = lines[i];
511
+ out.push(line);
512
+ const markers = [...line.matchAll(/<<(-?)\s*(['"]?)([A-Za-z_][\w.-]*)\2/g)];
513
+ for (const m of markers) {
514
+ const stripTabs = m[1] === '-';
515
+ const delim = m[3];
516
+ const body = [];
517
+ i++;
518
+ while (i < lines.length) {
519
+ const candidate = stripTabs ? lines[i].replace(/^\t+/, '') : lines[i];
520
+ if (candidate === delim)
521
+ break;
522
+ body.push(lines[i]);
523
+ i++;
524
+ }
525
+ const before = line.slice(0, m.index);
526
+ const head = before.split(/;|&&|\|\||\||\(|\$\(/).pop() ?? '';
527
+ heredocs.push({ head, tail: line.slice((m.index ?? 0) + m[0].length), body: body.join('\n') });
528
+ }
529
+ }
530
+ return { shell: out.join('\n'), heredocs };
531
+ }
532
+ function readScript(resolved) {
533
+ try {
534
+ const stat = fs.statSync(resolved);
535
+ if (!stat.isFile() || stat.size > MAX_SCRIPT_BYTES)
536
+ return null;
537
+ return fs.readFileSync(resolved, 'utf-8');
538
+ }
539
+ catch {
540
+ return null;
541
+ }
542
+ }
543
+ function collect(command, cwd, depth, out, seen) {
544
+ const { shell, heredocs } = extractHeredocs(command);
545
+ // A heredoc is code when an interpreter reads it (`node <<EOF`, `cat <<EOF | python3`).
546
+ // Otherwise it is data — usually a file being written (`cat > pay.mjs <<EOF`),
547
+ // which counts as code if this same command then runs that file.
548
+ const writtenFiles = new Map();
549
+ for (const doc of heredocs) {
550
+ const headRun = analyzeCommand(splitShellCommands(doc.head).pop()?.words ?? []);
551
+ const pipeRun = /\|/.test(doc.tail)
552
+ ? analyzeCommand(splitShellCommands(doc.tail.replace(/^[^|]*\|/, '')).shift()?.words ?? [])
553
+ : null;
554
+ const interp = headRun.interpreter ?? pipeRun?.interpreter ?? null;
555
+ if (interp) {
556
+ if (SHELL_INTERPRETERS.has(interp)) {
557
+ if (depth < MAX_SHELL_DEPTH)
558
+ collect(doc.body, cwd, depth + 1, out, seen);
559
+ else
560
+ out.code.push(doc.body);
561
+ }
562
+ else {
563
+ out.code.push(doc.body);
564
+ }
565
+ continue;
566
+ }
567
+ out.data.push(doc.body);
568
+ const target = /(?:>>?|\btee\s+(?:-a\s+)?)\s*(['"]?)([^\s'";&|<>]+)\1/.exec(doc.head + doc.tail);
569
+ if (target)
570
+ writtenFiles.set(path.basename(expandHome(target[2])), doc.body);
571
+ }
572
+ const commands = splitShellCommands(shell);
573
+ // Files this same command writes or replaces before (or while) running
574
+ // things: their on-disk contents are stale, so the command text that writes
575
+ // them is evidence too.
576
+ const modified = new Set([...writtenFiles.keys()]);
577
+ for (const c of commands) {
578
+ for (const f of c.outFiles)
579
+ modified.add(path.basename(expandHome(f)));
580
+ for (const f of filesWrittenBy(c.words))
581
+ modified.add(path.basename(expandHome(f)));
582
+ }
583
+ for (const simple of commands) {
584
+ const { words } = simple;
585
+ if (words[0] === 'cd' || words[0] === 'pushd') {
586
+ const dir = words.slice(1).find(w => !w.startsWith('-'));
587
+ cwd = dir ? path.resolve(cwd, expandHome(dir)) : (process.env.HOME ?? cwd);
588
+ continue;
589
+ }
590
+ const run = analyzeCommand(words);
591
+ const runsSomething = Boolean(run.interpreter || run.cli || run.scripts.length || run.inlineCode.length || run.inlineShell.length);
592
+ if (simple.background || words.some(w => DETACHERS.has(path.basename(w))))
593
+ out.detached = true;
594
+ if (!runsSomething && (simple.writesFile || !NON_RECORDING.has(path.basename(words[0] ?? '')))) {
595
+ out.data.push(words.join(' '));
596
+ }
597
+ // A program whose output goes into a file writes what it prints
598
+ // (`node -e 'console.log("unpaid")' > ledger.txt`), and an HTTP call
599
+ // with a body or a write method sends what it carries. A send's own
600
+ // text is left out: its error messages are not outcome records.
601
+ const httpWrite = Boolean(run.cli && isHttpWrite(words));
602
+ if (runsSomething && (simple.writesFile || httpWrite)) {
603
+ const own = [words.join(' '), ...run.inlineCode];
604
+ for (const t of own)
605
+ if (!isPaymentSend(t))
606
+ out.data.push(t);
607
+ }
608
+ // An interpreter with no program argument runs its stdin: `node < pay.mjs`,
609
+ // `cat pay.mjs | node`, `python3 <<< "code"`.
610
+ if (run.interpreter && !run.scripts.length && !run.inlineCode.length && !run.inlineShell.length) {
611
+ run.scripts.push(...simple.stdinFiles);
612
+ const source = simple.pipedFrom;
613
+ if (source && FILE_PASSTHROUGH.has(path.basename(source.words[0] ?? ''))) {
614
+ run.scripts.push(...source.words.slice(1).filter(w => !w.startsWith('-') && !/^\d+$/.test(w)));
615
+ }
616
+ for (const hs of simple.hereStrings) {
617
+ if (SHELL_INTERPRETERS.has(run.interpreter))
618
+ run.inlineShell.push(hs);
619
+ else
620
+ run.inlineCode.push(hs);
621
+ }
622
+ }
623
+ const runDir = run.chdir ? path.resolve(cwd, expandHome(run.chdir)) : cwd;
624
+ for (const code of run.inlineCode)
625
+ out.code.push(code);
626
+ if (run.cli)
627
+ out.code.push(run.cli);
628
+ for (const inner of run.inlineShell) {
629
+ // `bash -c "node pay.mjs"` runs in the caller's directory.
630
+ if (depth < MAX_SHELL_DEPTH)
631
+ collect(inner, runDir, depth + 1, out, seen);
632
+ else
633
+ out.code.push(inner);
634
+ }
635
+ for (const script of run.scripts) {
636
+ const name = expandHome(script);
637
+ const fresh = writtenFiles.get(path.basename(name));
638
+ if (fresh !== undefined)
639
+ out.code.push(fresh);
640
+ else if (modified.has(path.basename(name)))
641
+ out.code.push(command);
642
+ const resolved = path.resolve(runDir, name);
643
+ if (seen.has(resolved))
644
+ continue;
645
+ seen.add(resolved);
646
+ const content = readScript(resolved);
647
+ if (content === null) {
648
+ // Not on disk yet (written earlier in this same command by echo,
649
+ // printf or a heredoc): the whole command is the best evidence.
650
+ if (fresh === undefined)
651
+ out.code.push(command);
652
+ continue;
653
+ }
654
+ if (SHELL_SCRIPT_RE.test(resolved) || (run.interpreter && SHELL_INTERPRETERS.has(run.interpreter))) {
655
+ // `bash scripts/run.sh` runs with the CALLER's working directory, not
656
+ // the script's own: relative paths inside resolve from here.
657
+ if (depth < MAX_SHELL_DEPTH)
658
+ collect(content, runDir, depth + 1, out, seen);
659
+ else
660
+ out.code.push(content);
661
+ }
662
+ else {
663
+ out.code.push(content);
664
+ if (simple.writesFile && !isPaymentSend(content))
665
+ out.data.push(content);
666
+ }
667
+ }
668
+ }
669
+ }
670
+ /**
671
+ * What a Bash run will actually execute: the shell text, heredocs an
672
+ * interpreter reads, inline programs (`node -e`, `bash -c`, `eval`), chain
673
+ * CLI calls, and the contents of every local script file it runs — resolved
674
+ * through `cd`, quoting and wrappers like `timeout` or `npx`. A model that
675
+ * writes `pay.mjs` and then runs `bash -c 'node "pay scripts/pay.mjs"'` must
676
+ * not slip past a check that only reads the command line; a command that
677
+ * merely reads or writes a script (`cat pay.mjs`, `printf … > check.mjs`)
678
+ * must not count as running it.
679
+ */
680
+ export function analyzeBash(command, workingDir) {
681
+ const out = { code: [], data: [], detached: false };
682
+ collect(command, workingDir, 0, out, new Set());
683
+ return { code: out.code.join('\n'), data: out.data.join('\n'), detached: out.detached };
684
+ }
685
+ export function bashExecutedText(command, workingDir) {
686
+ return analyzeBash(command, workingDir).code;
687
+ }
688
+ export function isPaymentSend(text) {
689
+ return SEND_PATTERNS.some(re => re.test(text));
690
+ }
691
+ export function isReconciliation(text) {
692
+ return !isPaymentSend(text) && RECONCILE_PATTERNS.some(re => re.test(text));
693
+ }
694
+ /** Addresses that may identify who is being paid, lower-cased. */
695
+ export function extractRecipients(text, ownAddresses = []) {
696
+ const own = new Set(ownAddresses.map(a => a.toLowerCase()));
697
+ const found = new Set();
698
+ for (const m of text.matchAll(EVM_ADDRESS_RE))
699
+ found.add(m[0].toLowerCase());
700
+ for (const m of text.matchAll(QUOTED_BASE58_RE))
701
+ found.add(m[1].toLowerCase());
702
+ return [...found].filter(a => !NON_RECIPIENT_ADDRESSES.has(a) && !own.has(a));
703
+ }
704
+ /**
705
+ * Why a payment attempt's outcome is unknown, or null when the result is
706
+ * conclusive (clean success, or an error with no sign anything was sent).
707
+ */
708
+ export function ambiguousOutcomeReason(output, isError, ranInBackground) {
709
+ if (ranInBackground)
710
+ return 'it was detached to the background, so its result was never observed';
711
+ const marker = AMBIGUOUS_OUTCOME_RE.exec(output);
712
+ if (marker)
713
+ return `the run ended with "${marker[0].trim()}"`;
714
+ if (isError && TX_HASH_RE.test(output)) {
715
+ TX_HASH_RE.lastIndex = 0;
716
+ return 'it errored after a transaction hash was produced';
717
+ }
718
+ TX_HASH_RE.lastIndex = 0;
719
+ return null;
720
+ }
721
+ export function extractTxHashes(output) {
722
+ return [...new Set([...output.matchAll(TX_HASH_RE)].map(m => m[0]))];
723
+ }
724
+ /**
725
+ * Recording an outcome as failed / unpaid. Matched against the input of
726
+ * non-read tools (an outcome tool, a ledger write, a memory note) while an
727
+ * attempt is unknown.
728
+ */
729
+ const NEGATIVE_OUTCOME_RE = new RegExp([
730
+ '\\bunpaid\\b',
731
+ '\\bnot\\s+(?:been\\s+)?paid\\b',
732
+ '\\b(?:payment|transfer|transaction|tx|send)\\s+(?:has\\s+|was\\s+)?failed\\b',
733
+ '\\bfailed\\s+(?:payment|transfer|transaction)\\b',
734
+ '["\']?(?:status|outcome|result|state)["\']?\\s*[:=]\\s*["\']?(?:failed|failure|unpaid|not_paid|not paid)\\b',
735
+ ].join('|'), 'i');
736
+ export function recordsNegativeOutcome(text) {
737
+ return NEGATIVE_OUTCOME_RE.test(text);
738
+ }
739
+ /** Code that persists something: a file, a database row, or a write request. */
740
+ const PERSIST_RE = new RegExp([
741
+ '\\b(?:writeFile|appendFile)(?:Sync)?\\b',
742
+ '\\bcreateWriteStream\\b',
743
+ '\\bfs\\.(?:promises\\.)?write',
744
+ '\\.write(?:_text|_bytes)?\\s*\\(',
745
+ '\\bopen\\s*\\([^)]*[\'"][wax]\\+?b?[\'"]',
746
+ '\\bjson\\.dump\\s*\\(',
747
+ '\\bINSERT\\s+INTO\\b',
748
+ '\\bUPDATE\\s+\\w+\\s+SET\\b',
749
+ 'method\\s*:\\s*[\'"](?:POST|PUT|PATCH)[\'"]',
750
+ '\\brequests\\.(?:post|put|patch)\\s*\\(',
751
+ '\\baxios\\.(?:post|put|patch)\\s*\\(',
752
+ ].join('|'), 'i');
753
+ /**
754
+ * Whether code a Bash run executes records a failed/unpaid outcome: it
755
+ * persists something AND carries a negative outcome. A lookup that merely
756
+ * prints `paid` / `unpaid` writes nothing and passes; a ledger script that
757
+ * writes `{"status":"unpaid"}` does not.
758
+ */
759
+ export function codeRecordsNegativeOutcome(code) {
760
+ return PERSIST_RE.test(code) && NEGATIVE_OUTCOME_RE.test(code);
761
+ }
762
+ export function attemptsOverlap(a, b) {
763
+ if (a.length === 0 || b.length === 0)
764
+ return true;
765
+ const set = new Set(a);
766
+ return b.some(x => set.has(x));
767
+ }
768
+ export function commandPreview(command) {
769
+ const flat = command.replace(/\s+/g, ' ').trim();
770
+ return flat.length > 160 ? flat.slice(0, 157) + '...' : flat;
771
+ }
772
+ export function describeAttempt(a) {
773
+ const who = a.recipients.length ? a.recipients.join(', ') : 'recipient not identifiable';
774
+ const hashes = a.txHashes.length ? `; tx hash(es) seen: ${a.txHashes.join(', ')}` : '; no tx hash was printed';
775
+ return `#${a.id} (${who}) — ${a.reason}${hashes}. Command: ${a.command}`;
776
+ }
777
+ export function unknownOutcomeNotice(a) {
778
+ return [
779
+ '',
780
+ '',
781
+ `[Franklin payment guard] OUTCOME UNKNOWN — payment attempt ${describeAttempt(a)}`,
782
+ 'This is NOT a failure. The transaction may have been broadcast and may settle (or already have settled).',
783
+ '- Do not send another payment for this obligation. Franklin will hold any new send to the same recipient until the user decides.',
784
+ '- Reconcile first with READ-ONLY checks: the receipt for any tx hash above, the sender\'s nonce, and the sender/recipient token balances (or the venue\'s status endpoint).',
785
+ '- Do not record this payment as failed or unpaid unless a reconciliation proves it did not settle. If you cannot establish the outcome, record it as UNKNOWN and tell the user exactly what is unknown.',
786
+ ].join('\n');
787
+ }
788
+ // ─── Persistence ───────────────────────────────────────────────────────────
789
+ //
790
+ // An unknown outcome must survive the process: `franklin --resume` rebuilds
791
+ // the guard, and a hold that lived only in memory would let the very next
792
+ // rewritten send through. One JSON file per session id.
793
+ export function paymentHoldsDir() {
794
+ return path.join(BLOCKRUN_DIR, 'payment-holds');
795
+ }
796
+ function holdsPath(sessionId) {
797
+ return path.join(paymentHoldsDir(), `${sessionId.replace(/[^\w.-]/g, '_')}.json`);
798
+ }
799
+ export function loadPaymentAttempts(sessionId) {
800
+ try {
801
+ const raw = JSON.parse(fs.readFileSync(holdsPath(sessionId), 'utf-8'));
802
+ if (!Array.isArray(raw.attempts))
803
+ return [];
804
+ return raw.attempts.filter((a) => !!a && typeof a === 'object' && typeof a.id === 'number' && Array.isArray(a.recipients)).map(a => ({ ...a, senders: Array.isArray(a.senders) ? a.senders : [], txHashes: Array.isArray(a.txHashes) ? a.txHashes : [] }));
805
+ }
806
+ catch {
807
+ return [];
808
+ }
809
+ }
810
+ export function savePaymentAttempts(sessionId, attempts) {
811
+ try {
812
+ fs.mkdirSync(paymentHoldsDir(), { recursive: true });
813
+ const file = holdsPath(sessionId);
814
+ const tmp = `${file}.${process.pid}.tmp`;
815
+ fs.writeFileSync(tmp, JSON.stringify({ sessionId, attempts }, null, 2));
816
+ fs.renameSync(tmp, file);
817
+ }
818
+ catch {
819
+ /* best-effort: the in-memory hold still applies for this process */
820
+ }
821
+ }