@blockrun/franklin 3.49.18 → 3.49.20

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.
@@ -5,7 +5,7 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { execSync } from 'node:child_process';
8
- import { API_URLS, BLOCKRUN_DIR, CHAIN_LABELS, CHAINS } from '../config.js';
8
+ import { API_URLS, CHAIN_LABELS, CHAINS } from '../config.js';
9
9
  import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
10
10
  import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
@@ -204,19 +204,9 @@ After delivering results, if a better data source exists, add one line at the en
204
204
  Do NOT check access before acting. Do NOT explain what you tried. Just deliver, then tip.`;
205
205
  }
206
206
  function getWalletKnowledgeSection() {
207
- // Read the panel URL persisted by startPanelBackground (start.ts) so we
208
- // surface the actual bound port — the panel auto-increments past 3100
209
- // when the default is taken (e.g. a second franklin running). Falls back
210
- // to the canonical default when the file is missing (panel disabled or
211
- // never started this session).
212
- let panelUrl = 'http://localhost:3100';
213
- try {
214
- const persisted = fs.readFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), 'utf8').trim();
215
- if (persisted.startsWith('http://') || persisted.startsWith('https://')) {
216
- panelUrl = persisted;
217
- }
218
- }
219
- catch { /* fall through to default */ }
207
+ // The panel URL is deliberately not in this prompt: it carries the panel's
208
+ // access token, which must not reach a model provider or a transcript.
209
+ // `franklin panel --open wallet` reads it from the 0600 panel-url file.
220
210
  return `# Wallet Storage (answer "where is my wallet" directly — no searching)
221
211
  Franklin stores wallet keys in ~/.blockrun/. When the user asks about wallet location, answer from this map — do not grep or scan.
222
212
 
