@blockrun/franklin 3.29.9 → 3.29.12

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',
@@ -101,6 +102,12 @@ const SAFE_CARGO_SUBCOMMANDS = new Set([
101
102
  'test', 'check', 'clippy', 'build', 'run', 'bench', 'doc',
102
103
  'fmt', 'tree', 'metadata', 'verify-project',
103
104
  ]);
105
+ // Env vars that may be stripped as a benign command PREFIX (`LANG=C ls`). These
106
+ // only affect locale/display — none change code loading, library injection, or
107
+ // interpreter behavior. Anything NOT on this list (BASH_ENV, LD_PRELOAD,
108
+ // DYLD_INSERT_LIBRARIES, PERL5OPT, NODE_OPTIONS, PATH, IFS, a custom var, …) is
109
+ // treated as an execution-hijack risk and forces a prompt.
110
+ const BENIGN_ENV_PREFIXES = /^(?:LANG|LANGUAGE|LC_[A-Z]+|TZ|TERM|COLUMNS|LINES|NO_COLOR|FORCE_COLOR|CLICOLOR|CLICOLOR_FORCE|GREP_COLOR|GREP_COLORS)$/;
104
111
  // ─── Classifier ──────────────────────────────────────────────────────────
105
112
  export function classifyBashRisk(command) {
106
113
  // 1. Check dangerous patterns first (highest priority)
@@ -109,8 +116,13 @@ export function classifyBashRisk(command) {
109
116
  return { level: 'dangerous', reason };
110
117
  }
111
118
  }
112
- // 2. Check if every segment is a known-safe command
113
- const segments = command.split(/\s*(?:&&|\|\||[;|])\s*/);
119
+ // 2. Check if every segment is a known-safe command. Split on ALL bash
120
+ // command separators — &&, ||, ;, |, a lone & (background), and newline/CR —
121
+ // so an injected second command (`pwd\nnpm install evil`, `pwd & node x`) is
122
+ // classified on its own rather than hiding behind a benign first word. (`&&`
123
+ // is matched before the lone `&`; numeric fd dups like `2>&1` have no
124
+ // standalone `&` and are handled per-segment by the redirect check.)
125
+ const segments = command.split(/\s*(?:&&|\|\||[;|]|(?<![>&])&(?![&>])|[\n\r])\s*/);
114
126
  let allSafe = true;
