@blockrun/franklin 3.49.2 → 3.49.4

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.
@@ -9,6 +9,7 @@ import { recordFailure } from '../stats/failures.js';
9
9
  import { estimateSpendUsd, isSpendTool } from '../tools/spend-tools.js';
10
10
  import { BLOCKRUN_DIR } from '../config.js';
11
11
  import { redactSecretsInOutput } from './secret-redact.js';
12
+ import { walletSecretLiterals } from '../tools/sensitive-paths.js';
12
13
  import { resolvePayMode } from '../payments/auth-mode.js';
13
14
  import { logger } from '../logger.js';
14
15
  /** Persist a large tool result to disk and return a preview string. */
@@ -297,9 +298,12 @@ export class StreamingExecutor {
297
298
  // model, the transcript, and the on-disk overflow file alike.
298
299
  //
299
300
  // resolvePayMode() is memoised per process, so reading the configured
300
- // key here costs nothing per tool call.
301
+ // key here costs nothing per tool call. walletSecretLiterals() is the
302
+ // backstop for the path guards: whatever tool a key file leaks through,
303
+ // its exact value never reaches the model. It re-reads only when a key
304
+ // file's mtime/size changes.
301
305
  const payMode = resolvePayMode();
302
- const redacted = redactSecretsInOutput(result.output, payMode.kind === 'key' ? [payMode.key] : []);
306
+ const redacted = redactSecretsInOutput(result.output, [...(payMode.kind === 'key' ? [payMode.key] : []), ...walletSecretLiterals()]);
303
307
  if (redacted.labels.length > 0) {
304
308
  logger.warn(`[franklin] Redacted ${redacted.labels.join(', ')} from ${invocation.name} output`);
305
309
  result = { ...result, output: redacted.text };
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
22
22
  import type { McpServerConfig } from './client.js';
23
+ export declare function openBrowser(url: string): Promise<void>;
23
24
  export interface FranklinOAuthProvider {
24
25
  provider: OAuthClientProvider;
25
26
  /** Cheap signal for `/mcp` to show "authorized" without re-validating tokens. */
package/dist/mcp/oauth.js CHANGED
@@ -21,11 +21,11 @@
21
21
  import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
  import { createServer } from 'node:http';
24
- import { exec } from 'node:child_process';
24
+ import { execFile } from 'node:child_process';
25
25
  import { promisify } from 'node:util';
26
26
  import { BLOCKRUN_DIR } from '../config.js';
27
27
  import { logger } from '../logger.js';
28
- const execAsync = promisify(exec);
28
+ const execFileAsync = promisify(execFile);
29
29
  const OAUTH_DIR = join(BLOCKRUN_DIR, 'mcp', 'oauth');
30
30
  function storePath(serverName) {
31
31
  return join(OAUTH_DIR, `${serverName.replace(/[^A-Za-z0-9_.-]/g, '_')}.json`);
@@ -47,14 +47,33 @@ function saveState(serverName, state) {
47
47
  mkdirSync(dirname(p), { recursive: true, mode: 0o700 });
48
48
  writeFileSync(p, JSON.stringify(state, null, 2), { mode: 0o600 });
49
49
  }
50
- async function openBrowser(url) {
50
+ export async function openBrowser(url) {
51
+ // The URL comes from the remote server's OAuth metadata
52
+ // (authorization_endpoint), so it is attacker-controlled. It must never
53
+ // reach a shell: `$(...)` survives URL serialization and double quotes do
54
+ // not stop command substitution. Only http(s), passed as an argv entry.
55
+ let parsed;
56
+ try {
57
+ parsed = new URL(url);
58
+ }
59
+ catch {
60
+ logger.warn(`[mcp:oauth] refusing to open an unparseable authorization URL`);
61
+ return;
62
+ }
63
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
64
+ logger.warn(`[mcp:oauth] refusing to open a non-http(s) authorization URL (${parsed.protocol})`);
65
+ return;
66
+ }
67
+ const href = parsed.href;
51
68
  // Prefer the platform native opener so unusual environments (corporate
52
69
  // wrappers, WSL, headless ssh-with-X-forward) still work when they have it.
53
- const cmd = process.platform === 'darwin' ? `open "${url}"` :
54
- process.platform === 'win32' ? `start "" "${url}"` :
55
- `xdg-open "${url}"`;
70
+ // Windows: `start` is a cmd builtin and cmd re-parses `&`/`|`, so use the
71
+ // URL protocol handler directly.
72
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [href]] :
73
+ process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', href]] :
74
+ ['xdg-open', [href]];
56
75
  try {
57
- await execAsync(cmd);
76
+ await execFileAsync(cmd, args, { timeout: 10_000 });
58
77
  }
59
78
  catch (err) {
60
79
  logger.warn(`[mcp:oauth] couldn't open browser automatically: ${err.message}`);
@@ -4,4 +4,4 @@
4
4
  * Design language adapted from Multica (oklch palette, sidebar nav).
5
5
  * Currency-grade watermark + Inter font.
6
6
  */
7
- export declare function getHTML(): string;
7
+ export declare function getHTML(panelToken?: string): string;
@@ -4,7 +4,7 @@
4
4
  * Design language adapted from Multica (oklch palette, sidebar nav).
5
5
  * Currency-grade watermark + Inter font.
6
6
  */
7
- export function getHTML() {
7
+ export function getHTML(panelToken = '') {
8
8
  return `<!DOCTYPE html>
9
9
  <html lang="en">
10
10
  <head>
@@ -913,6 +913,18 @@ a:hover { text-decoration:underline; }
913
913
  </div>
914
914
 
915
915
  <script>
916
+ // Every same-origin request carries the per-process panel token; the server
917
+ // refuses wallet, spend, and state-changing routes without it.
918
+ (() => {
919
+ const PANEL_TOKEN = ${JSON.stringify(panelToken)};
920
+ const nativeFetch = window.fetch.bind(window);
921
+ window.fetch = (input, init = {}) => {
922
+ const headers = new Headers(init.headers || {});
923
+ headers.set('X-Franklin-Panel-Token', PANEL_TOKEN);
924
+ return nativeFetch(input, { ...init, headers });
925
+ };
926
+ })();
927
+
916
928
  // Tab switching — supports URL hash (e.g. #tasks) for deep links.
917
929
  // Emits a 'tab:activated' / 'tab:deactivated' event so per-tab modules
918
930
  // can start/stop their pollers without coupling to the dispatcher.
@@ -4,6 +4,7 @@
4
4
  * Zero external dependencies — uses node:http only.
5
5
  */
6
6
  import http from 'node:http';
7
+ import crypto from 'node:crypto';
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
9
10
  import { loadChain, saveChain, isChain, CHAIN_LABELS } from '../config.js';
@@ -72,8 +73,36 @@ function isTrustedPanelOrigin(req) {
72
73
  return false;
73
74
  }
74
75
  }
76
+ function isLocalHostHeader(req) {
77
+ const host = req.headers.host;
78
+ if (!host)
79
+ return false;
80
+ try {
81
+ return isLocalHostname(new URL(`http://${host}`).hostname);
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ /**
88
+ * Per-process token, embedded in the panel page and sent back by its fetch
89
+ * wrapper as `X-Franklin-Panel-Token`. Loopback + local Host + Origin are not
90
+ * enough on their own: a request with no Origin passes isTrustedPanelOrigin,
91
+ * and that is exactly what an SSRF from inside Franklin looks like (a tool
92
+ * fetching a public URL that 30x-redirects to localhost:3100). A custom
93
+ * header that only the served page knows closes that, and a cross-origin
94
+ * browser page cannot set it without a CORS preflight the panel never grants.
95
+ */
96
+ const PANEL_TOKEN = crypto.randomBytes(32).toString('hex');
97
+ const PANEL_TOKEN_HEADER = 'x-franklin-panel-token';
98
+ function hasPanelToken(req) {
99
+ const got = req.headers[PANEL_TOKEN_HEADER];
100
+ if (typeof got !== 'string' || got.length !== PANEL_TOKEN.length)
101
+ return false;
102
+ return crypto.timingSafeEqual(Buffer.from(got), Buffer.from(PANEL_TOKEN));
103
+ }
75
104
  function isLocalPanelRequest(req) {
76
- return isLoopback(req) && isTrustedPanelOrigin(req);
105
+ return isLoopback(req) && isTrustedPanelOrigin(req) && hasPanelToken(req);
77
106
  }
78
107
  async function readBody(req, maxBytes = 16 * 1024) {
79
108
  return new Promise((resolve, reject) => {
@@ -123,11 +152,26 @@ async function currentWalletAddress() {
123
152
  return client.getWalletAddress();
124
153
  }
125
154
  export function createPanelServer(port) {
126
- const html = getHTML();
155
+ const html = getHTML(PANEL_TOKEN);
127
156
  const server = http.createServer(async (req, res) => {
128
157
  try {
129
158
  const url = new URL(req.url || '/', `http://localhost:${port}`);
130
159
  const p = url.pathname;
160
+ // Every route, read-only ones included: session transcripts and the audit
161
+ // log are as sensitive as the wallet routes. Loopback alone does not stop
162
+ // DNS rebinding (a page on attacker.example re-resolved to 127.0.0.1), so
163
+ // the Host header must name a local host too.
164
+ if (!isLoopback(req) || !isLocalHostHeader(req)) {
165
+ res.writeHead(403, { 'Content-Type': 'text/plain' });
166
+ res.end('Forbidden');
167
+ return;
168
+ }
169
+ // Anything that changes state needs the page's token, including routes
170
+ // that only check loopback (task cancel).
171
+ if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS' && !hasPanelToken(req)) {
172
+ json(res, { error: 'forbidden' }, 403);
173
+ return;
174
+ }
131
175
  // ─── HTML ──
132
176
  if (p === '/') {
133
177
  res.writeHead(200, {
@@ -163,7 +207,6 @@ export function createPanelServer(port) {
163
207
  'Content-Type': 'text/event-stream',
164
208
  'Cache-Control': 'no-cache',
165
209
  'Connection': 'keep-alive',
166
- 'Access-Control-Allow-Origin': '*',
167
210
  });
168
211
  res.write('data: {"type":"connected"}\n\n');
169
212
  sseClients.add(res);
@@ -357,7 +400,9 @@ export function createPanelServer(port) {
357
400
  // ─── Wallet secret (loopback only) ──────────────────────────────────
358
401
  // Returns the private key so the user can back it up / move it.
359
402
  // Hardened: loopback-only (belt-and-suspenders on the 127.0.0.1 bind),
360
- // same-origin for browser requests, no-store cache header, JSON only.
403
+ // same-origin for browser requests, the page token (so no other local
404
+ // client — including a redirected tool fetch — can read it), no-store
405
+ // cache header, JSON only.
361
406
  if (p === '/api/wallet/secret') {
362
407
  if (!isLocalPanelRequest(req)) {
363
408
  json(res, { error: 'forbidden' }, 403);
@@ -54,6 +54,10 @@ function getSessionsDir() {
54
54
  return resolvedSessionsDir;
55
55
  }
56
56
  function sessionPath(id) {
57
+ // Ids reach here from URLs (panel /api/sessions/:id); never let one escape the sessions dir.
58
+ if (!id || id !== path.basename(id) || id.includes('..') || id.includes('\0')) {
59
+ throw new Error(`Invalid session id: ${JSON.stringify(id)}`);
60
+ }
57
61
  return path.join(getSessionsDir(), `${id}.jsonl`);
58
62
  }
59
63
  /** Get the absolute path to a session's JSONL file (for external readers like search). */
@@ -14,4 +14,14 @@
14
14
  * profile links, "Show more"), never reply/like/follow buttons.
15
15
  */
16
16
  import type { CapabilityHandler } from '../agent/types.js';
17
+ /**
18
+ * Why a URL may not be loaded (or read back) in the browser, or null if it is
19
+ * fine. The model picks the URL, so this is WebFetch's rule set: http(s) only
20
+ * (no file:, so ~/.blockrun/.session can't be rendered and snapshotted) and no
21
+ * loopback/private/metadata host (the local panel serves the wallet key).
22
+ * `about:blank` is allowed for the current-page check only.
23
+ */
24
+ export declare function browserUrlRefusal(raw: string, { allowBlank }?: {
25
+ allowBlank?: boolean | undefined;
26
+ }): string | null;
17
27
  export declare const browserXCapability: CapabilityHandler;
@@ -18,7 +18,46 @@ import os from 'node:os';
18
18
  import { browserPool } from '../social/browser-pool.js';
19
19
  import { frameUntrusted } from './untrusted.js';
20
20
  import { isWalletKeyPath } from './sensitive-paths.js';
21
+ import { isBlockedSsrfHost } from './ssrf.js';
21
22
  const MAX_WAIT_MS = 15_000;
23
+ /**
24
+ * Why a URL may not be loaded (or read back) in the browser, or null if it is
25
+ * fine. The model picks the URL, so this is WebFetch's rule set: http(s) only
26
+ * (no file:, so ~/.blockrun/.session can't be rendered and snapshotted) and no
27
+ * loopback/private/metadata host (the local panel serves the wallet key).
28
+ * `about:blank` is allowed for the current-page check only.
29
+ */
30
+ export function browserUrlRefusal(raw, { allowBlank = false } = {}) {
31
+ let u;
32
+ try {
33
+ u = new URL(raw);
34
+ }
35
+ catch {
36
+ return `invalid URL: ${raw.slice(0, 200)}`;
37
+ }
38
+ if (allowBlank && u.href === 'about:blank')
39
+ return null;
40
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
41
+ return `only http(s) URLs are allowed, got ${u.protocol}`;
42
+ }
43
+ if (isBlockedSsrfHost(u.hostname)) {
44
+ return `refusing a private/loopback/metadata host: ${u.hostname}`;
45
+ }
46
+ return null;
47
+ }
48
+ /**
49
+ * A public page can redirect into a blocked one after open() returns, so check
50
+ * where the browser actually is before reading anything out of it. On a hit,
51
+ * park the tab on about:blank so the content can't be read on a later call.
52
+ */
53
+ async function currentPageRefusal(browser) {
54
+ const current = await browser.getUrl();
55
+ const why = browserUrlRefusal(current, { allowBlank: true });
56
+ if (!why)
57
+ return null;
58
+ await browser.open('about:blank').catch(() => { });
59
+ return `Error: the page navigated to a blocked location (${why}). It was closed.`;
60
+ }
22
61
  function summariseTree(tree, max = 8000) {
23
62
  if (tree.length <= max)
24
63
  return tree;
@@ -29,6 +68,12 @@ async function execute(input, _ctx) {
29
68
  if (!action) {
30
69
  return { output: 'Error: action is required (open|snapshot|click|scroll|screenshot|getUrl|wait)', isError: true };
31
70
  }
71
+ // Refuse before launching Chrome, not after.
72
+ if (action === 'open' && url) {
73
+ const refused = browserUrlRefusal(url);
74
+ if (refused)
75
+ return { output: `Error: BrowserX ${refused}`, isError: true };
76
+ }
32
77
  let browser;
33
78
  try {
34
79
  browser = await browserPool.getBrowser();
@@ -43,10 +88,16 @@ async function execute(input, _ctx) {
43
88
  const msg = err instanceof Error ? err.message : String(err);
44
89
  return { output: `BrowserX open(${url}) failed: ${msg.slice(0, 200)}`, isError: true };
45
90
  }
91
+ const landed = await currentPageRefusal(browser);
92
+ if (landed)
93
+ return { output: landed, isError: true };
46
94
  return { output: `Opened ${url}. Call action="snapshot" next to inspect the page.` };
47
95
  }
48
96
  case 'snapshot': {
49
97
  try {
98
+ const blocked = await currentPageRefusal(browser);
99
+ if (blocked)
100
+ return { output: blocked, isError: true };
50
101
  const tree = await browser.snapshot();
51
102
  const out = `Page snapshot (${tree.length} chars):\n\n${summariseTree(tree)}\n\n` +
52
103
  `Refs are valid until the next snapshot. Use action="click" with a ref to navigate.`;
@@ -65,6 +116,9 @@ async function execute(input, _ctx) {
65
116
  // Give the navigation a moment to start, then return — model can
66
117
  // call snapshot next to see the result.
67
118
  await browser.waitForTimeout(1500);
119
+ const blocked = await currentPageRefusal(browser);
120
+ if (blocked)
121
+ return { output: blocked, isError: true };
68
122
  const newUrl = await browser.getUrl();
69
123
  return { output: `Clicked ref [${ref}]. Current URL: ${newUrl}. Call action="snapshot" to see the result.` };
70
124
  }
@@ -93,6 +147,9 @@ async function execute(input, _ctx) {
93
147
  return { output: `Error: refusing to write to the wallet key store: ${finalPath}`, isError: true };
94
148
  }
95
149
  try {
150
+ const blocked = await currentPageRefusal(browser);
151
+ if (blocked)
152
+ return { output: blocked, isError: true };
96
153
  const fs = await import('node:fs');
97
154
  fs.mkdirSync(path.dirname(finalPath), { recursive: true });
98
155
  await browser.screenshot(finalPath);
@@ -4,7 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { partiallyReadFiles, fileReadTracker, invalidateFileCache } from './read.js';
7
- import { isWalletKeyPath } from './sensitive-paths.js';
7
+ import { isHostCredentialPath, isWalletKeyPath } from './sensitive-paths.js';
8
8
  /**
9
9
  * Normalize curly/smart quotes to straight quotes.
10
10
  * Handles API-sanitized strings and editor paste artifacts.
@@ -33,6 +33,9 @@ async function execute(input, ctx) {
33
33
  if (isWalletKeyPath(resolved)) {
34
34
  return { output: `Error: refusing to edit the wallet key store: ${resolved}`, isError: true };
35
35
  }
36
+ if (isHostCredentialPath(resolved)) {
37
+ return { output: `Error: refusing to edit a credential store: ${resolved}`, isError: true };
38
+ }
36
39
  // Enforce read-before-edit: the model must Read the file before editing it
37
40
  const readRecord = fileReadTracker.get(resolved);
38
41
  if (!readRecord) {
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
+ import { isHostCredentialPath, isWalletKeyPath } from './sensitive-paths.js';
6
7
  const MAX_RESULTS = 200;
7
8
  const MAX_OUTPUT_CHARS = 12_000; // ~3,000 tokens — prevents huge glob results from blowing up context
8
9
  /**
@@ -55,6 +56,9 @@ function walkDirectory(dir, baseDir, pattern, results, depth, visited) {
55
56
  const fullPath = path.join(dir, entry.name);
56
57
  const relativePath = path.relative(baseDir, fullPath);
57
58
  if (entry.isFile() || (entry.isSymbolicLink() && !isDir)) {
59
+ // Don't hand the model a map to the key store or host credentials.
60
+ if (isWalletKeyPath(fullPath) || isHostCredentialPath(fullPath))
61
+ continue;
58
62
  if (globMatch(pattern, relativePath)) {
59
63
  results.push(fullPath);
60
64
  }
@@ -4,6 +4,8 @@
4
4
  import { execSync, execFileSync } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import { BLOCKRUN_DIR } from '../config.js';
8
+ import { WALLET_KEY_PATHS, hostCredentialDirPaths, isHostCredentialPath, isWalletKeyPath, secretPathRefusal, } from './sensitive-paths.js';
7
9
  const MAX_GREP_OUTPUT_CHARS = 16_000; // ~4,000 tokens — prevents huge grep results
8
10
  let _hasRipgrep = null;
9
11
  function hasRipgrep() {
@@ -29,6 +31,12 @@ async function execute(input, ctx) {
29
31
  if (!fs.existsSync(searchPath)) {
30
32
  return { output: `Error: path not found: ${searchPath}`, isError: true };
31
33
  }
34
+ // Grep reads file contents, so it carries Read's guard. An explicit file
35
+ // path makes rg read a hidden file it would skip on a walk — exactly how
36
+ // the wallet key reached the model before this check.
37
+ const refusal = secretPathRefusal(path.resolve(searchPath));
38
+ if (refusal)
39
+ return { output: refusal, isError: true };
32
40
  const mode = opts.output_mode || 'files_with_matches';
33
41
  const limit = opts.head_limit ?? 250;
34
42
  if (hasRipgrep()) {
@@ -36,6 +44,41 @@ async function execute(input, ctx) {
36
44
  }
37
45
  return runNativeGrep(opts, searchPath, mode, limit, ctx.workingDir);
38
46
  }
47
+ // Exclusions for a directory walk. Key files and credential stores are hidden
48
+ // or live under hidden dirs, which rg skips by default, but api-key and
49
+ // solana-wallet.json are not hidden and a search rooted at ~/.blockrun reaches
50
+ // them. `**/` anchoring matches whichever root the walk starts from.
51
+ const CASE_INSENSITIVE_FS = process.platform === 'darwin' || process.platform === 'win32';
52
+ function secretExcludeGlobs() {
53
+ const blockrunName = path.basename(BLOCKRUN_DIR);
54
+ const home = path.dirname(BLOCKRUN_DIR);
55
+ const flag = CASE_INSENSITIVE_FS ? '--iglob' : '--glob';
56
+ const globs = WALLET_KEY_PATHS.map((f) => `${flag}=!**/${blockrunName}/${path.relative(BLOCKRUN_DIR, f).split(path.sep).join('/')}`);
57
+ for (const dir of hostCredentialDirPaths()) {
58
+ const rel = path.relative(home, dir).split(path.sep).join('/');
59
+ globs.push(`${flag}=!**/${rel}/**`);
60
+ }
61
+ return globs;
62
+ }
63
+ /** Second line of defence: drop any result line that names a secret file. */
64
+ function dropSecretLines(lines, searchPath) {
65
+ const isFile = (() => { try {
66
+ return fs.statSync(searchPath).isFile();
67
+ }
68
+ catch {
69
+ return false;
70
+ } })();
71
+ return lines.filter((line) => {
72
+ if (isFile)
73
+ return true; // the explicit path already passed secretPathRefusal
74
+ // Result lines: `/abs/path`, `/abs/path:12:text`, `/abs/path-12-ctx`, `/abs/path:3`.
75
+ const m = /^(\/.*?)(?:[:-]\d+[:-]|:\d+$|$)/.exec(line);
76
+ if (!m)
77
+ return true;
78
+ const file = m[1];
79
+ return !isWalletKeyPath(file) && !isHostCredentialPath(file);
80
+ });
81
+ }
39
82
  function toRelative(absPath, cwd) {
40
83
  const rel = path.relative(cwd, absPath);
41
84
  return rel.startsWith('..') ? absPath : rel;
@@ -74,6 +117,8 @@ function runRipgrep(opts, searchPath, mode, limit, cwd) {
74
117
  args.push(`--type=${opts.type}`);
75
118
  // Always exclude common noise + lock files (huge, rarely useful)
76
119
  args.push('--glob=!node_modules', '--glob=!.git', '--glob=!dist', '--glob=!*.lock', '--glob=!package-lock.json', '--glob=!pnpm-lock.yaml');
120
+ // Last, so a caller-supplied glob cannot re-include them.
121
+ args.push(...secretExcludeGlobs());
77
122
  args.push('--', opts.pattern);
78
123
  args.push(searchPath);
79
124
  try {
@@ -82,7 +127,7 @@ function runRipgrep(opts, searchPath, mode, limit, cwd) {
82
127
  maxBuffer: 2 * 1024 * 1024,
83
128
  stdio: ['pipe', 'pipe', 'pipe'],
84
129
  });
85
- const lines = result.split('\n').filter(Boolean);
130
+ const lines = dropSecretLines(result.split('\n').filter(Boolean), searchPath);
86
131
  const offset = opts.offset ?? 0;
87
132
  const sliced = offset > 0 ? lines.slice(offset) : lines;
88
133
  const limited = limit > 0 ? sliced.slice(0, limit) : sliced;
@@ -139,6 +184,12 @@ function runNativeGrep(opts, searchPath, mode, limit, cwd) {
139
184
  args.push(`--include=${nativeGlob}`);
140
185
  }
141
186
  args.push('--exclude-dir=node_modules', '--exclude-dir=.git', '--exclude-dir=dist', '--exclude=*.lock', '--exclude=package-lock.json', '--exclude=pnpm-lock.yaml');
187
+ // grep's --exclude matches basenames only, so this over-excludes any file
188
+ // that happens to share a key file's name. Acceptable for the fallback path.
189
+ for (const f of WALLET_KEY_PATHS)
190
+ args.push(`--exclude=${path.basename(f)}`);
191
+ for (const d of hostCredentialDirPaths())
192
+ args.push(`--exclude-dir=${path.basename(d)}`);
142
193
  args.push('-e', opts.pattern, searchPath);
143
194
  try {
144
195
  const result = execFileSync('grep', args, {
@@ -146,7 +197,7 @@ function runNativeGrep(opts, searchPath, mode, limit, cwd) {
146
197
  maxBuffer: 2 * 1024 * 1024,
147
198
  stdio: ['pipe', 'pipe', 'pipe'],
148
199
  });
149
- const lines = result.split('\n').filter(Boolean);
200
+ const lines = dropSecretLines(result.split('\n').filter(Boolean), searchPath);
150
201
  const limited = limit > 0 ? lines.slice(0, limit) : lines;
151
202
  const relativized = limited.map(line => {
152
203
  const colonIdx = line.indexOf(':');
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { isWalletKeyPath } from './sensitive-paths.js';
6
+ import { secretPathRefusal } from './sensitive-paths.js';
7
7
  /**
8
8
  * Tracks files that were only partially read (offset or limit applied).
9
9
  * Stores the read range so Edit tool can give smarter warnings —
@@ -58,10 +58,13 @@ async function execute(input, ctx) {
58
58
  return { output: 'Error: file_path is required', isError: true };
59
59
  }
60
60
  const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(ctx.workingDir, filePath);
61
- // Never let the model read the wallet private key into context.
62
- if (isWalletKeyPath(resolved)) {
63
- return { output: `Error: refusing to read the wallet key store: ${resolved}`, isError: true };
64
- }
61
+ // Never let the model read the wallet private key, or the host's own
62
+ // credential stores (~/.ssh, ~/.aws, ...), into context. Read is
63
+ // auto-approved, so this check is the only thing between a steered model
64
+ // and those files.
65
+ const refusal = secretPathRefusal(resolved);
66
+ if (refusal)
67
+ return { output: refusal, isError: true };
65
68
  try {
66
69
  const stat = fs.statSync(resolved);
67
70
  // File state cache: if file hasn't changed and same range requested, return stub
@@ -16,3 +16,25 @@
16
16
  export declare function isWalletKeyPath(resolvedAbsPath: string): boolean;
17
17
  /** Exported for tests / reuse. */
18
18
  export declare const WALLET_KEY_PATHS: string[];
19
+ /**
20
+ * True if `absDir` is (or resolves to) a directory that contains a wallet key
21
+ * file somewhere beneath it. Search tools use this to exclude the key files
22
+ * from a directory walk, since a walk never passes the exact key path to
23
+ * isWalletKeyPath.
24
+ */
25
+ export declare function walletKeyFilesUnder(absDir: string): string[];
26
+ /**
27
+ * True if `resolvedAbsPath` is — or resolves through a symlink to — a host
28
+ * credential store (see hostCredentialDirs / hostCredentialFiles).
29
+ */
30
+ export declare function isHostCredentialPath(resolvedAbsPath: string): boolean;
31
+ /** Home-relative credential directories, for tools that keep their own blocklist. */
32
+ export declare function hostCredentialDirPaths(): string[];
33
+ /** The single refusal used by every model-facing tool that reads files. */
34
+ export declare function secretPathRefusal(resolvedAbsPath: string): string | null;
35
+ /**
36
+ * Current wallet key + account key values, for the tool-output redactor.
37
+ * Re-read only when a key file's mtime/size changes (the panel can import a
38
+ * new wallet mid-session).
39
+ */
40
+ export declare function walletSecretLiterals(): string[];
@@ -10,6 +10,7 @@
10
10
  * close that gap for Write, Edit, AND Read.
11
11
  */
12
12
  import fs from 'node:fs';
13
+ import os from 'node:os';
13
14
  import path from 'node:path';
14
15
  import { API_KEY_FILE, BLOCKRUN_DIR } from '../config.js';
15
16
  /**
@@ -57,3 +58,170 @@ export function isWalletKeyPath(resolvedAbsPath) {
57
58
  }
58
59
  /** Exported for tests / reuse. */
59
60
  export const WALLET_KEY_PATHS = WALLET_KEY_FILES;
61
+ /**
62
+ * True if `absDir` is (or resolves to) a directory that contains a wallet key
63
+ * file somewhere beneath it. Search tools use this to exclude the key files
64
+ * from a directory walk, since a walk never passes the exact key path to
65
+ * isWalletKeyPath.
66
+ */
67
+ export function walletKeyFilesUnder(absDir) {
68
+ const roots = [absDir];
69
+ try {
70
+ roots.push(fs.realpathSync(absDir));
71
+ }
72
+ catch { /* not on disk */ }
73
+ const out = new Set();
74
+ for (const root of roots) {
75
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
76
+ for (const f of WALLET_KEY_FILES) {
77
+ const hit = CASE_INSENSITIVE_FS
78
+ ? f.toLowerCase().startsWith(prefix.toLowerCase())
79
+ : f.startsWith(prefix);
80
+ if (hit)
81
+ out.add(path.relative(root, f));
82
+ }
83
+ }
84
+ return [...out];
85
+ }
86
+ // ─── Host credential stores ────────────────────────────────────────────────
87
+ // Secrets that belong to the machine, not to Franklin: SSH keys, cloud
88
+ // credentials, other wallets' keypairs. Write already refused these; Read and
89
+ // the search tools did not, and Read is auto-approved, so a steered model
90
+ // could pull `~/.ssh/id_rsa` into context without a prompt. Bash still reaches
91
+ // them, but bash-guard classifies those reads as needing approval.
92
+ /** Directories whose whole contents are credential material. */
93
+ function hostCredentialDirs(home) {
94
+ return [
95
+ path.join(home, '.ssh'),
96
+ path.join(home, '.aws'),
97
+ path.join(home, '.kube'),
98
+ path.join(home, '.gnupg'),
99
+ path.join(home, '.config', 'gcloud'),
100
+ path.join(home, '.config', 'solana'), // Solana CLI keypair (id.json)
101
+ path.join(home, '.azure'),
102
+ ];
103
+ }
104
+ /** Single credential files. */
105
+ function hostCredentialFiles(home) {
106
+ return [
107
+ path.join(home, '.netrc'),
108
+ path.join(home, '.npmrc'),
109
+ path.join(home, '.pgpass'),
110
+ path.join(home, '.git-credentials'),
111
+ path.join(home, '.docker', 'config.json'),
112
+ path.join(home, '.cargo', 'credentials'),
113
+ path.join(home, '.cargo', 'credentials.toml'),
114
+ path.join(home, '.config', 'rclone', 'rclone.conf'),
115
+ path.join(home, '.config', 'gh', 'hosts.yml'),
116
+ ];
117
+ }
118
+ function norm(p) {
119
+ const n = p.length > 1 && p.endsWith(path.sep) ? p.slice(0, -1) : p;
120
+ return CASE_INSENSITIVE_FS ? n.toLowerCase() : n;
121
+ }
122
+ function matchesHostCredential(p, home) {
123
+ const target = norm(p);
124
+ for (const dir of hostCredentialDirs(home)) {
125
+ const d = norm(dir);
126
+ if (target === d || target.startsWith(d + path.sep))
127
+ return true;
128
+ }
129
+ return hostCredentialFiles(home).some((f) => norm(f) === target);
130
+ }
131
+ /**
132
+ * True if `resolvedAbsPath` is — or resolves through a symlink to — a host
133
+ * credential store (see hostCredentialDirs / hostCredentialFiles).
134
+ */
135
+ export function isHostCredentialPath(resolvedAbsPath) {
136
+ const home = os.homedir();
137
+ if (matchesHostCredential(resolvedAbsPath, home))
138
+ return true;
139
+ try {
140
+ if (fs.existsSync(resolvedAbsPath) &&
141
+ matchesHostCredential(fs.realpathSync(resolvedAbsPath), home)) {
142
+ return true;
143
+ }
144
+ }
145
+ catch { /* best-effort symlink check */ }
146
+ return false;
147
+ }
148
+ /** Home-relative credential directories, for tools that keep their own blocklist. */
149
+ export function hostCredentialDirPaths() {
150
+ return hostCredentialDirs(os.homedir());
151
+ }
152
+ /** The single refusal used by every model-facing tool that reads files. */
153
+ export function secretPathRefusal(resolvedAbsPath) {
154
+ if (isWalletKeyPath(resolvedAbsPath)) {
155
+ return `Error: refusing to read the wallet key store: ${resolvedAbsPath}`;
156
+ }
157
+ if (isHostCredentialPath(resolvedAbsPath)) {
158
+ return `Error: refusing to read a credential store: ${resolvedAbsPath}. ` +
159
+ `If the user needs this file, they can open it themselves.`;
160
+ }
161
+ return null;
162
+ }
163
+ // ─── Wallet secrets as redaction literals ──────────────────────────────────
164
+ // The path guards stop the tools we know about. This is the backstop for any
165
+ // path we do not: the exact key values, scrubbed from every tool result.
166
+ // Matching on the literal (not a 0x + 64-hex shape) keeps tx hashes intact.
167
+ let secretCache = null;
168
+ function extractSecrets(file, raw) {
169
+ const out = [];
170
+ const text = raw.trim();
171
+ if (!text)
172
+ return out;
173
+ if (file.endsWith('.json')) {
174
+ try {
175
+ const obj = JSON.parse(text);
176
+ for (const k of ['privateKey', 'private_key', 'secretKey', 'secret_key']) {
177
+ const v = obj[k];
178
+ if (typeof v === 'string')
179
+ out.push(v.trim());
180
+ }
181
+ }
182
+ catch { /* not JSON: fall through to raw */ }
183
+ if (out.length)
184
+ return out;
185
+ }
186
+ out.push(text);
187
+ return out;
188
+ }
189
+ /**
190
+ * Current wallet key + account key values, for the tool-output redactor.
191
+ * Re-read only when a key file's mtime/size changes (the panel can import a
192
+ * new wallet mid-session).
193
+ */
194
+ export function walletSecretLiterals() {
195
+ const stats = WALLET_KEY_FILES.map((f) => {
196
+ try {
197
+ const s = fs.statSync(f);
198
+ return `${s.mtimeMs}:${s.size}`;
199
+ }
200
+ catch {
201
+ return '-';
202
+ }
203
+ });
204
+ const stamp = stats.join('|');
205
+ if (secretCache && secretCache.stamp === stamp)
206
+ return secretCache.values;
207
+ const values = new Set();
208
+ WALLET_KEY_FILES.forEach((f, i) => {
209
+ if (stats[i] === '-')
210
+ return;
211
+ try {
212
+ for (const v of extractSecrets(f, fs.readFileSync(f, 'utf-8'))) {
213
+ if (v.length < 32)
214
+ continue;
215
+ values.add(v);
216
+ // An EVM key shows up with or without its 0x prefix.
217
+ if (/^0x[0-9a-fA-F]{64}$/.test(v))
218
+ values.add(v.slice(2));
219
+ else if (/^[0-9a-fA-F]{64}$/.test(v))
220
+ values.add('0x' + v);
221
+ }
222
+ }
223
+ catch { /* unreadable: nothing to redact */ }
224
+ });
225
+ secretCache = { stamp, values: [...values] };
226
+ return secretCache.values;
227
+ }
@@ -1,11 +1,13 @@
1
1
  /**
2
- * Basic SSRF guard for model-driven fetches (WebFetch, reference-image resolve).
2
+ * SSRF guard for model-driven requests (WebFetch, WebhookPost, BrowserX,
3
+ * reference-image resolve).
3
4
  *
4
5
  * Blocks loopback / private / link-local / cloud-metadata hosts so a steered
5
6
  * model can't make Franklin fetch `http://169.254.169.254/...` (cloud creds) or
6
7
  * `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.
8
+ * it does NOT resolve DNS, so a public name that resolves to a private address
9
+ * gets through. ssrfSafeFetch re-checks every redirect hop. Every outbound
10
+ * model-driven request must use these two, not a private copy of the check.
9
11
  */
10
12
  // Named cloud-metadata endpoints that aren't `*.internal` (AWS legacy alias,
11
13
  // GCP short form). They resolve to 169.254.169.254 / a link-local address.
@@ -9,10 +9,11 @@
9
9
  * channels. If a channel needs a signature header (e.g., Feishu sign
10
10
  * mode), the agent passes it in via `headers`.
11
11
  *
12
- * Safety: outbound URLs are a publish surface. We refuse localhost,
13
- * private ranges, and file schemes so an agent can't be tricked into
14
- * hitting internal services. A permission prompt fires on first use per
15
- * session.
12
+ * Safety: outbound URLs are a publish surface. Hosts go through the same
13
+ * SSRF guard as WebFetch, and redirects are followed manually with every
14
+ * hop re-checked: a public URL that 30x-redirects to the local panel would
15
+ * otherwise hand the panel's response (the wallet key) back to the model.
16
+ * A permission prompt fires on first use per session.
16
17
  */
17
18
  import type { CapabilityHandler } from '../agent/types.js';
18
19
  export declare const webhookPostCapability: CapabilityHandler;
@@ -9,50 +9,16 @@
9
9
  * channels. If a channel needs a signature header (e.g., Feishu sign
10
10
  * mode), the agent passes it in via `headers`.
11
11
  *
12
- * Safety: outbound URLs are a publish surface. We refuse localhost,
13
- * private ranges, and file schemes so an agent can't be tricked into
14
- * hitting internal services. A permission prompt fires on first use per
15
- * session.
12
+ * Safety: outbound URLs are a publish surface. Hosts go through the same
13
+ * SSRF guard as WebFetch, and redirects are followed manually with every
14
+ * hop re-checked: a public URL that 30x-redirects to the local panel would
15
+ * otherwise hand the panel's response (the wallet key) back to the model.
16
+ * A permission prompt fires on first use per session.
16
17
  */
17
- import { isIP } from 'node:net';
18
18
  import { VERSION } from '../config.js';
19
+ import { isBlockedSsrfHost, ssrfSafeFetch } from './ssrf.js';
19
20
  const DEFAULT_TIMEOUT_MS = 15_000;
20
21
  const MAX_BODY_BYTES = 512 * 1024; // 512 KB is generous for a chat push.
21
- function isPrivateHost(hostname) {
22
- const h = hostname
23
- .trim()
24
- .replace(/^\[/, '')
25
- .replace(/\]$/, '')
26
- .split('%', 1)[0]
27
- .toLowerCase();
28
- if (h === 'localhost' || h === '127.0.0.1' || h === '0.0.0.0' || h === '::' || h === '::1')
29
- return true;
30
- // IPv4 private ranges.
31
- if (isIP(h) === 4) {
32
- const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(h);
33
- if (m) {
34
- const [a, b] = [Number(m[1]), Number(m[2])];
35
- if (a === 10)
36
- return true;
37
- if (a === 172 && b >= 16 && b <= 31)
38
- return true;
39
- if (a === 192 && b === 168)
40
- return true;
41
- if (a === 169 && b === 254)
42
- return true; // link-local
43
- if (a === 127)
44
- return true;
45
- }
46
- }
47
- if (isIP(h) === 6) {
48
- if (h.startsWith('fc') || h.startsWith('fd') || h.startsWith('fe80:'))
49
- return true;
50
- if (h.startsWith('::ffff:')) {
51
- return isPrivateHost(h.slice('::ffff:'.length));
52
- }
53
- }
54
- return false;
55
- }
56
22
  async function execute(input, ctx) {
57
23
  const { url, body, headers, method = 'POST' } = input;
58
24
  if (!url || typeof url !== 'string') {
@@ -68,7 +34,7 @@ async function execute(input, ctx) {
68
34
  if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
69
35
  return { output: `Error: only http(s) URLs allowed, got ${parsed.protocol}`, isError: true };
70
36
  }
71
- if (isPrivateHost(parsed.hostname)) {
37
+ if (isBlockedSsrfHost(parsed.hostname)) {
72
38
  return {
73
39
  output: `Error: refusing to post to private/loopback host ${parsed.hostname}. ` +
74
40
  `WebhookPost is for public webhook endpoints only.`,
@@ -111,7 +77,7 @@ async function execute(input, ctx) {
111
77
  ctx.abortSignal.addEventListener('abort', onParentAbort);
112
78
  const timer = setTimeout(() => ctrl.abort(), DEFAULT_TIMEOUT_MS);
113
79
  try {
114
- const res = await fetch(url, {
80
+ const res = await ssrfSafeFetch(url, {
115
81
  method,
116
82
  headers: finalHeaders,
117
83
  body: bodyText || undefined,
@@ -138,7 +104,11 @@ async function execute(input, ctx) {
138
104
  return { output: 'Webhook POST canceled by user.', isError: true };
139
105
  return { output: `Webhook POST timed out after ${DEFAULT_TIMEOUT_MS}ms`, isError: true };
140
106
  }
141
- return { output: `Webhook POST error: ${err.message}`, isError: true };
107
+ const msg = err.message;
108
+ if (msg.startsWith('SSRF:')) {
109
+ return { output: `Error: refusing to follow a redirect to a private/loopback host. ${msg}`, isError: true };
110
+ }
111
+ return { output: `Webhook POST error: ${msg}`, isError: true };
142
112
  }
143
113
  finally {
144
114
  clearTimeout(timer);
@@ -5,7 +5,7 @@ import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import os from 'node:os';
7
7
  import { partiallyReadFiles, fileReadTracker, invalidateFileCache } from './read.js';
8
- import { isWalletKeyPath } from './sensitive-paths.js';
8
+ import { hostCredentialDirPaths, isWalletKeyPath } from './sensitive-paths.js';
9
9
  function withTrailingSep(value) {
10
10
  return value.endsWith(path.sep) ? value : value + path.sep;
11
11
  }
@@ -51,11 +51,7 @@ async function execute(input, ctx) {
51
51
  const allowedTempDirs = getAllowedTempDirs();
52
52
  const dangerousPaths = [
53
53
  '/etc/', '/usr/', '/bin/', '/sbin/', '/var/', '/System/',
54
- path.join(home, '.ssh') + '/',
55
- path.join(home, '.aws') + '/',
56
- path.join(home, '.kube') + '/',
57
- path.join(home, '.gnupg') + '/',
58
- path.join(home, '.config/gcloud') + '/',
54
+ ...hostCredentialDirPaths().map((d) => d + '/'),
59
55
  ];
60
56
  // Check both the resolved path and the real path (after symlink resolution)
61
57
  const checkPath = (p) => !allowedTempDirs.some(dir => isWithinDir(p, dir)) &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.2",
3
+ "version": "3.49.4",
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": {