@@ -242,25 +232,23 @@ When the user asks about "my wallet" without qualifier, default to Base (it's th
242
232
 
243
233
  When the user asks about depositing or funding USDC — in any language — do not describe the steps in chat. **Open the panel wallet page directly in their browser** using Bash, then confirm in chat what you opened and which chain is active.
244
234
 
245
- The exact wallet URL for this session:
246
-
247
- ${panelUrl}/#wallet
235
+ Bash command to open it (same on macOS, Linux and Windows; it finds the running panel's port and access link itself):
248
236
 
249
- Bash command to open it (macOS \`open\`, Linux \`xdg-open\`, Windows \`start\`):
237
+ franklin panel --open wallet
250
238
 
251
- open ${panelUrl}/#wallet
239
+ If it reports that no panel is running, tell the user to run \`franklin panel\` and open the Wallet tab from there.
252
240
 
253
241
  That page is where the deposit address, QR code, live balance, chain switcher, and back-up controls all live. The user lands on it instead of you reciting steps.
254
242
 
255
- After running \`open\`:
256
- - Tell the user one line: "Opened the wallet page — \`${panelUrl}/#wallet\`. Active chain: <base|solana>."
243
+ After running it:
244
+ - Tell the user one line: "Opened the wallet page in your browser. Active chain: <base|solana>."
257
245
  - Read the active chain from ~/.blockrun/payment-chain so they know which network to send USDC on.
258
246
  - Mention USDC is the only accepted token; ETH/SOL on their own won't settle x402 calls.
259
247
 
260
248
  Hard rules:
261
249
  - Do NOT print the private key in chat. The panel reveals it behind a click.
262
250
  - Do NOT invent a \`franklin deposit\` CLI flow — there isn't one; the panel IS the funding surface.
263
- - Do NOT hand-craft a different localhost port; the URL above tracks the actual bound port (3100 might have been taken; the panel could be on 3101+).
251
+ - Do NOT hand-craft a localhost panel URL or read ~/.blockrun/panel-url: the panel needs its access token, and \`franklin panel --open wallet\` supplies it without showing it to you.
264
252
  - If \`open\` fails (e.g. no GUI on a remote box), fall back to giving them the URL as plain text and tell them to paste it into a browser.`;
265
253
  }
266
254
  function getBlockRunApiSection() {
package/dist/agent/llm.js CHANGED
@@ -1201,7 +1201,7 @@ export class ModelClient {
1201
1201
  catch (err) {
1202
1202
  const msg = err.message || '';
1203
1203
  if (msg.includes('insufficient') || msg.includes('balance')) {
1204
- console.error(`[franklin] Insufficient USDC balance. Open http://localhost:3100/#wallet to deposit (or run 'franklin balance').`);
1204
+ console.error(`[franklin] Insufficient USDC balance. Run 'franklin panel --open wallet' to deposit (or 'franklin balance').`);
1205
1205
  }
1206
1206
  else if (this.debug) {
1207
1207
  console.error('[franklin] Payment error:', msg);
@@ -169,7 +169,7 @@ async function runChecks() {
169
169
  ? `$${walletBalance.toFixed(2)} — low; paid calls likely to fail mid-stream`
170
170
  : `$${walletBalance.toFixed(2)}`;
171
171
  const balanceRemedy = walletBalance < LOW_BALANCE_THRESHOLD
172
- ? `Send USDC on ${chain} to ${walletAddress} (or open http://localhost:3100/#wallet)`
172
+ ? `Send USDC on ${chain} to ${walletAddress} (or run: franklin panel --open wallet)`
173
173
  : undefined;
174
174
  out.push({
175
175
  name: 'USDC balance',
@@ -1,6 +1,12 @@
1
1
  /**
2
2
  * franklin panel — launch the local web dashboard.
3
3
  */
4
+ /**
5
+ * Open a URL in the default browser without going through a shell: the URL
6
+ * carries the panel token and `?`/`#`, which a shell would glob or cut.
7
+ */
8
+ export declare function openInBrowser(url: string): void;
4
9
  export declare function panelCommand(options: {
5
10
  port?: string;
11
+ open?: string | boolean;
6
12
  }): Promise<void>;
@@ -3,10 +3,63 @@
3
3
  */
4
4
  import chalk from 'chalk';
5
5
  import fs from 'node:fs';
6
- import path from 'node:path';
7
- import { createPanelServer } from '../panel/server.js';
8
- import { BLOCKRUN_DIR } from '../config.js';
6
+ import { execFile } from 'node:child_process';
7
+ import { createPanelServer, writePanelUrlFile, PANEL_URL_FILE } from '../panel/server.js';
8
+ /**
9
+ * Open a URL in the default browser without going through a shell: the URL
10
+ * carries the panel token and `?`/`#`, which a shell would glob or cut.
11
+ */
12
+ export function openInBrowser(url) {
13
+ const onError = () => { };
14
+ if (process.platform === 'darwin')
15
+ execFile('open', [url], onError);
16
+ else if (process.platform === 'win32') {
17
+ // `start` treats its first quoted argument as a window title.
18
+ execFile('cmd', ['/c', 'start', '""', `"${url}"`], { windowsVerbatimArguments: true }, onError);
19
+ }
20
+ else
21
+ execFile('xdg-open', [url], onError);
22
+ }
23
+ /**
24
+ * `franklin panel --open [section]`: open the panel that is already running
25
+ * (started by `franklin` or `franklin panel`) at an optional #section. The
26
+ * agent uses this for the wallet page, so the token never enters a prompt
27
+ * or a transcript: nothing here prints the token-bearing URL.
28
+ */
29
+ async function openRunningPanel(section) {
30
+ if (section && !/^[a-z0-9-]+$/i.test(section)) {
31
+ console.error(chalk.red(` Unknown panel section: ${section}`));
32
+ process.exit(1);
33
+ }
34
+ let launch = '';
35
+ try {
36
+ launch = fs.readFileSync(PANEL_URL_FILE, 'utf8').trim();
37
+ }
38
+ catch { /* none */ }
39
+ let alive = false;
40
+ if (/^http:\/\/localhost:\d+\/\?token=[0-9a-f]{64}$/.test(launch)) {
41
+ try {
42
+ const res = await fetch(launch, { signal: AbortSignal.timeout(1500) });
43
+ alive = res.status === 200; // 401 means a different panel process owns the port now
44
+ await res.body?.cancel();
45
+ }
46
+ catch {
47
+ alive = false;
48
+ }
49
+ }
50
+ if (!alive) {
51
+ console.error(chalk.yellow(' No running Franklin panel found. Start one with: franklin panel'));
52
+ process.exit(1);
53
+ }
54
+ openInBrowser(section ? `${launch}#${section}` : launch);
55
+ const port = new URL(launch).port;
56
+ console.log(` Opened the Franklin panel${section ? ` (${section})` : ''} on localhost:${port}.`);
57
+ }
9
58
  export async function panelCommand(options) {
59
+ if (options.open !== undefined) {
60
+ await openRunningPanel(typeof options.open === 'string' ? options.open : '');
61
+ return;
62
+ }
10
63
  const requestedPort = parseInt(options.port || '3100', 10);
11
64
  // Handle port-in-use by trying up to 20 subsequent ports silently.
12
65
  // Only log when we finally bind (or fail completely) — no per-attempt spam.
@@ -28,17 +81,9 @@ export async function panelCommand(options) {
28
81
  // Bind to loopback only — the panel exposes wallet secrets on /api/wallet/secret
29
82
  // and a write-capable /api/wallet/import. Never expose these on a LAN.
30
83
  server.listen(port, '127.0.0.1', () => {
31
- const url = `http://localhost:${port}`;
32
- // Mirror what start.ts does for the auto-panel — persist the bound
33
- // URL so any concurrent `franklin start` agent can read /#wallet
34
- // off the same file. Without this, a user who disables panel
35
- // autostart and runs `franklin panel` separately would still get
36
- // the hardcoded 3100 default in the agent prompt.
37
- try {
38
- fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
39
- fs.writeFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), url, 'utf8');
40
- }
41
- catch { /* best-effort */ }
84
+ // Persist the launch URL (0600) so `franklin panel --open wallet`,
85
+ // which the agent runs for funding, finds this panel's port and token.
86
+ const url = writePanelUrlFile(port);
42
87
  console.log('');
43
88
  console.log(chalk.bold(' Franklin Panel'));
44
89
  console.log(chalk.dim(` ${url}`) +
@@ -46,11 +91,7 @@ export async function panelCommand(options) {
46
91
  console.log('');
47
92
  console.log(chalk.dim(' Press Ctrl+C to stop.'));
48
93
  console.log('');
49
- // Try to open browser
50
- const open = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
51
- import('node:child_process').then(({ exec }) => {
52
- exec(`${open} ${url}`);
53
- }).catch(() => { });
94
+ openInBrowser(url);
54
95
  });
55
96
  // Graceful shutdown
56
97
  const shutdown = () => {
@@ -1,9 +1,7 @@
1
1
  import chalk from 'chalk';
2
2
  import { refreshModelCatalog } from '../model-catalog.js';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
3
  import { getOrCreateWallet, getOrCreateSolanaWallet } from '@blockrun/llm';
6
- import { BLOCKRUN_DIR, loadChain } from '../config.js';
4
+ import { loadChain } from '../config.js';
7
5
  import { gatewayBase } from '../payments/auth-mode.js';
8
6
  import { retryFetchBalance } from './balance-retry.js';
9
7
  import { flushStats, loadStats, getLiveSpendUsd } from '../stats/tracker.js';
@@ -238,7 +236,7 @@ export async function startCommand(options) {
238
236
  // Full wallet address is shown so the user can copy-paste it to fund the wallet.
239
237
  console.log(chalk.dim(' Wallet: ') + (walletAddress || chalk.yellow('not set')));
240
238
  console.log(chalk.dim(' Dir: ') + workDir);
241
- console.log(chalk.dim(' Dashboard: ') + (panelUrl ? chalk.cyan(panelUrl) : chalk.cyan('franklin panel') + chalk.dim(' → http://localhost:3100')));
239
+ console.log(chalk.dim(' Dashboard: ') + (panelUrl ? chalk.cyan(panelUrl) : chalk.cyan('franklin panel')));
242
240
  console.log(chalk.dim(' Help: ') + chalk.cyan('/help'));
243
241
  console.log('');
244
242
  // Balance fetcher — used at startup and after each turn.
@@ -737,7 +735,7 @@ async function runWithBasicUI(agentConfig, model, workDir, initialInput) {
737
735
  async function startPanelBackground(startPort) {
738
736
  const MAX_ATTEMPTS = 20;
739
737
  try {
740
- const { createPanelServer } = await import('../panel/server.js');
738
+ const { createPanelServer, writePanelUrlFile } = await import('../panel/server.js');
741
739
  return await new Promise((resolve) => {
742
740
  const tryListen = (port, attempt) => {
743
741
  const server = createPanelServer(port);
@@ -750,18 +748,11 @@ async function startPanelBackground(startPort) {
750
748
  });
751
749
  server.listen(port, '127.0.0.1', () => {
752
750
  server.unref?.();
753
- const url = `http://localhost:${port}`;
754
- // Persist the bound URL so the agent context (assembled per-turn)
755
- // can point users at /#wallet for funding without baking in the
756
- // 3100 default — the panel auto-increments past EADDRINUSE.
757
- // Best-effort write: a stale file from a crashed run is harmless,
758
- // since the user just sees a dead link.
759
- try {
760
- fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
761
- fs.writeFileSync(path.join(BLOCKRUN_DIR, 'panel-url'), url, 'utf8');
762
- }
763
- catch { /* best-effort */ }
764
- resolve(url);
751
+ // Persist the launch URL (0600, token included) so the agent's
752
+ // `franklin panel --open wallet` finds the bound port; the panel
753
+ // auto-increments past EADDRINUSE. A stale file from a crashed run
754
+ // is harmless: --open probes it and reports no running panel.
755
+ resolve(writePanelUrlFile(port));
765
756
  });
766
757
  };
767
758
  tryListen(startPort, 0);
package/dist/config.d.ts CHANGED
@@ -15,6 +15,14 @@ export declare function isEvmChain(chain: Chain): boolean;
15
15
  export declare const CHAIN_LABELS: Record<Chain, string>;
16
16
  export declare const BLOCKRUN_DIR: string;
17
17
  export declare const CHAIN_FILE: string;
18
+ /**
19
+ * ~/.blockrun holds session transcripts, the LLM audit log, cost and trade
20
+ * ledgers, and wallet keys. Created under the default umask it is 755 with
21
+ * 644 files, so any other account on the machine can read all of it.
22
+ * Owner-only, like ~/.ssh. Runs once per CLI start; never touches a
23
+ * directory owned by someone else.
24
+ */
25
+ export declare function hardenBlockrunDir(): void;
18
26
  export declare const API_URLS: Record<Chain, string>;
19
27
  export declare const DEFAULT_PROXY_PORT = 8402;
20
28
  export declare const MARKET_URL: string;
package/dist/config.js CHANGED
@@ -34,6 +34,32 @@ export const CHAIN_LABELS = {
34
34
  };
35
35
  export const BLOCKRUN_DIR = path.join(os.homedir(), '.blockrun');
36
36
  export const CHAIN_FILE = path.join(BLOCKRUN_DIR, 'payment-chain');
37
+ /**
38
+ * ~/.blockrun holds session transcripts, the LLM audit log, cost and trade
39
+ * ledgers, and wallet keys. Created under the default umask it is 755 with
40
+ * 644 files, so any other account on the machine can read all of it.
41
+ * Owner-only, like ~/.ssh. Runs once per CLI start; never touches a
42
+ * directory owned by someone else.
43
+ */
44
+ export function hardenBlockrunDir() {
45
+ if (process.platform === 'win32')
46
+ return;
47
+ try {
48
+ const st = fs.statSync(BLOCKRUN_DIR);
49
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid())
50
+ return;
51
+ if ((st.mode & 0o077) !== 0)
52
+ fs.chmodSync(BLOCKRUN_DIR, 0o700);
53
+ }
54
+ catch (err) {
55
+ if (err.code === 'ENOENT') {
56
+ try {
57
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true, mode: 0o700 });
58
+ }
59
+ catch { /* best-effort */ }
60
+ }
61
+ }
62
+ }
37
63
  export const API_URLS = {
38
64
  base: 'https://blockrun.ai/api',
39
65
  solana: 'https://sol.blockrun.ai/api',
package/dist/index.js CHANGED
@@ -31,7 +31,9 @@ import { buildContentCommand } from './commands/content.js';
31
31
  import { predictCommand } from './commands/predict.js';
32
32
  import { loginCommand, logoutCommand } from './commands/login.js';
33
33
  import { useWalletMode } from './payments/auth-mode.js';
34
- import { VERSION as version } from './config.js';
34
+ import { VERSION as version, hardenBlockrunDir } from './config.js';
35
+ // Before any command reads or writes ~/.blockrun (GHSA-jx74-262x-94p3 follow-up).
36
+ hardenBlockrunDir();
35
37
  // `--wallet` is process-global rather than a per-command option: it has to take
36
38
  // effect before anything resolves a pay mode, and it belongs on `balance`,
37
39
  // `doctor` and `models` too, not just `start`. Applying it straight from argv
@@ -120,6 +122,7 @@ program
120
122
  .command('panel')
121
123
  .description('Open the Franklin dashboard (localhost:3100)')
122
124
  .option('-p, --port <port>', 'Dashboard port', '3100')
125
+ .option('--open [section]', 'Open the already-running panel in the browser (e.g. --open wallet)')
123
126
  .action(async (options) => {
124
127
  const { panelCommand } = await import('./commands/panel.js');
125
128
  await panelCommand(options);
@@ -917,6 +917,8 @@ a:hover { text-decoration:underline; }
917
917
  // refuses wallet, spend, and state-changing routes without it.
918
918
  (() => {
919
919
  const PANEL_TOKEN = ${JSON.stringify(panelToken)};
920
+ // EventSource cannot set headers; /api/events reads it from ?token=.
921
+ window.__FRANKLIN_PANEL_TOKEN = PANEL_TOKEN;
920
922
  const nativeFetch = window.fetch.bind(window);
921
923
  window.fetch = (input, init = {}) => {
922
924
  const headers = new Headers(init.headers || {});
@@ -1425,7 +1427,7 @@ document.getElementById('wallet-import-btn').addEventListener('click', async ()
1425
1427
  }
1426
1428
  });
1427
1429
 
1428
- const es = new EventSource('/api/events');
1430
+ const es = new EventSource('/api/events?token=' + encodeURIComponent(window.__FRANKLIN_PANEL_TOKEN));
1429
1431
  const dot = document.getElementById('dot');
1430
1432
  const statusEl = document.getElementById('status');
1431
1433
  es.onopen = () => { dot.className = 'dot on'; statusEl.textContent = 'live'; };
@@ -4,4 +4,20 @@
4
4
  * Zero external dependencies — uses node:http only.
5
5
  */
6
6
  import http from 'node:http';
7
+ /**
8
+ * The page itself is gated on the token too, passed once as `/?token=`.
9
+ * Without that, any local client (another OS user, a process reaching the
10
+ * port through an ssh -L tunnel) could GET `/`, read the token out of the
11
+ * HTML, and call /api/wallet/secret. Only someone who can see the terminal
12
+ * that started the panel, or read the 0600 panel-url file, has the link.
13
+ */
14
+ export declare function getPanelLaunchUrl(port: number): string;
15
+ export declare const PANEL_URL_FILE: string;
16
+ /**
17
+ * Persist the launch URL (token included) for `franklin panel --open`.
18
+ * Owner-only: the file is the key to the panel. writeFileSync's mode only
19
+ * applies on create, so chmod covers a file left by an older release.
20
+ * Returns the launch URL.
21
+ */
22
+ export declare function writePanelUrlFile(port: number): string;
7
23
  export declare function createPanelServer(port: number): http.Server;
@@ -21,6 +21,7 @@ import { describeWiring } from '../trading/providers/registry.js';
21
21
  import { listTasks, readTaskMeta, readTaskEvents, } from '../tasks/store.js';
22
22
  import { reconcileLostTasks } from '../tasks/lost-detection.js';
23
23
  import { taskLogPath } from '../tasks/paths.js';
24
+ import { isSafePathSegment } from '../storage/safe-id.js';
24
25
  import { isTerminalTaskStatus } from '../tasks/types.js';
25
26
  import { readLiveAgents } from '../session/live-registry.js';
26
27
  import { BLOCKRUN_DIR } from '../config.js';
@@ -95,12 +96,49 @@ function isLocalHostHeader(req) {
95
96
  */
96
97
  const PANEL_TOKEN = crypto.randomBytes(32).toString('hex');
97
98
  const PANEL_TOKEN_HEADER = 'x-franklin-panel-token';
98
- function hasPanelToken(req) {
99
- const got = req.headers[PANEL_TOKEN_HEADER];
99
+ function tokenMatches(got) {
100
100
  if (typeof got !== 'string' || got.length !== PANEL_TOKEN.length)
101
101
  return false;
102
102
  return crypto.timingSafeEqual(Buffer.from(got), Buffer.from(PANEL_TOKEN));
103
103
  }
104
+ function hasPanelToken(req) {
105
+ return tokenMatches(req.headers[PANEL_TOKEN_HEADER]);
106
+ }
107
+ /**
108
+ * The page itself is gated on the token too, passed once as `/?token=`.
109
+ * Without that, any local client (another OS user, a process reaching the
110
+ * port through an ssh -L tunnel) could GET `/`, read the token out of the
111
+ * HTML, and call /api/wallet/secret. Only someone who can see the terminal
112
+ * that started the panel, or read the 0600 panel-url file, has the link.
113
+ */
114
+ export function getPanelLaunchUrl(port) {
115
+ return `http://localhost:${port}/?token=${PANEL_TOKEN}`;
116
+ }
117
+ export const PANEL_URL_FILE = path.join(BLOCKRUN_DIR, 'panel-url');
118
+ /**
119
+ * Persist the launch URL (token included) for `franklin panel --open`.
120
+ * Owner-only: the file is the key to the panel. writeFileSync's mode only
121
+ * applies on create, so chmod covers a file left by an older release.
122
+ * Returns the launch URL.
123
+ */
124
+ export function writePanelUrlFile(port) {
125
+ const launch = getPanelLaunchUrl(port);
126
+ try {
127
+ fs.mkdirSync(BLOCKRUN_DIR, { recursive: true });
128
+ fs.writeFileSync(PANEL_URL_FILE, launch, { encoding: 'utf8', mode: 0o600 });
129
+ fs.chmodSync(PANEL_URL_FILE, 0o600);
130
+ }
131
+ catch { /* best-effort: the terminal still shows the link */ }
132
+ return launch;
133
+ }
134
+ const LOCKED_PAGE = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Franklin Panel</title>
135
+ <meta name="referrer" content="no-referrer"></head>
136
+ <body style="font-family:system-ui,sans-serif;max-width:34rem;margin:4rem auto;line-height:1.5">
137
+ <h1>Franklin Panel</h1>
138
+ <p>This link is missing its access token.</p>
139
+ <p>Open the Dashboard link printed in the terminal where Franklin is running,
140
+ or run <code>franklin panel --open</code>.</p>
141
+ </body></html>`;
104
142
  function isLocalPanelRequest(req) {
105
143
  return isLoopback(req) && isTrustedPanelOrigin(req) && hasPanelToken(req);
106
144
  }
@@ -166,6 +204,17 @@ export function createPanelServer(port) {
166
204
  res.end('Forbidden');
167
205
  return;
168
206
  }
207
+ // Every API route needs the page's token, read-only ones included.
208
+ // Loopback + local Host does not tell OS users apart: on a shared machine
209
+ // another account, or anyone reaching the port through an ssh -L tunnel,
210
+ // passes both and could read transcripts and the audit log
211
+ // (GHSA-jx74-262x-94p3). EventSource cannot set headers, so /api/events
212
+ // alone may carry the token as ?token=.
213
+ if (p.startsWith('/api/') && !hasPanelToken(req)
214
+ && !(p === '/api/events' && tokenMatches(url.searchParams.get('token')))) {
215
+ json(res, { error: 'forbidden' }, 403);
216
+ return;
217
+ }
169
218
  // Anything that changes state needs the page's token, including routes
170
219
  // that only check loopback (task cancel).
171
220
  if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS' && !hasPanelToken(req)) {
@@ -174,12 +223,15 @@ export function createPanelServer(port) {
174
223
  }
175
224
  // ─── HTML ──
176
225
  if (p === '/') {
177
- res.writeHead(200, {
226
+ const ok = tokenMatches(url.searchParams.get('token'));
227
+ res.writeHead(ok ? 200 : 401, {
178
228
  'Content-Type': 'text/html; charset=utf-8',
179
229
  'Cache-Control': 'no-store, no-cache, must-revalidate',
180
230
  'Pragma': 'no-cache',
231
+ // The URL carries the token; never send it on as a Referer.
232
+ 'Referrer-Policy': 'no-referrer',
181
233
  });
182
- res.end(html);
234
+ res.end(ok ? html : LOCKED_PAGE);
183
235
  return;
184
236
  }
185
237
  // ─── Static assets ──
@@ -768,9 +820,14 @@ export function createPanelServer(port) {
768
820
  if (p.startsWith('/api/tasks/')) {
769
821
  const rest = p.slice('/api/tasks/'.length);
770
822
  const segments = rest.split('/');
771
- const runId = decodeURIComponent(segments[0] || '');
823
+ let runId = '';
824
+ try {
825
+ runId = decodeURIComponent(segments[0] || '');
826
+ }
827
+ catch { /* malformed %-escape */ }
772
828
  const sub = segments[1];
773
- if (!runId) {
829
+ // getTaskDir also refuses these; answer 404 here instead of a 500.
830
+ if (!isSafePathSegment(runId)) {
774
831
  res.writeHead(404);
775
832
  res.end('Not found');
776
833
  return;
@@ -815,7 +815,7 @@ function sleep(ms) {
815
815
  async function handleBasePayment(response, url, method, headers, body, privateKey, fromAddress, timeoutMs = getProxyRequestTimeoutMs(), model = 'unknown') {
816
816
  const paymentHeader = await extractPaymentHeader(response);
817
817
  if (!paymentHeader) {
818
- throw new Error('402 Payment Required — wallet may need funding. Open http://localhost:3100/#wallet to deposit USDC (or run: franklin balance)');
818
+ throw new Error('402 Payment Required — wallet may need funding. Run: franklin panel --open wallet to deposit USDC (or: franklin balance)');
819
819
  }
820
820
  const paymentRequired = parsePaymentRequired(paymentHeader);
821
821
  const details = extractPaymentDetails(paymentRequired);
@@ -852,7 +852,7 @@ async function handleBasePayment(response, url, method, headers, body, privateKe
852
852
  async function handleSolanaPayment(response, url, method, headers, body, privateKey, fromAddress, timeoutMs = getProxyRequestTimeoutMs(), model = 'unknown') {
853
853
  const paymentHeader = await extractPaymentHeader(response);
854
854
  if (!paymentHeader) {
855
- throw new Error('402 Payment Required — wallet may need funding. Open http://localhost:3100/#wallet to deposit USDC (or run: franklin balance)');
855
+ throw new Error('402 Payment Required — wallet may need funding. Run: franklin panel --open wallet to deposit USDC (or: franklin balance)');
856
856
  }
857
857
  const paymentRequired = parsePaymentRequired(paymentHeader);
858
858
  const details = extractPaymentDetails(paymentRequired, SOLANA_NETWORK);
@@ -7,6 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { randomUUID } from 'node:crypto';
9
9
  import { BLOCKRUN_DIR } from '../config.js';
10
+ import { assertSafePathSegment } from '../storage/safe-id.js';
10
11
  const MAX_SESSIONS = 20; // Keep last 20 sessions
11
12
  let resolvedSessionsDir = null;
12
13
  // When in-process tests run interactiveSession() with model="local/test*",
@@ -55,9 +56,7 @@ function getSessionsDir() {
55
56
  }
56
57
  function sessionPath(id) {
57
58
  // 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
- }
59
+ assertSafePathSegment(id, 'session id');
61
60
  return path.join(getSessionsDir(), `${id}.jsonl`);
62
61
  }
63
62
  /** Get the absolute path to a session's JSONL file (for external readers like search). */
@@ -65,6 +64,7 @@ export function getSessionFilePath(id) {
65
64
  return sessionPath(id);
66
65
  }
67
66
  function metaPath(id) {
67
+ assertSafePathSegment(id, 'session id');
68
68
  return path.join(getSessionsDir(), `${id}.meta.json`);
69
69
  }
70
70
  function withWritableSessionDir(action) {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Ids that become a single path segment (session ids, task run ids).
3
+ *
4
+ * These ids reach the filesystem helpers from URLs (panel /api/sessions/:id,
5
+ * /api/tasks/:runId) after decodeURIComponent, so `..%2F` arrives as `../`.
6
+ * Validate in the shared path helper, not in each route: GHSA-jx74-262x-94p3
7
+ * fixed the sessions route while the tasks route kept the same hole.
8
+ */
9
+ export declare function isSafePathSegment(id: unknown): id is string;
10
+ export declare function assertSafePathSegment(id: unknown, kind: string): asserts id is string;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Ids that become a single path segment (session ids, task run ids).
3
+ *
4
+ * These ids reach the filesystem helpers from URLs (panel /api/sessions/:id,
5
+ * /api/tasks/:runId) after decodeURIComponent, so `..%2F` arrives as `../`.
6
+ * Validate in the shared path helper, not in each route: GHSA-jx74-262x-94p3
7
+ * fixed the sessions route while the tasks route kept the same hole.
8
+ */
9
+ import path from 'node:path';
10
+ export function isSafePathSegment(id) {
11
+ return (typeof id === 'string' &&
12
+ id.length > 0 &&
13
+ id !== '.' &&
14
+ !id.includes('..') &&
15
+ !id.includes('/') &&
16
+ !id.includes('\\') &&
17
+ !id.includes('\0') &&
18
+ id === path.basename(id));
19
+ }
20
+ export function assertSafePathSegment(id, kind) {
21
+ if (!isSafePathSegment(id)) {
22
+ throw new Error(`Invalid ${kind}: ${JSON.stringify(id)}`);
23
+ }
24
+ }
@@ -23,6 +23,7 @@ import fs from 'node:fs';
23
23
  import os from 'node:os';
24
24
  import path from 'node:path';
25
25
  import { BLOCKRUN_DIR } from '../config.js';
26
+ import { assertSafePathSegment } from '../storage/safe-id.js';
26
27
  const LEGACY_FRANKLIN_HOME = path.join(os.homedir(), '.franklin');
27
28
  function franklinHome() {
28
29
  return process.env.FRANKLIN_HOME || BLOCKRUN_DIR;
@@ -34,6 +35,9 @@ export function getLegacyTasksDir() {
34
35
  return path.join(LEGACY_FRANKLIN_HOME, 'tasks');
35
36
  }
36
37
  export function getTaskDir(runId) {
38
+ // Run ids reach here from URLs (panel /api/tasks/:runId); never let one
39
+ // escape the tasks dir. Every task path helper routes through here.
40
+ assertSafePathSegment(runId, 'task run id');
37
41
  // Prefer the primary location. If a task already exists in the
38
42
  // legacy ~/.franklin/tasks/ — either created by an older release or
39
43
  // by a runner subprocess started before this version was installed —
package/dist/ui/app.js CHANGED
@@ -653,7 +653,7 @@ function InputBox({ input, setInput, onSubmit, model, balance, chain, walletTail
653
653
  const m = balance.match(/\$([\d.]+)/);
654
654
  const num = m ? parseFloat(m[1]) : null;
655
655
  if (num !== null && num < 0.50) {
656
- return _jsxs(_Fragment, { children: [_jsx(Text, { color: "red", bold: true, children: balance }), _jsx(Text, { color: "red", children: " \u26A0 low \u2014 deposit at http://localhost:3100/#wallet or /model free" })] });
656
+ return _jsxs(_Fragment, { children: [_jsx(Text, { color: "red", bold: true, children: balance }), _jsx(Text, { color: "red", children: " \u26A0 low \u2014 deposit: franklin panel --open wallet, or /model free" })] });
657
657
  }
658
658
  if (num !== null && num < 1.00) {
659
659
  return _jsx(Text, { color: "yellow", children: balance });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.18",
3
+ "version": "3.49.20",
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": {