115
127
  for (const segment of segments) {
116
128
  const trimmed = segment.trim();
@@ -127,14 +139,79 @@ export function classifyBashRisk(command) {
127
139
  return { level: 'normal' };
128
140
  }
129
141
  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)) {
142
+ // Never auto-approve a command that touches the wallet key store. Matching the
143
+ // FILENAME is hopeless — it's trivially obfuscated (`.solana""-session`,
144
+ // `.\solana-session`, a glob, or an unlisted key file like
145
+ // solana-wallet-key2.json). So match the DIRECTORY: any reference to
146
+ // ~/.blockrun forces a prompt. (The file Read/Write/Edit tools have a separate
147
+ // canonicalized guard; this is the best-effort net for the shell. Over-
148
+ // prompting on a stray `.blockrun` path is fine — it prompts, never blocks.)
149
+ if (/\.blockrun/i.test(segment)) {
134
150
  return false;
135
151
  }
136
- // Parse: strip env vars, extract command and args
137
- const words = segment.split(/\s+/).filter(w => !w.includes('='));
152
+ // Relative reads with no `.blockrun` in the text (e.g. the cwd is the wallet
153
+ // dir): match the known key/secret basenames broadly (any *wallet*.json/.key).
154
+ if (/(?<![\w-])(?:\.solana-session(?:-key2)?|\.session|[\w-]*wallet[\w-]*\.(?:json|key))(?![\w-])/i.test(segment)) {
155
+ return false;
156
+ }
157
+ // Command/process substitution runs an arbitrary INNER command the classifier
158
+ // can't see (`echo $(node evil)`, `cat <(touch x)`) — never safe.
159
+ if (/\$\(|`|<\(|>\(/.test(segment)) {
160
+ return false;
161
+ }
162
+ // Parameter expansion (`$VAR`, `${VAR}`) expands to text the classifier also
163
+ // can't see, so a bare `$HOME` glob can reach the wallet store exactly like
164
+ // `$(...)` — `cat $HOME/.bl*/.s*` evaded the rooted-glob guard below because it
165
+ // starts with `$`, not `~`/`.`/`/`. Treat any `$NAME` / `${NAME}` as opaque.
166
+ // (`$` followed by a non-name char — e.g. a `grep 'foo$'` regex anchor, `$?`,
167
+ // `$5` — is left alone so common read commands still auto-approve.)
168
+ if (/\$\{?[A-Za-z_]/.test(segment)) {
169
+ return false;
170
+ }
171
+ // A glob/brace in an explicit PATH (a token rooted at ~, ., or /) expands AFTER
172
+ // this guard and can reach the wallet store (`cat ~/.b*/.s*`) or a sensitive
173
+ // file. Bare cwd globs (`*.md`, `src/*.ts`) have no such prefix and stay safe.
174
+ if (/(?:^|\s)(?:~|\.|\/)\S*[*?[{]/.test(segment)) {
175
+ return false;
176
+ }
177
+ // Output redirection to a FILE target is a write — block it for EVERY segment,
178
+ // not just SAFE_COMMANDS ones. git/npm/cargo/bun resolve through their own
179
+ // branches below and used to skip the redirect check, so `git status > ~/.bashrc`
180
+ // (overwrite a shell rc → RCE on next shell) and `npm test > attack.sh`
181
+ // auto-approved. Allows numeric fd dups (`2>&1`, `>&2` — a digit follows `>`).
182
+ if (/>[>|&]?\s*[^\s&|0-9]/.test(segment)) {
183
+ return false;
184
+ }
185
+ // Reading host credential stores should PROMPT — mirror the Write tool's
186
+ // dangerous-path block so `cat ~/.ssh/id_rsa`, `cat ~/.aws/credentials`,
187
+ // `cat ~/.gnupg/secring.gpg`, gcloud tokens, `.npmrc`/`.pgpass`/`.netrc`, and
188
+ // docker registry creds don't auto-approve secrets into model context.
189
+ if (/(?:^|[\s/~'"=])\.(?:ssh|aws|gnupg|kube)(?:\/|$|['"\s])/i.test(segment))
190
+ return false;
191
+ if (/\bid_(?:rsa|dsa|ecdsa|ed25519)\b/i.test(segment))
192
+ return false;
193
+ if (/(?:^|[\s/~'"=])\.(?:npmrc|pgpass|netrc)(?:$|['"\s])/i.test(segment))
194
+ return false;
195
+ if (/gcloud\/(?:credentials|access_tokens|application_default)|\.docker\/config/i.test(segment))
196
+ return false;
197
+ // Parse into words. An env-assignment PREFIX (`FOO=bar cmd …`) is a real
198
+ // assignment only in the LEADING run before the command word — a later `x=y`
199
+ // is just an argument (`grep x=y file`). Walk the leading run: reject the
200
+ // segment if any assignment names a code-loading / execution-hijack var, so a
201
+ // benign-looking base command can't smuggle one (`BASH_ENV=./rc ls`,
202
+ // `LD_PRELOAD=/x.so cat f`). Only locale/display vars strip silently.
203
+ const rawWords = segment.split(/\s+/).filter(Boolean);
204
+ let envPrefixCount = 0;
205
+ for (const w of rawWords) {
206
+ const eq = w.indexOf('=');
207
+ // Stop at the first token that isn't a `NAME=value` assignment — that's the command.
208
+ if (eq <= 0 || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(w.slice(0, eq)))
209
+ break;
210
+ if (!BENIGN_ENV_PREFIXES.test(w.slice(0, eq).toUpperCase()))
211
+ return false;
212
+ envPrefixCount++;
213
+ }
214
+ const words = rawWords.slice(envPrefixCount);
138
215
  let idx = 0;
139
216
  let cmd = words[idx] || '';
140
217
  // Strip harmless prefixes
@@ -149,7 +226,28 @@ function isSegmentSafe(segment) {
149
226
  const subCmd = words[argIdx] || '';
150
227
  // git
151
228
  if (baseName === 'git') {
152
- return SAFE_GIT_SUBCOMMANDS.has(subCmd);
229
+ if (!SAFE_GIT_SUBCOMMANDS.has(subCmd))
230
+ return false;
231
+ // `config` is read-only ONLY in get/list form. A bare `git config key value`
232
+ // WRITES — and `--global` escapes the repo to plant an exec hook via
233
+ // core.pager/core.editor/alias.x (`git config core.pager "node evil.js"`).
234
+ // Count positional args after `config`: 2+ (key + value) is a write; explicit
235
+ // write flags (--add/--unset/…) also force a prompt.
236
+ if (subCmd === 'config') {
237
+ const cfgPositionals = segment
238
+ .replace(/^[^]*?\bconfig\b/, '')
239
+ .split(/\s+/)
240
+ .filter((w) => w && !w.startsWith('-'));
241
+ const writeFlag = /(?:^|\s)--(?:add|unset(?:-all)?|replace-all|remove-section|rename-section|edit|set)\b/.test(segment);
242
+ if (cfgPositionals.length >= 2 || writeFlag)
243
+ return false;
244
+ }
245
+ // `git remote add/set-url/remove/rename/…` mutate remotes (can point at an
246
+ // attacker repo). Only the read forms (`git remote`, `git remote -v`) are safe.
247
+ if (subCmd === 'remote' && /(?:^|\s)(?:add|set-url|set-head|set-branches|remove|rm|rename|prune|update)\b/.test(segment)) {
248
+ return false;
249
+ }
250
+ return true;
153
251
  }
154
252
  // npm / yarn / pnpm / bun / npx
155
253
  if (['npm', 'npx', 'yarn', 'pnpm', 'bun'].includes(baseName)) {
@@ -165,13 +263,27 @@ function isSegmentSafe(segment) {
165
263
  // rtk (RTK wrapper — safe, it's a proxy)
166
264
  if (baseName === 'rtk')
167
265
  return true;
266
+ // `find` is read-only EXCEPT its action predicates, which execute arbitrary
267
+ // commands or delete files (`find / -name id_rsa -exec cat {} +`, `find . -delete`).
268
+ // Same arbitrary-exec hazard that excludes xargs — force a prompt.
269
+ if (baseName === 'find' && /(?:^|\s)-(?:exec|execdir|ok|okdir|delete|fprint|fprintf|fls)\b/.test(segment)) {
270
+ return false;
271
+ }
168
272
  // Known safe base command
169
273
  if (SAFE_COMMANDS.has(baseName)) {
170
274
  // sed -i is not read-only
171
275
  if (baseName === 'sed' && segment.includes(' -i'))
172
276
  return false;
173
- // Output redirection means writing — not safe
174
- if (/>\s*[^&|]/.test(segment))
277
+ // (Output redirection is now blocked for every segment near the top of this
278
+ // function, so the per-command redirect check that used to live here is gone.)
279
+ // Coreutils with a hidden write mode the redirect check can't see:
280
+ if ((baseName === 'sort' || baseName === 'uniq' || baseName === 'tree') && /(?:^|\s)(?:-o(?:[=\s]|$)|--output\b)/.test(segment))
281
+ return false;
282
+ // `uniq IN OUT` overwrites the 2nd positional file.
283
+ if (baseName === 'uniq' && words.slice(argIdx).filter((w) => w && !w.startsWith('-')).length >= 2)
284
+ return false;
285
+ // `yq -i` / `jq` in-place edits.
286
+ if ((baseName === 'yq' || baseName === 'jq') && /(?:^|\s)(?:-i\b|--in-?place\b)/.test(segment))
175
287
  return false;
176
288
  return true;
177
289
  }
@@ -187,11 +299,20 @@ function isSegmentSafe(segment) {
187
299
  return true;
188
300
  // `gh api` DEFAULTS to GET (read-only) but `-X/--method` and write-body
189
301
  // 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.
302
+ // etc.). Match the flag in EVERY form gh accepts — `-X POST`, `-XDELETE`,
303
+ // `--method=POST`, `-ftitle=v`, `-f k=v` — and auto-approve only when none
304
+ // is present (a plain GET). The space-only regex was bypassable with `=` /
305
+ // glued forms.
191
306
  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))
307
+ if (/(?:^|\s)-X/.test(segment))
308
+ return false; // -X POST / -XPOST / -XDELETE
309
+ if (/(?:^|\s)--method\b/i.test(segment))
310
+ return false; // --method POST / --method=POST
311
+ if (/(?:^|\s)-[fF][A-Za-z0-9_]*=/.test(segment))
312
+ return false; // -ffield=val (glued)
313
+ if (/(?:^|\s)-[fF](?:\s|$)/.test(segment))
314
+ return false; // -f / -F (spaced value)
315
+ if (/(?:^|\s)--(?:field|raw-field|input)\b/.test(segment))
195
316
  return false;
196
317
  return true;
197
318
  }
@@ -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() });
@@ -17,6 +17,7 @@ import path from 'node:path';
17
17
  import os from 'node:os';
18
18
  import { browserPool } from '../social/browser-pool.js';
19
19
  import { frameUntrusted } from './untrusted.js';
20
+ import { isWalletKeyPath } from './sensitive-paths.js';
20
21
  const MAX_WAIT_MS = 15_000;
21
22
  function summariseTree(tree, max = 8000) {
22
23
  if (tree.length <= max)
@@ -88,6 +89,9 @@ async function execute(input, _ctx) {
88
89
  const finalPath = outPath
89
90
  ? outPath
90
91
  : path.join(os.homedir(), '.blockrun', 'screenshots', `browsex-${Date.now()}.png`);
92
+ if (isWalletKeyPath(path.resolve(finalPath))) {
93
+ return { output: `Error: refusing to write to the wallet key store: ${finalPath}`, isError: true };
94
+ }
91
95
  try {
92
96
  const fs = await import('node:fs');
93
97
  fs.mkdirSync(path.dirname(finalPath), { recursive: true });
@@ -11,7 +11,8 @@ 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
+ import { isWalletKeyPath } from './sensitive-paths.js';
15
16
  /**
16
17
  * Models that accept a reference image via /v1/images/image2image. Mirrors the
17
18
  * gateway's EDIT_SUPPORTED_MODELS (src/app/api/v1/images/image2image/route.ts):
@@ -87,19 +88,16 @@ export async function resolveReferenceImage(input, workingDir) {
87
88
  if (input.startsWith('data:image/'))
88
89
  return input;
89
90
  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
91
  const ctrl = new AbortController();
100
92
  const timeout = setTimeout(() => ctrl.abort(), 30_000);
101
93
  try {
102
- const resp = await fetch(input, { signal: ctrl.signal });
94
+ // SSRF guard with per-redirect re-validation (a reference-image URL is
95
+ // model/attacker-controllable, and a 302 to a loopback/metadata host
96
+ // would otherwise slip a host-only check).
97
+ const resp = await ssrfSafeFetch(input, {
98
+ signal: ctrl.signal,
99
+ allowPrivate: process.env.FRANKLIN_ALLOW_PRIVATE_FETCH === '1',
100
+ });
103
101
  if (!resp.ok) {
104
102
  throw new Error(`Reference image fetch failed: ${resp.status} ${resp.statusText}`);
105
103
  }
@@ -300,6 +298,11 @@ function buildExecute(deps) {
300
298
  const outPath = output_path
301
299
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
302
300
  : path.resolve(ctx.workingDir, `generated-${Date.now()}.png`);
301
+ // A caller-controlled output_path must not be allowed to overwrite the wallet
302
+ // key store (e.g. output_path="~/.blockrun/.session" would brick the wallet).
303
+ if (isWalletKeyPath(outPath)) {
304
+ return { output: `Error: refusing to write to the wallet key store: ${outPath}`, isError: true };
305
+ }
303
306
  const body = JSON.stringify(editMode
304
307
  ? {
305
308
  model: imageModel,
@@ -18,6 +18,7 @@ import path from 'node:path';
18
18
  import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, createSolanaPaymentPayload, parsePaymentRequired, extractPaymentDetails, solanaKeyToBytes, SOLANA_NETWORK, } from '@blockrun/llm';
19
19
  import { loadChain, API_URLS, VERSION } from '../config.js';
20
20
  import { logger } from '../logger.js';
21
+ import { isWalletKeyPath } from './sensitive-paths.js';
21
22
  import { findModel, estimateCostUsd } from '../gateway-models.js';
22
23
  import { recordUsage } from '../stats/tracker.js';
23
24
  const DEFAULT_MODEL = 'minimax/music-2.5+';
@@ -80,6 +81,10 @@ function buildExecute(deps) {
80
81
  const outPath = output_path
81
82
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
82
83
  : path.resolve(ctx.workingDir, `generated-${Date.now()}.mp3`);
84
+ // Don't let a caller-controlled output_path overwrite the wallet key store.
85
+ if (isWalletKeyPath(outPath)) {
86
+ return { output: `Error: refusing to write to the wallet key store: ${outPath}`, isError: true };
87
+ }
83
88
  const body = JSON.stringify({
84
89
  model: musicModel,
85
90
  prompt,
@@ -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
  /**
@@ -1,10 +1,11 @@
1
+ export declare function isBlockedSsrfHost(hostname: string): boolean;
1
2
  /**
2
- * Basic SSRF guard for model-driven fetches (WebFetch, reference-image resolve).
3
- *
4
- * Blocks loopback / private / link-local / cloud-metadata hosts so a steered
5
- * model can't make Franklin fetch `http://169.254.169.254/...` (cloud creds) or
6
- * `http://127.0.0.1:<port>/...` (the local proxy / panel). Literal-host based:
7
- * it does NOT resolve DNS or re-validate each redirect hop, so it stops the
8
- * common direct-IP/localhost cases, not a DNS-rebinding or redirect attack.
3
+ * Fetch with per-redirect-hop SSRF re-validation. Node's `fetch` follows
4
+ * redirects automatically, so a public URL can 302 to 169.254.169.254 / a
5
+ * loopback service — checking only the initial host is useless. This follows
6
+ * redirects MANUALLY, re-running isBlockedSsrfHost on every hop. `allow=true`
7
+ * (FRANKLIN_ALLOW_PRIVATE_FETCH) skips the check for local dev servers.
9
8
  */
10
- export declare function isBlockedSsrfHost(hostname: string): boolean;
9
+ export declare function ssrfSafeFetch(url: string, init?: RequestInit & {
10
+ allowPrivate?: boolean;
11
+ }, maxHops?: number): Promise<Response>;
@@ -7,21 +7,65 @@
7
7
  * it does NOT resolve DNS or re-validate each redirect hop, so it stops the
8
8
  * common direct-IP/localhost cases, not a DNS-rebinding or redirect attack.
9
9
  */
10
+ // Named cloud-metadata endpoints that aren't `*.internal` (AWS legacy alias,
11
+ // GCP short form). They resolve to 169.254.169.254 / a link-local address.
12
+ const METADATA_HOSTS = new Set([
13
+ 'metadata', 'metadata.goog', 'instance-data', 'instance-data.ec2.internal',
14
+ ]);
10
15
  export function isBlockedSsrfHost(hostname) {
11
- const h = hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, ''); // strip IPv6 brackets
16
+ // Normalize: lowercase, strip IPv6 brackets, strip a single trailing dot
17
+ // (`localhost.` / `127.0.0.1.` resolve the same as without it).
18
+ const h = hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '').replace(/\.$/, '');
12
19
  if (!h)
13
20
  return true;
14
21
  if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local'))
15
22
  return true;
16
- // IPv6 loopback / unspecified / link-local (fe80::/10) / unique-local (fc00::/7)
17
- if (h === '::1' || h === '::')
23
+ // Cloud-metadata hostnames resolve (at the OS/fetch layer, AFTER this literal
24
+ // check) to 169.254.169.254 / a NAT address, so blocking only the IP misses the
25
+ // named form. `.internal` is the ICANN-reserved private TLD (GCE
26
+ // metadata.google.internal, EC2 *.ec2.internal) — denied wholesale.
27
+ if (h.endsWith('.internal'))
18
28
  return true;
19
- if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd'))
29
+ if (METADATA_HOSTS.has(h))
20
30
  return true;
31
+ // IPv6 literal (only IPv6 hosts contain a colon — so the fc/fd/fe80 ULA checks
32
+ // can't false-positive on public DNS names like fda.gov / fcc.gov).
33
+ if (h.includes(':')) {
34
+ if (h === '::1' || h === '::')
35
+ return true; // loopback / unspecified
36
+ if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd'))
37
+ return true; // link-local / ULA
38
+ // NAT64 (`64:ff9b::a.b.c.d` / `64:ff9b::hhhh:hhhh`) embeds an IPv4 that a NAT64
39
+ // gateway routes to — decode and recheck it like the IPv4-mapped form below.
40
+ const nat64 = h.match(/^64:ff9b::(.+)$/);
41
+ if (nat64) {
42
+ const t = nat64[1];
43
+ if (t.includes('.'))
44
+ return isBlockedSsrfHost(t);
45
+ const seg = t.split(':');
46
+ if (seg.length === 2) {
47
+ const n = ((parseInt(seg[0], 16) << 16) | parseInt(seg[1], 16)) >>> 0;
48
+ return isBlockedSsrfHost(`${(n >>> 24) & 255}.${(n >>> 16) & 255}.${(n >>> 8) & 255}.${n & 255}`);
49
+ }
50
+ }
51
+ // IPv4-mapped IPv6 (`::ffff:a.b.c.d` or `::ffff:hhhh:hhhh`) → recheck the embedded v4.
52
+ const mapped = h.match(/::ffff:(.+)$/);
53
+ if (mapped) {
54
+ const tail = mapped[1];
55
+ if (tail.includes('.'))
56
+ return isBlockedSsrfHost(tail);
57
+ const hx = tail.split(':');
58
+ if (hx.length === 2) {
59
+ const n = ((parseInt(hx[0], 16) << 16) | parseInt(hx[1], 16)) >>> 0;
60
+ return isBlockedSsrfHost(`${(n >>> 24) & 255}.${(n >>> 16) & 255}.${(n >>> 8) & 255}.${n & 255}`);
61
+ }
62
+ }
63
+ return false;
64
+ }
21
65
  // IPv4 literal
22
66
  const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
23
67
  if (m) {
24
- const a = Number(m[1]), b = Number(m[2]);
68
+ const a = Number(m[1]), b = Number(m[2]), c = Number(m[3]);
25
69
  if (a === 127 || a === 0 || a === 10)
26
70
  return true; // loopback / this-host / private
27
71
  if (a === 169 && b === 254)
@@ -30,6 +74,39 @@ export function isBlockedSsrfHost(hostname) {
30
74
  return true; // private
31
75
  if (a === 192 && b === 168)
32
76
  return true; // private
77
+ if (a === 100 && b === 100)
78
+ return true; // Alibaba Cloud metadata (100.100.100.200)
79
+ if (a === 192 && b === 0 && c === 0)
80
+ return true; // Oracle OCI metadata (192.0.0.192) / 192.0.0.0/24
81
+ if (a === 100 && b >= 64 && b <= 127)
82
+ return true; // CGNAT 100.64.0.0/10
33
83
  }
34
84
  return false;
35
85
  }
86
+ /**
87
+ * Fetch with per-redirect-hop SSRF re-validation. Node's `fetch` follows
88
+ * redirects automatically, so a public URL can 302 to 169.254.169.254 / a
89
+ * loopback service — checking only the initial host is useless. This follows
90
+ * redirects MANUALLY, re-running isBlockedSsrfHost on every hop. `allow=true`
91
+ * (FRANKLIN_ALLOW_PRIVATE_FETCH) skips the check for local dev servers.
92
+ */
93
+ export async function ssrfSafeFetch(url, init = {}, maxHops = 5) {
94
+ const { allowPrivate, ...fetchInit } = init;
95
+ let current = url;
96
+ for (let hop = 0; hop <= maxHops; hop++) {
97
+ const host = new URL(current).hostname;
98
+ if (!allowPrivate && isBlockedSsrfHost(host)) {
99
+ throw new Error(`SSRF: refusing to fetch a private/loopback/metadata address: ${host}`);
100
+ }
101
+ const res = await fetch(current, { ...fetchInit, redirect: 'manual' });
102
+ if (res.status >= 300 && res.status < 400) {
103
+ const loc = res.headers.get('location');
104
+ if (!loc)
105
+ return res;
106
+ current = new URL(loc, current).href; // resolve relative redirects
107
+ continue;
108
+ }
109
+ return res;
110
+ }
111
+ throw new Error('SSRF: too many redirects');
112
+ }
@@ -24,6 +24,7 @@ import { getOrCreateWallet, getOrCreateSolanaWallet, createPaymentPayload, creat
24
24
  import { loadChain, API_URLS, VERSION } from '../config.js';
25
25
  import { logger } from '../logger.js';
26
26
  import { resolveReferenceImage } from './imagegen.js';
27
+ import { isWalletKeyPath } from './sensitive-paths.js';
27
28
  import { recordUsage } from '../stats/tracker.js';
28
29
  import { findModel, estimateCostUsd, GATEWAY_MARGIN } from '../gateway-models.js';
29
30
  // BytePlus RealFace asset IDs from the RealFace tool (after H5 liveness +
@@ -164,6 +165,10 @@ function buildExecute(deps) {
164
165
  const outPath = output_path
165
166
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
166
167
  : path.resolve(ctx.workingDir, `generated-${Date.now()}.mp4`);
168
+ // Don't let a caller-controlled output_path overwrite the wallet key store.
169
+ if (isWalletKeyPath(outPath)) {
170
+ return { output: `Error: refusing to write to the wallet key store: ${outPath}`, isError: true };
171
+ }
167
172
  const body = JSON.stringify({
168
173
  model: videoModel,
169
174
  prompt: chosenPrompt,
@@ -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.12",
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": {