@blockrun/franklin 3.29.10 → 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.
@@ -102,6 +102,12 @@ const SAFE_CARGO_SUBCOMMANDS = new Set([
102
102
  'test', 'check', 'clippy', 'build', 'run', 'bench', 'doc',
103
103
  'fmt', 'tree', 'metadata', 'verify-project',
104
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)$/;
105
111
  // ─── Classifier ──────────────────────────────────────────────────────────
106
112
  export function classifyBashRisk(command) {
107
113
  // 1. Check dangerous patterns first (highest priority)
@@ -110,8 +116,13 @@ export function classifyBashRisk(command) {
110
116
  return { level: 'dangerous', reason };
111
117
  }
112
118
  }
113
- // 2. Check if every segment is a known-safe command
114
- 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*/);
115
126
  let allSafe = true;
116
127
  for (const segment of segments) {
117
128
  const trimmed = segment.trim();
@@ -143,8 +154,64 @@ function isSegmentSafe(segment) {
143
154
  if (/(?<![\w-])(?:\.solana-session(?:-key2)?|\.session|[\w-]*wallet[\w-]*\.(?:json|key))(?![\w-])/i.test(segment)) {
144
155
  return false;
145
156
  }
146
- // Parse: strip env vars, extract command and args
147
- const words = segment.split(/\s+/).filter(w => !w.includes('='));
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);
148
215
  let idx = 0;
149
216
  let cmd = words[idx] || '';
150
217
  // Strip harmless prefixes
@@ -159,7 +226,28 @@ function isSegmentSafe(segment) {
159
226
  const subCmd = words[argIdx] || '';
160
227
  // git
161
228
  if (baseName === 'git') {
162
- 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;
163
251
  }
164
252
  // npm / yarn / pnpm / bun / npx
165
253
  if (['npm', 'npx', 'yarn', 'pnpm', 'bun'].includes(baseName)) {
@@ -186,10 +274,8 @@ function isSegmentSafe(segment) {
186
274
  // sed -i is not read-only
187
275
  if (baseName === 'sed' && segment.includes(' -i'))
188
276
  return false;
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;
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.)
193
279
  // Coreutils with a hidden write mode the redirect check can't see:
194
280
  if ((baseName === 'sort' || baseName === 'uniq' || baseName === 'tree') && /(?:^|\s)(?:-o(?:[=\s]|$)|--output\b)/.test(segment))
195
281
  return false;
@@ -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 });
@@ -12,6 +12,7 @@ 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
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):
@@ -297,6 +298,11 @@ function buildExecute(deps) {
297
298
  const outPath = output_path
298
299
  ? (path.isAbsolute(output_path) ? output_path : path.resolve(ctx.workingDir, output_path))
299
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
+ }
300
306
  const body = JSON.stringify(editMode
301
307
  ? {
302
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,
@@ -1,12 +1,3 @@
1
- /**
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.
9
- */
10
1
  export declare function isBlockedSsrfHost(hostname: string): boolean;
11
2
  /**
12
3
  * Fetch with per-redirect-hop SSRF re-validation. Node's `fetch` follows
@@ -7,6 +7,11 @@
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
16
  // Normalize: lowercase, strip IPv6 brackets, strip a single trailing dot
12
17
  // (`localhost.` / `127.0.0.1.` resolve the same as without it).
@@ -15,6 +20,14 @@ export function isBlockedSsrfHost(hostname) {
15
20
  return true;
16
21
  if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local'))
17
22
  return true;
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'))
28
+ return true;
29
+ if (METADATA_HOSTS.has(h))
30
+ return true;
18
31
  // IPv6 literal (only IPv6 hosts contain a colon — so the fc/fd/fe80 ULA checks
19
32
  // can't false-positive on public DNS names like fda.gov / fcc.gov).
20
33
  if (h.includes(':')) {
@@ -22,6 +35,19 @@ export function isBlockedSsrfHost(hostname) {
22
35
  return true; // loopback / unspecified
23
36
  if (h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd'))
24
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
+ }
25
51
  // IPv4-mapped IPv6 (`::ffff:a.b.c.d` or `::ffff:hhhh:hhhh`) → recheck the embedded v4.
26
52
  const mapped = h.match(/::ffff:(.+)$/);
27
53
  if (mapped) {
@@ -39,7 +65,7 @@ export function isBlockedSsrfHost(hostname) {
39
65
  // IPv4 literal
40
66
  const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
41
67
  if (m) {
42
- const a = Number(m[1]), b = Number(m[2]);
68
+ const a = Number(m[1]), b = Number(m[2]), c = Number(m[3]);
43
69
  if (a === 127 || a === 0 || a === 10)
44
70
  return true; // loopback / this-host / private
45
71
  if (a === 169 && b === 254)
@@ -48,6 +74,12 @@ export function isBlockedSsrfHost(hostname) {
48
74
  return true; // private
49
75
  if (a === 192 && b === 168)
50
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
51
83
  }
52
84
  return false;
53
85
  }
@@ -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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.29.10",
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": {