@blockrun/franklin 3.29.9 → 3.29.10

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.
@@ -83,9 +83,10 @@ const SAFE_COMMANDS = new Set([
83
83
  'pwd', 'realpath', 'dirname', 'basename',
84
84
  // Text processing (read-only when not redirecting)
85
85
  'jq', 'yq', 'sort', 'uniq', 'cut', 'tr', 'diff', 'comm', 'less', 'more',
86
- 'wc', 'tee',
87
- // NB: `xargs` is intentionally NOT here — it executes an arbitrary wrapped
88
- // command (`... | xargs rm -f`), so it must never auto-approve as "safe".
86
+ 'wc',
87
+ // NB: `xargs` and `tee` are intentionally NOT here — xargs executes an
88
+ // arbitrary wrapped command (`... | xargs rm -f`) and tee WRITES files
89
+ // (`echo evil | tee ~/.zshrc`), so neither may auto-approve as "safe".
89
90
  ]);
90
91
  const SAFE_GIT_SUBCOMMANDS = new Set([
91
92
  'status', 'log', 'diff', 'show', 'branch', 'tag', 'remote',
@@ -127,10 +128,19 @@ export function classifyBashRisk(command) {
127
128
  return { level: 'normal' };
128
129
  }
129
130
  function isSegmentSafe(segment) {
130
- // Never auto-approve a command that touches the wallet private key — a bare
131
- // `cat ~/.blockrun/.solana-session` would dump the key into model context with
132
- // no prompt. Force a permission prompt (>= normal) for any key-file reference.
133
- if (/\.blockrun[/\\](?:\.session|\.solana-session|\.solana-session-key2|solana-wallet\.json)\b/.test(segment)) {
131
+ // Never auto-approve a command that touches the wallet key store. Matching the
132
+ // FILENAME is hopeless — it's trivially obfuscated (`.solana""-session`,
133
+ // `.\solana-session`, a glob, or an unlisted key file like
134
+ // solana-wallet-key2.json). So match the DIRECTORY: any reference to
135
+ // ~/.blockrun forces a prompt. (The file Read/Write/Edit tools have a separate
136
+ // canonicalized guard; this is the best-effort net for the shell. Over-
137
+ // prompting on a stray `.blockrun` path is fine — it prompts, never blocks.)
138
+ if (/\.blockrun/i.test(segment)) {
139
+ return false;
140
+ }
141
+ // Relative reads with no `.blockrun` in the text (e.g. the cwd is the wallet
142
+ // dir): match the known key/secret basenames broadly (any *wallet*.json/.key).
143
+ if (/(?<![\w-])(?:\.solana-session(?:-key2)?|\.session|[\w-]*wallet[\w-]*\.(?:json|key))(?![\w-])/i.test(segment)) {
134
144
  return false;
135
145
  }
136
146
  // Parse: strip env vars, extract command and args
@@ -165,13 +175,29 @@ function isSegmentSafe(segment) {
165
175
  // rtk (RTK wrapper — safe, it's a proxy)
166
176
  if (baseName === 'rtk')
167
177
  return true;
178
+ // `find` is read-only EXCEPT its action predicates, which execute arbitrary
179
+ // commands or delete files (`find / -name id_rsa -exec cat {} +`, `find . -delete`).
180
+ // Same arbitrary-exec hazard that excludes xargs — force a prompt.
181
+ if (baseName === 'find' && /(?:^|\s)-(?:exec|execdir|ok|okdir|delete|fprint|fprintf|fls)\b/.test(segment)) {
182
+ return false;
183
+ }
168
184
  // Known safe base command
169
185
  if (SAFE_COMMANDS.has(baseName)) {
170
186
  // sed -i is not read-only
171
187
  if (baseName === 'sed' && segment.includes(' -i'))
172
188
  return false;
173
- // Output redirection means writing — not safe
174
- if (/>\s*[^&|]/.test(segment))
189
+ // Output redirection means writing — not safe. Covers `>`, `>>`, `>|`, and
190
+ // `>&FILE` (a path target), while still allowing numeric fd dups (`2>&1`, `>&2`).
191
+ if (/>[>|&]?\s*[^\s&|0-9]/.test(segment))
192
+ return false;
193
+ // Coreutils with a hidden write mode the redirect check can't see:
194
+ if ((baseName === 'sort' || baseName === 'uniq' || baseName === 'tree') && /(?:^|\s)(?:-o(?:[=\s]|$)|--output\b)/.test(segment))
195
+ return false;
196
+ // `uniq IN OUT` overwrites the 2nd positional file.
197
+ if (baseName === 'uniq' && words.slice(argIdx).filter((w) => w && !w.startsWith('-')).length >= 2)
198
+ return false;
199
+ // `yq -i` / `jq` in-place edits.
200
+ if ((baseName === 'yq' || baseName === 'jq') && /(?:^|\s)(?:-i\b|--in-?place\b)/.test(segment))
175
201
  return false;
176
202
  return true;
177
203
  }
@@ -187,11 +213,20 @@ function isSegmentSafe(segment) {
187
213
  return true;
188
214
  // `gh api` DEFAULTS to GET (read-only) but `-X/--method` and write-body
189
215
  // flags (-f/-F/--field/--input) make it a mutation (delete repo, merge PR,
190
- // etc.). Only auto-approve a plain GET; anything else must prompt.
216
+ // etc.). Match the flag in EVERY form gh accepts — `-X POST`, `-XDELETE`,
217
+ // `--method=POST`, `-ftitle=v`, `-f k=v` — and auto-approve only when none
218
+ // is present (a plain GET). The space-only regex was bypassable with `=` /
219
+ // glued forms.
191
220
  if (subCmd === 'api') {
192
- if (/(?:^|\s)(?:-X|--method)\s+(?!GET\b)\S+/i.test(segment))
193
- return false;
194
- if (/(?:^|\s)(?:-f|-F|--field|--raw-field|--input)\b/.test(segment))
221
+ if (/(?:^|\s)-X/.test(segment))
222
+ return false; // -X POST / -XPOST / -XDELETE
223
+ if (/(?:^|\s)--method\b/i.test(segment))
224
+ return false; // --method POST / --method=POST
225
+ if (/(?:^|\s)-[fF][A-Za-z0-9_]*=/.test(segment))
226
+ return false; // -ffield=val (glued)
227
+ if (/(?:^|\s)-[fF](?:\s|$)/.test(segment))
228
+ return false; // -f / -F (spaced value)
229
+ if (/(?:^|\s)--(?:field|raw-field|input)\b/.test(segment))
195
230
  return false;
196
231
  return true;
197
232
  }
@@ -25,13 +25,13 @@ function pidIsFranklinRunner(pid) {
25
25
  const procCmdline = `/proc/${pid}/cmdline`;
26
26
  if (fs.existsSync(procCmdline)) {
27
27
  const raw = fs.readFileSync(procCmdline, 'utf-8').replace(/\0/g, ' ').trim();
28
- return /franklin|runcode|node.*dist\/index/.test(raw);
28
+ return /_task-runner|franklin|runcode|node.*dist\/index/.test(raw);
29
29
  }
30
30
  }
31
31
  catch { /* fall through to ps */ }
32
32
  try {
33
33
  const cmd = execSync(`ps -p ${pid} -o command=`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
34
- return /franklin|runcode|node.*dist\/index/.test(cmd);
34
+ return /_task-runner|franklin|runcode|node.*dist\/index/.test(cmd);
35
35
  }
36
36
  catch {
37
37
  return true;
@@ -83,7 +83,7 @@ function parseStatsFile(file) {
83
83
  // every downstream `history.push` / `Object.values(byModel)` would throw.
84
84
  if (!Array.isArray(merged.history))
85
85
  merged.history = [];
86
- if (!merged.byModel || typeof merged.byModel !== 'object')
86
+ if (!merged.byModel || typeof merged.byModel !== 'object' || Array.isArray(merged.byModel))
87
87
  merged.byModel = {};
88
88
  const numKeys = ['totalRequests', 'totalCostUsd', 'totalInputTokens', 'totalOutputTokens', 'totalFallbacks'];
89
89
  for (const k of numKeys) {
@@ -129,13 +129,16 @@ export function clearStats() {
129
129
  }
130
130
  resolvedStatsFile = null;
131
131
  for (const statsFile of new Set([preferredStatsFile(), fallbackStatsFile()])) {
132
- try {
133
- if (fs.existsSync(statsFile)) {
134
- fs.unlinkSync(statsFile);
132
+ // Remove the .bak/.tmp siblings too — else loadStats's new .bak fallback
133
+ // could resurrect the pre-reset stats from a stale snapshot.
134
+ for (const f of [statsFile, `${statsFile}.bak`, `${statsFile}.tmp`]) {
135
+ try {
136
+ if (fs.existsSync(f))
137
+ fs.unlinkSync(f);
138
+ }
139
+ catch {
140
+ /* ignore */
135
141
  }
136
- }
137
- catch {
138
- /* ignore */
139
142
  }
140
143
  }
141
144
  saveStats({ ...EMPTY_STATS, resetAt: Date.now() });
@@ -11,7 +11,7 @@ import { estimateImageCostUsd } from '../content/image-pricing.js';
11
11
  import { recordUsage } from '../stats/tracker.js';
12
12
  import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
13
13
  import { logger } from '../logger.js';
14
- import { isBlockedSsrfHost } from './ssrf.js';
14
+ import { ssrfSafeFetch } from './ssrf.js';
15
15
  /**
16
16
  * Models that accept a reference image via /v1/images/image2image. Mirrors the
17
17
  * gateway's EDIT_SUPPORTED_MODELS (src/app/api/v1/images/image2image/route.ts):
@@ -87,19 +87,16 @@ export async function resolveReferenceImage(input, workingDir) {
87
87
  if (input.startsWith('data:image/'))
88
88
  return input;
89
89
  if (/^https?:\/\//i.test(input)) {
90
- // SSRF guard: a reference-image URL is model/attacker-controllable.
91
- try {
92
- if (isBlockedSsrfHost(new URL(input).hostname) && process.env.FRANKLIN_ALLOW_PRIVATE_FETCH !== '1') {
93
- throw new Error(`refusing to fetch a private/loopback/metadata address: ${new URL(input).hostname}`);
94
- }
95
- }
96
- catch (e) {
97
- throw e instanceof Error && e.message.startsWith('refusing') ? e : new Error(`invalid reference image URL: ${input}`);
98
- }
99
90
  const ctrl = new AbortController();
100
91
  const timeout = setTimeout(() => ctrl.abort(), 30_000);
101
92
  try {
102
- const resp = await fetch(input, { signal: ctrl.signal });
93
+ // SSRF guard with per-redirect re-validation (a reference-image URL is
94
+ // model/attacker-controllable, and a 302 to a loopback/metadata host
95
+ // would otherwise slip a host-only check).
96
+ const resp = await ssrfSafeFetch(input, {
97
+ signal: ctrl.signal,
98
+ allowPrivate: process.env.FRANKLIN_ALLOW_PRIVATE_FETCH === '1',
99
+ });
103
100
  if (!resp.ok) {
104
101
  throw new Error(`Reference image fetch failed: ${resp.status} ${resp.statusText}`);
105
102
  }
@@ -19,8 +19,16 @@ const WALLET_KEY_FILES = [
19
19
  path.join(BLOCKRUN_DIR, '.solana-session-key2'),
20
20
  path.join(BLOCKRUN_DIR, 'solana-wallet.json'), // legacy { address, private_key }
21
21
  ];
22
+ // macOS (APFS) and Windows are case-INSENSITIVE by default, and fs.realpathSync
23
+ // does NOT canonicalize case — so `.SOLANA-SESSION` opens the real
24
+ // `.solana-session` while an exact compare would miss it. Compare accordingly.
25
+ const CASE_INSENSITIVE_FS = process.platform === 'darwin' || process.platform === 'win32';
22
26
  function matchesKeyFile(p) {
23
27
  const norm = p.endsWith(path.sep) ? p.slice(0, -1) : p;
28
+ if (CASE_INSENSITIVE_FS) {
29
+ const lower = norm.toLowerCase();
30
+ return WALLET_KEY_FILES.some((f) => f.toLowerCase() === lower);
31
+ }
24
32
  return WALLET_KEY_FILES.includes(norm);
25
33
  }
26
34
  /**
@@ -8,3 +8,13 @@
8
8
  * common direct-IP/localhost cases, not a DNS-rebinding or redirect attack.
9
9
  */
10
10
  export declare function isBlockedSsrfHost(hostname: string): boolean;
11
+ /**
12
+ * Fetch with per-redirect-hop SSRF re-validation. Node's `fetch` follows
13
+ * redirects automatically, so a public URL can 302 to 169.254.169.254 / a
14
+ * loopback service — checking only the initial host is useless. This follows
15
+ * redirects MANUALLY, re-running isBlockedSsrfHost on every hop. `allow=true`
16
+ * (FRANKLIN_ALLOW_PRIVATE_FETCH) skips the check for local dev servers.
17
+ */
18
+ export declare function ssrfSafeFetch(url: string, init?: RequestInit & {
19
+ allowPrivate?: boolean;
20
+ }, maxHops?: number): Promise<Response>;
@@ -8,16 +8,34 @@
8
8
  * common direct-IP/localhost cases, not a DNS-rebinding or redirect attack.
9
9
  */
10
10
  export function isBlockedSsrfHost(hostname) {
11
- const h = hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, ''); // strip IPv6 brackets
11
+ // Normalize: lowercase, strip IPv6 brackets, strip a single trailing dot
12
+ // (`localhost.` / `127.0.0.1.` resolve the same as without it).
13
+ const h = hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '').replace(/\.$/, '');
12
14
  if (!h)
13
15
  return true;
14
16
  if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local'))
15
17
  return true;
16
- // IPv6 loopback / unspecified / link-local (fe80::/10) / unique-local (fc00::/7)
17
- if (h === '::1' || h === '::')
18
- return true;
19
- if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd'))
20
- return true;
18
+ // IPv6 literal (only IPv6 hosts contain a colon — so the fc/fd/fe80 ULA checks
19
+ // can't false-positive on public DNS names like fda.gov / fcc.gov).
20
+ if (h.includes(':')) {
21
+ if (h === '::1' || h === '::')
22
+ return true; // loopback / unspecified
23
+ if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd'))
24
+ return true; // link-local / ULA
25
+ // IPv4-mapped IPv6 (`::ffff:a.b.c.d` or `::ffff:hhhh:hhhh`) → recheck the embedded v4.
26
+ const mapped = h.match(/::ffff:(.+)$/);
27
+ if (mapped) {
28
+ const tail = mapped[1];
29
+ if (tail.includes('.'))
30
+ return isBlockedSsrfHost(tail);
31
+ const hx = tail.split(':');
32
+ if (hx.length === 2) {
33
+ const n = ((parseInt(hx[0], 16) << 16) | parseInt(hx[1], 16)) >>> 0;
34
+ return isBlockedSsrfHost(`${(n >>> 24) & 255}.${(n >>> 16) & 255}.${(n >>> 8) & 255}.${n & 255}`);
35
+ }
36
+ }
37
+ return false;
38
+ }
21
39
  // IPv4 literal
22
40
  const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
23
41
  if (m) {
@@ -33,3 +51,30 @@ export function isBlockedSsrfHost(hostname) {
33
51
  }
34
52
  return false;
35
53
  }
54
+ /**
55
+ * Fetch with per-redirect-hop SSRF re-validation. Node's `fetch` follows
56
+ * redirects automatically, so a public URL can 302 to 169.254.169.254 / a
57
+ * loopback service — checking only the initial host is useless. This follows
58
+ * redirects MANUALLY, re-running isBlockedSsrfHost on every hop. `allow=true`
59
+ * (FRANKLIN_ALLOW_PRIVATE_FETCH) skips the check for local dev servers.
60
+ */
61
+ export async function ssrfSafeFetch(url, init = {}, maxHops = 5) {
62
+ const { allowPrivate, ...fetchInit } = init;
63
+ let current = url;
64
+ for (let hop = 0; hop <= maxHops; hop++) {
65
+ const host = new URL(current).hostname;
66
+ if (!allowPrivate && isBlockedSsrfHost(host)) {
67
+ throw new Error(`SSRF: refusing to fetch a private/loopback/metadata address: ${host}`);
68
+ }
69
+ const res = await fetch(current, { ...fetchInit, redirect: 'manual' });
70
+ if (res.status >= 300 && res.status < 400) {
71
+ const loc = res.headers.get('location');
72
+ if (!loc)
73
+ return res;
74
+ current = new URL(loc, current).href; // resolve relative redirects
75
+ continue;
76
+ }
77
+ return res;
78
+ }
79
+ throw new Error('SSRF: too many redirects');
80
+ }
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { USER_AGENT } from '../config.js';
5
5
  import { frameUntrusted } from './untrusted.js';
6
- import { isBlockedSsrfHost } from './ssrf.js';
6
+ import { isBlockedSsrfHost, ssrfSafeFetch } from './ssrf.js';
7
7
  const MAX_BODY_BYTES = 256 * 1024; // 256KB
8
8
  const DEFAULT_MAX_LENGTH = 12_288;
9
9
  const HTML_READ_AHEAD_BYTES = 8_192;
@@ -122,13 +122,16 @@ async function execute(input, ctx) {
122
122
  const onAbort = () => controller.abort();
123
123
  ctx.abortSignal.addEventListener('abort', onAbort, { once: true });
124
124
  try {
125
- const response = await fetch(url, {
125
+ // ssrfSafeFetch follows redirects MANUALLY and re-checks the host on every
126
+ // hop — a plain redirect:'follow' would let a public URL 302 to a
127
+ // loopback/metadata address, defeating the guard above.
128
+ const response = await ssrfSafeFetch(url, {
126
129
  signal: controller.signal,
127
130
  headers: {
128
131
  'User-Agent': USER_AGENT,
129
132
  'Accept': 'text/html,application/json,text/plain,*/*',
130
133
  },
131
- redirect: 'follow',
134
+ allowPrivate: process.env.FRANKLIN_ALLOW_PRIVATE_FETCH === '1',
132
135
  });
133
136
  if (!response.ok) {
134
137
  // 403 / 429 from a domain not in the static block list often still
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.29.9",
3
+ "version": "3.29.10",
4
4
  "description": "Franklin Agent — The AI agent with a wallet. Spends USDC autonomously to get real work done. Pay per action, no subscriptions.",
5
5
  "type": "module",
6
6
  "exports": {