@blockrun/franklin 3.49.21 → 3.49.23

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.
@@ -2,6 +2,7 @@ import { spawn, execFileSync, execSync } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import chalk from 'chalk';
5
+ import { proxyBaseUrl } from '../proxy/claude-settings.js';
5
6
  import { BLOCKRUN_DIR, DEFAULT_PROXY_PORT } from '../config.js';
6
7
  const PID_FILE = path.join(BLOCKRUN_DIR, 'franklin.pid');
7
8
  const LOG_FILE = path.join(BLOCKRUN_DIR, 'franklin-debug.log');
@@ -64,7 +65,7 @@ export async function daemonCommand(action, options) {
64
65
  const existing = readPid();
65
66
  if (existing && isRunning(existing)) {
66
67
  console.log(chalk.yellow(`franklin daemon already running (PID ${existing})`));
67
- console.log(chalk.dim(` Proxy: http://localhost:${port}/api`));
68
+ console.log(chalk.dim(` Proxy: ${proxyBaseUrl(port)}`));
68
69
  return;
69
70
  }
70
71
  const daemonBin = findDaemonBinary();
@@ -81,7 +82,7 @@ export async function daemonCommand(action, options) {
81
82
  child.unref();
82
83
  fs.writeFileSync(PID_FILE, String(child.pid));
83
84
  console.log(chalk.green(`✓ franklin daemon started (PID ${child.pid})`));
84
- console.log(chalk.dim(` Proxy: http://localhost:${port}/api`));
85
+ console.log(chalk.dim(` Proxy: ${proxyBaseUrl(port)}`));
85
86
  console.log(chalk.dim(` Logs: ${LOG_FILE}`));
86
87
  break;
87
88
  }
@@ -127,7 +128,7 @@ export async function daemonCommand(action, options) {
127
128
  if (isRunning(pid)) {
128
129
  console.log(chalk.green(`✓ franklin daemon running`));
129
130
  console.log(` PID: ${chalk.bold(pid)}`);
130
- console.log(` Proxy: ${chalk.cyan(`http://localhost:${port}/api`)}`);
131
+ console.log(` Proxy: ${chalk.cyan(proxyBaseUrl(port))}`);
131
132
  console.log(chalk.dim(` Logs: ${LOG_FILE}`));
132
133
  }
133
134
  else {
@@ -3,7 +3,8 @@ import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import chalk from 'chalk';
5
5
  import { DEFAULT_PROXY_PORT } from '../config.js';
6
- const CLAUDE_SETTINGS_FILE = path.join(os.homedir(), '.claude', 'settings.json');
6
+ import { CLAUDE_SETTINGS_FILE, proxyBaseUrl, restrictToOwner } from '../proxy/claude-settings.js';
7
+ import { getOrCreateProxyToken } from '../proxy/token.js';
7
8
  const LAUNCH_AGENT_DIR = path.join(os.homedir(), 'Library', 'LaunchAgents');
8
9
  const LAUNCH_AGENT_PLIST = path.join(LAUNCH_AGENT_DIR, 'ai.blockrun.franklin.plist');
9
10
  const LEGACY_LAUNCH_AGENT_PLIST = path.join(LAUNCH_AGENT_DIR, 'ai.blockrun.runcode.plist');
@@ -25,8 +26,10 @@ export async function initCommand(options) {
25
26
  }
26
27
  settings.env = {
27
28
  ...(settings.env ?? {}),
28
- ANTHROPIC_BASE_URL: `http://localhost:${port}/api`,
29
- ANTHROPIC_AUTH_TOKEN: 'x402-proxy-handles-auth',
29
+ // 127.0.0.1, never localhost: see proxy/claude-settings.ts.
30
+ ANTHROPIC_BASE_URL: proxyBaseUrl(port),
31
+ // The proxy refuses requests without its token (proxy/token.ts).
32
+ ANTHROPIC_AUTH_TOKEN: getOrCreateProxyToken(),
30
33
  ANTHROPIC_MODEL: 'blockrun/auto',
31
34
  ANTHROPIC_DEFAULT_SONNET_MODEL: 'anthropic/claude-sonnet-4.6',
32
35
  ANTHROPIC_DEFAULT_OPUS_MODEL: 'anthropic/claude-opus-5',
@@ -34,6 +37,7 @@ export async function initCommand(options) {
34
37
  };
35
38
  fs.mkdirSync(path.dirname(CLAUDE_SETTINGS_FILE), { recursive: true });
36
39
  fs.writeFileSync(CLAUDE_SETTINGS_FILE, JSON.stringify(settings, null, 2));
40
+ restrictToOwner(CLAUDE_SETTINGS_FILE); // holds the proxy token now
37
41
  console.log(chalk.green(`✓ Configured ${CLAUDE_SETTINGS_FILE}`));
38
42
  // ── 2. Install macOS LaunchAgent (auto-start on login) ─────────────────
39
43
  if (process.platform === 'darwin') {
@@ -9,6 +9,8 @@ import { loadChain, CHAIN_LABELS, DEFAULT_PROXY_PORT } from '../config.js';
9
9
  import { gatewayBase } from '../payments/auth-mode.js';
10
10
  import { loadConfig } from './config.js';
11
11
  import { printBanner } from '../banner.js';
12
+ import { proxyBaseUrl, migrateClaudeSettings, CLAUDE_SETTINGS_FILE } from '../proxy/claude-settings.js';
13
+ import { getOrCreateProxyToken } from '../proxy/token.js';
12
14
  export async function proxyCommand(options) {
13
15
  const version = options.version ?? '1.0.0';
14
16
  const chain = loadChain();
@@ -36,7 +38,7 @@ export async function proxyCommand(options) {
36
38
  if (model)
37
39
  console.log(`Model: ${chalk.green(model)}`);
38
40
  console.log(`Fallback: ${fallbackEnabled ? chalk.green('enabled') : chalk.yellow('disabled')}`);
39
- console.log(`Proxy: ${chalk.cyan(`http://localhost:${port}`)}`);
41
+ console.log(`Proxy: ${chalk.cyan(proxyBaseUrl(port))}`);
40
42
  console.log(`Backend: ${chalk.dim(apiUrl)}\n`);
41
43
  const server = createProxy({
42
44
  port,
@@ -63,7 +65,7 @@ export async function proxyCommand(options) {
63
65
  if (model)
64
66
  console.log(`Model: ${chalk.green(model)}`);
65
67
  console.log(`Fallback: ${fallbackEnabled ? chalk.green('enabled') : chalk.yellow('disabled')}`);
66
- console.log(`Proxy: ${chalk.cyan(`http://localhost:${port}`)}`);
68
+ console.log(`Proxy: ${chalk.cyan(proxyBaseUrl(port))}`);
67
69
  console.log(`Backend: ${chalk.dim(apiUrl)}\n`);
68
70
  const server = createProxy({
69
71
  port,
@@ -88,16 +90,24 @@ function launchProxy(server, port, debug) {
88
90
  });
89
91
  // Bind to loopback ONLY — this proxy signs x402 USDC payments from the local
90
92
  // wallet on every request, so it must never be reachable from the LAN. Every
91
- // other Franklin server binds 127.0.0.1; the banner below says "localhost".
93
+ // other Franklin server binds 127.0.0.1, and every URL we print or write
94
+ // says 127.0.0.1 too (see proxy/claude-settings.ts for why not localhost).
92
95
  server.listen(port, '127.0.0.1', () => {
93
96
  console.log(chalk.green(`✓ Proxy running on port ${port}`));
97
+ // `franklin daemon` and the LaunchAgent both start here, so this one call
98
+ // updates the env block an older `franklin init` wrote (127.0.0.1 base
99
+ // URL, real proxy token in place of the old placeholder).
100
+ const token = getOrCreateProxyToken();
101
+ if (migrateClaudeSettings(token)) {
102
+ console.log(chalk.yellow(` Updated Franklin's settings in ${CLAUDE_SETTINGS_FILE} (127.0.0.1 address, proxy token). Restart Claude Code to pick them up.`));
103
+ }
94
104
  console.log(chalk.dim(` Usage tracking: ~/.blockrun/franklin-stats.json`));
95
105
  if (debug)
96
106
  console.log(chalk.dim(` Debug log: ~/.blockrun/franklin-debug.log`));
97
107
  console.log(chalk.dim(` Run 'franklin stats' to view statistics\n`));
98
108
  console.log('Set these in your shell to route Anthropic-compatible CLI agents through franklin:\n');
99
- console.log(chalk.bold(` export ANTHROPIC_BASE_URL=http://localhost:${port}/api`));
100
- console.log(chalk.bold(` export ANTHROPIC_AUTH_TOKEN=x402-proxy-handles-auth`));
109
+ console.log(chalk.bold(` export ANTHROPIC_BASE_URL=${proxyBaseUrl(port)}`));
110
+ console.log(chalk.bold(` export ANTHROPIC_AUTH_TOKEN=$(cat ~/.blockrun/proxy-token)`));
101
111
  console.log(`\nThen run ${chalk.bold('claude')} in another terminal.`);
102
112
  });
103
113
  const shutdown = () => {
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Where Anthropic-compatible CLI agents (Claude Code) are pointed at the
3
+ * Franklin proxy, and the one-time fix for links written by older releases.
4
+ *
5
+ * The proxy binds 127.0.0.1 only. `localhost` resolves to ::1 first in Node
6
+ * and most clients, and another account on the machine can listen on
7
+ * [::1]:<port> beside our 127.0.0.1:<port> without a bind conflict. A
8
+ * `localhost` base URL would send that listener every prompt, and its
9
+ * replies would reach the agent as model output, tool calls included.
10
+ */
11
+ export declare const CLAUDE_SETTINGS_FILE: string;
12
+ /**
13
+ * The auth value `franklin init` wrote before 3.49.23, when the proxy took no
14
+ * token. It still marks an env block as Franklin's for the migration below.
15
+ */
16
+ export declare const PROXY_AUTH_PLACEHOLDER = "x402-proxy-handles-auth";
17
+ export declare function proxyBaseUrl(port: number): string;
18
+ /** The settings file now holds the proxy token: owner-only, like the token file. */
19
+ export declare function restrictToOwner(file: string): void;
20
+ /**
21
+ * Bring the env block an older `franklin init` wrote up to date: a
22
+ * `localhost` ANTHROPIC_BASE_URL becomes 127.0.0.1, and the placeholder
23
+ * ANTHROPIC_AUTH_TOKEN becomes the proxy's real token. Only touches a block
24
+ * that is Franklin's (placeholder or current token), so a user's own
25
+ * settings are left alone. Returns true when it changed the file.
26
+ */
27
+ export declare function migrateClaudeSettings(token: string, file?: string): boolean;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Where Anthropic-compatible CLI agents (Claude Code) are pointed at the
3
+ * Franklin proxy, and the one-time fix for links written by older releases.
4
+ *
5
+ * The proxy binds 127.0.0.1 only. `localhost` resolves to ::1 first in Node
6
+ * and most clients, and another account on the machine can listen on
7
+ * [::1]:<port> beside our 127.0.0.1:<port> without a bind conflict. A
8
+ * `localhost` base URL would send that listener every prompt, and its
9
+ * replies would reach the agent as model output, tool calls included.
10
+ */
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ export const CLAUDE_SETTINGS_FILE = path.join(os.homedir(), '.claude', 'settings.json');
15
+ /**
16
+ * The auth value `franklin init` wrote before 3.49.23, when the proxy took no
17
+ * token. It still marks an env block as Franklin's for the migration below.
18
+ */
19
+ export const PROXY_AUTH_PLACEHOLDER = 'x402-proxy-handles-auth';
20
+ export function proxyBaseUrl(port) {
21
+ return `http://127.0.0.1:${port}/api`;
22
+ }
23
+ /** The settings file now holds the proxy token: owner-only, like the token file. */
24
+ export function restrictToOwner(file) {
25
+ if (process.platform === 'win32')
26
+ return;
27
+ try {
28
+ fs.chmodSync(file, 0o600);
29
+ }
30
+ catch { /* best-effort */ }
31
+ }
32
+ const LEGACY_BASE_URL = /^http:\/\/localhost:(\d{1,5})\/api\/?$/;
33
+ /**
34
+ * Bring the env block an older `franklin init` wrote up to date: a
35
+ * `localhost` ANTHROPIC_BASE_URL becomes 127.0.0.1, and the placeholder
36
+ * ANTHROPIC_AUTH_TOKEN becomes the proxy's real token. Only touches a block
37
+ * that is Franklin's (placeholder or current token), so a user's own
38
+ * settings are left alone. Returns true when it changed the file.
39
+ */
40
+ export function migrateClaudeSettings(token, file = CLAUDE_SETTINGS_FILE) {
41
+ let raw;
42
+ try {
43
+ raw = fs.readFileSync(file, 'utf-8');
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ let settings;
49
+ try {
50
+ settings = JSON.parse(raw);
51
+ }
52
+ catch {
53
+ return false; // never rewrite a file we cannot parse
54
+ }
55
+ const env = settings.env;
56
+ if (!env)
57
+ return false;
58
+ const auth = env.ANTHROPIC_AUTH_TOKEN;
59
+ if (auth !== PROXY_AUTH_PLACEHOLDER && auth !== token)
60
+ return false;
61
+ let changed = false;
62
+ if (auth === PROXY_AUTH_PLACEHOLDER) {
63
+ env.ANTHROPIC_AUTH_TOKEN = token;
64
+ changed = true;
65
+ }
66
+ const current = env.ANTHROPIC_BASE_URL;
67
+ const m = typeof current === 'string' ? LEGACY_BASE_URL.exec(current) : null;
68
+ if (m) {
69
+ env.ANTHROPIC_BASE_URL = proxyBaseUrl(Number(m[1]));
70
+ changed = true;
71
+ }
72
+ if (!changed)
73
+ return false;
74
+ try {
75
+ fs.writeFileSync(file, JSON.stringify(settings, null, 2) + (raw.endsWith('\n') ? '\n' : ''));
76
+ restrictToOwner(file);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
@@ -9,6 +9,7 @@ export interface ProxyOptions {
9
9
  fallbackEnabled?: boolean;
10
10
  requestTimeoutMs?: number;
11
11
  streamTimeoutMs?: number;
12
+ authToken?: string;
12
13
  }
13
14
  /**
14
15
  * Decide the `max_tokens` the proxy forwards upstream.
@@ -14,6 +14,7 @@ import { estimateCost } from '../pricing.js';
14
14
  import { freeVisionModel, isFreeModelId } from '../free-models.js';
15
15
  import { getMaxOutputTokens } from '../agent/optimize.js';
16
16
  import { VERSION } from '../config.js';
17
+ import { getOrCreateProxyToken, hasProxyToken } from './token.js';
17
18
  // User-Agent for backend requests
18
19
  const USER_AGENT = `franklin/${VERSION}`;
19
20
  const X_FRANKLIN_VERSION = VERSION;
@@ -216,6 +217,7 @@ export function createProxy(options) {
216
217
  // process.env for the rest of the process — and for any sibling proxy.
217
218
  const effectiveRequestTimeoutMs = options.requestTimeoutMs ?? getProxyRequestTimeoutMs();
218
219
  const effectiveStreamTimeoutMs = options.streamTimeoutMs ?? getProxyStreamTimeoutMs();
220
+ const authToken = options.authToken ?? getOrCreateProxyToken();
219
221
  let baseWallet = null;
220
222
  let solanaWallet = null;
221
223
  // Base and Arc both pay from the EVM wallet; the 402 names the network.
@@ -250,6 +252,22 @@ export function createProxy(options) {
250
252
  res.end();
251
253
  return;
252
254
  }
255
+ // Every request that can reach the gateway, and so spend from the
256
+ // wallet, must carry the proxy token. Loopback alone is not enough:
257
+ // other accounts and local web pages can reach 127.0.0.1 too.
258
+ const pathOnly = (req.url || '').replace(/^\/api/, '').split('?')[0];
259
+ if (pathOnly !== '/health' && !hasProxyToken(req.headers, authToken)) {
260
+ res.writeHead(401, { 'Content-Type': 'application/json' });
261
+ res.end(JSON.stringify({
262
+ type: 'error',
263
+ error: {
264
+ type: 'authentication_error',
265
+ message: 'Franklin proxy: missing or wrong token. Run `franklin init` to configure Claude Code, ' +
266
+ 'or set ANTHROPIC_AUTH_TOKEN to the contents of ~/.blockrun/proxy-token.',
267
+ },
268
+ }));
269
+ return;
270
+ }
253
271
  // Rate limit paid endpoints (anything but /health and /v1/models)
254
272
  const rawPath = req.url?.replace(/^\/api/, '') || '';
255
273
  const isReadOnly = rawPath.startsWith('/health') || rawPath.startsWith('/v1/models');
@@ -445,9 +463,14 @@ export function createProxy(options) {
445
463
  'X-Franklin-Version': X_FRANKLIN_VERSION,
446
464
  };
447
465
  for (const [key, value] of Object.entries(req.headers)) {
448
- if (key.toLowerCase() !== 'host' &&
449
- key.toLowerCase() !== 'content-length' &&
450
- key.toLowerCase() !== 'user-agent' && // Don't forward client's user-agent
466
+ const lower = key.toLowerCase();
467
+ if (lower !== 'host' &&
468
+ lower !== 'content-length' &&
469
+ lower !== 'user-agent' && // Don't forward client's user-agent
470
+ // The client's credential is the local proxy token: never send
471
+ // it upstream. applyGatewayAuth adds the real gateway auth.
472
+ lower !== 'authorization' &&
473
+ lower !== 'x-api-key' &&
451
474
  value) {
452
475
  headers[key] = Array.isArray(value) ? value[0] : value;
453
476
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The local proxy's access token.
3
+ *
4
+ * The proxy signs x402 payments from the user's wallet on every request, so
5
+ * reaching 127.0.0.1:<port> must not be enough to spend: any other account
6
+ * on the machine, or any page on a local dev server, can reach that port.
7
+ * Clients prove they are the user's own by sending this token, which lives
8
+ * in an owner-only file. `franklin init` writes it into Claude Code's
9
+ * settings as ANTHROPIC_AUTH_TOKEN, which Claude Code sends as
10
+ * `Authorization: Bearer <token>`.
11
+ */
12
+ export declare const PROXY_TOKEN_FILE: string;
13
+ /** Read the token, creating it (0600) on first use. Stable across restarts. */
14
+ export declare function getOrCreateProxyToken(file?: string): string;
15
+ /**
16
+ * True when the request carries the token as `Authorization: Bearer <t>`
17
+ * (ANTHROPIC_AUTH_TOKEN) or `x-api-key: <t>` (ANTHROPIC_API_KEY).
18
+ */
19
+ export declare function hasProxyToken(headers: Record<string, string | string[] | undefined>, token: string): boolean;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The local proxy's access token.
3
+ *
4
+ * The proxy signs x402 payments from the user's wallet on every request, so
5
+ * reaching 127.0.0.1:<port> must not be enough to spend: any other account
6
+ * on the machine, or any page on a local dev server, can reach that port.
7
+ * Clients prove they are the user's own by sending this token, which lives
8
+ * in an owner-only file. `franklin init` writes it into Claude Code's
9
+ * settings as ANTHROPIC_AUTH_TOKEN, which Claude Code sends as
10
+ * `Authorization: Bearer <token>`.
11
+ */
12
+ import crypto from 'node:crypto';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { BLOCKRUN_DIR } from '../config.js';
16
+ export const PROXY_TOKEN_FILE = path.join(BLOCKRUN_DIR, 'proxy-token');
17
+ const TOKEN_RE = /^[0-9a-f]{64}$/;
18
+ /** Read the token, creating it (0600) on first use. Stable across restarts. */
19
+ export function getOrCreateProxyToken(file = PROXY_TOKEN_FILE) {
20
+ try {
21
+ const existing = fs.readFileSync(file, 'utf8').trim();
22
+ if (TOKEN_RE.test(existing)) {
23
+ try {
24
+ fs.chmodSync(file, 0o600);
25
+ }
26
+ catch { /* best-effort */ }
27
+ return existing;
28
+ }
29
+ }
30
+ catch { /* missing: create below */ }
31
+ const token = crypto.randomBytes(32).toString('hex');
32
+ fs.mkdirSync(path.dirname(file), { recursive: true });
33
+ fs.writeFileSync(file, token + '\n', { mode: 0o600 });
34
+ fs.chmodSync(file, 0o600);
35
+ return token;
36
+ }
37
+ function safeEqual(got, want) {
38
+ if (got.length !== want.length)
39
+ return false;
40
+ return crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
41
+ }
42
+ /**
43
+ * True when the request carries the token as `Authorization: Bearer <t>`
44
+ * (ANTHROPIC_AUTH_TOKEN) or `x-api-key: <t>` (ANTHROPIC_API_KEY).
45
+ */
46
+ export function hasProxyToken(headers, token) {
47
+ const pick = (v) => (Array.isArray(v) ? v[0] : v);
48
+ const auth = pick(headers['authorization']);
49
+ if (typeof auth === 'string') {
50
+ const m = /^Bearer\s+(\S+)$/i.exec(auth.trim());
51
+ if (m && safeEqual(m[1], token))
52
+ return true;
53
+ }
54
+ const key = pick(headers['x-api-key']);
55
+ return typeof key === 'string' && safeEqual(key.trim(), token);
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/franklin",
3
- "version": "3.49.21",
3
+ "version": "3.49.23",
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": {