@blockrun/franklin 3.49.3 → 3.49.5
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.
- package/README.md +83 -65
- package/dist/agent/streaming-executor.js +6 -2
- package/dist/mcp/oauth.d.ts +1 -0
- package/dist/mcp/oauth.js +26 -7
- package/dist/panel/html.d.ts +1 -1
- package/dist/panel/html.js +13 -1
- package/dist/panel/server.js +29 -3
- package/dist/tools/browsex.d.ts +10 -0
- package/dist/tools/browsex.js +57 -0
- package/dist/tools/edit.js +4 -1
- package/dist/tools/glob.js +4 -0
- package/dist/tools/grep.js +53 -2
- package/dist/tools/read.js +8 -5
- package/dist/tools/sensitive-paths.d.ts +22 -0
- package/dist/tools/sensitive-paths.js +168 -0
- package/dist/tools/ssrf.js +5 -3
- package/dist/tools/webhook.d.ts +5 -4
- package/dist/tools/webhook.js +13 -43
- package/dist/tools/write.js +2 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
|
|
46
46
|
## The pitch in one paragraph
|
|
47
47
|
|
|
48
|
-
Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from
|
|
48
|
+
Franklin Agent is an **autonomous economic agent** — an AI that holds a USDC wallet and spends it to get real work done, with **trading as its flagship arena**. It buys live market data, proposes trade plans you approve before a cent moves, pursues long-running goals across sessions, keeps a wallet-bound trading journal, and picks the best model per task from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. You state an outcome and set a budget. Franklin Agent decides what to call, what to pay for, and when to stop. No subscriptions, no seats, no rate limits.
|
|
49
49
|
|
|
50
50
|
Funding it is your choice. Fund a **USDC wallet** and every paid action routes through the [x402](https://x402.org) micropayment protocol, settling on-chain against a wallet only you control — no signup, no account, the wallet is the identity. Or top up a **prepaid balance** at [user.blockrun.ai](https://user.blockrun.ai) and hand Franklin an API key. Same models, same tools, same agent. See [Two ways to pay](#two-ways-to-pay).
|
|
51
51
|
|
|
@@ -67,7 +67,7 @@ Built by the [BlockRun](https://blockrun.ai) team. Apache-2.0. TypeScript. Ships
|
|
|
67
67
|
# 1. Install
|
|
68
68
|
npm install -g @blockrun/franklin
|
|
69
69
|
|
|
70
|
-
# 2. Run (free — uses
|
|
70
|
+
# 2. Run (free — uses the free models out of the box)
|
|
71
71
|
franklin
|
|
72
72
|
|
|
73
73
|
# 3. (optional) Unlock Sonnet, Opus, GPT, Gemini, Grok + every paid API.
|
|
@@ -113,7 +113,7 @@ npm install -g @blockrun/franklin
|
|
|
113
113
|
|
|
114
114
|
[](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode)
|
|
115
115
|
|
|
116
|
-
The same agent ships as a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode) — chat panel, model picker, wallet balance, image / video generation
|
|
116
|
+
The same agent ships as a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=blockrun.franklin-vscode) — chat panel, model picker, wallet balance, image / video generation — all driven by the wallet you already funded for the CLI.
|
|
117
117
|
|
|
118
118
|
```
|
|
119
119
|
VS Code → Extensions (Cmd+Shift+X / Ctrl+Shift+X)
|
|
@@ -264,13 +264,11 @@ Three consequences fall out of this:
|
|
|
264
264
|
2. **No rate limits.** Subscriptions throttle you when you need AI most. YOPO has no artificial caps — if you have USDC, you have access.
|
|
265
265
|
3. **No overdraft.** The wallet balance IS the hard limit. When it's empty, Franklin stops. No surprise bills, no 3 a.m. rate-limit walls.
|
|
266
266
|
|
|
267
|
-
Concretely — $1 in USDC
|
|
268
|
-
- ~
|
|
269
|
-
- ~
|
|
270
|
-
- ~
|
|
271
|
-
-
|
|
272
|
-
- ~40 Exa neural web searches
|
|
273
|
-
- Unlimited agent-tested NVIDIA free tier (Qwen3 Coder + Llama 4 Maverick, no wallet needed)
|
|
267
|
+
Concretely — $1 in USDC buys roughly (input tokens at provider list price, before the $0.001 per-call fee):
|
|
268
|
+
- ~330K Claude Sonnet 4.6 tokens
|
|
269
|
+
- ~750K DeepSeek V4 Pro tokens
|
|
270
|
+
- ~3.3M Gemini 2.5 Flash tokens
|
|
271
|
+
- Unlimited use of the free tier — no wallet needed
|
|
274
272
|
|
|
275
273
|
---
|
|
276
274
|
|
|
@@ -282,7 +280,7 @@ Concretely — $1 in USDC gets you roughly:
|
|
|
282
280
|
|
|
283
281
|
Most AI products fit into one of three buckets: they answer questions, write code, or automate a fixed workflow. None of them can spend money.
|
|
284
282
|
|
|
285
|
-
Franklin can. It combines **purchasing power** (it pays for models, tools, and APIs), **budget awareness** (cost is part of the loop, not an afterthought), **cross-vertical execution** (
|
|
283
|
+
Franklin can. It combines **purchasing power** (it pays for models, tools, and APIs), **budget awareness** (cost is part of the loop, not an afterthought), **cross-vertical execution** (trading, research, content, operations), and **hard stopping conditions** (wallet balance is a real constraint, not a suggestion).
|
|
286
284
|
|
|
287
285
|
That is why Franklin is an economic agent, not just a task agent.
|
|
288
286
|
|
|
@@ -353,9 +351,9 @@ Generates images via DALL-E / GPT Image directly from the CLI. Paid from your se
|
|
|
353
351
|
|
|
354
352
|
### 📱 Remote control via Telegram
|
|
355
353
|
|
|
356
|
-
Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TELEGRAM_OWNER_ID`) and drive Franklin from your phone. Owner-locked, session-resumable across restarts, slash commands (`/new`, `/balance`, `/status`). Trading,
|
|
354
|
+
Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TELEGRAM_OWNER_ID`) and drive Franklin from your phone. Owner-locked, session-resumable across restarts, slash commands (`/new`, `/balance`, `/status`). Trading, research, content — all reachable from a Telegram chat.
|
|
357
355
|
|
|
358
|
-
### 🔎 Research,
|
|
356
|
+
### 🔎 Research, analysis, anything with a budget
|
|
359
357
|
|
|
360
358
|
```text
|
|
361
359
|
> compare the top 5 AI agent pricing models, summarize the patterns, and save a note for me
|
|
@@ -371,18 +369,17 @@ Run `franklin telegram` on an always-on machine (set `TELEGRAM_BOT_TOKEN` + `TEL
|
|
|
371
369
|
```
|
|
372
370
|
|
|
373
371
|
```text
|
|
374
|
-
>
|
|
372
|
+
> backtest strategies/sol_breakout.py on the last 90 days and tell me if it beats holding
|
|
375
373
|
|
|
376
|
-
✓
|
|
377
|
-
✓ Read
|
|
378
|
-
✓
|
|
379
|
-
✓
|
|
380
|
-
› 142 passing · 0 failing · 2.4s
|
|
374
|
+
✓ TradingMarket SOL · 90d daily candles
|
|
375
|
+
✓ Read strategies/sol_breakout.py
|
|
376
|
+
✓ Bash python strategies/sol_breakout.py --days 90
|
|
377
|
+
✓ Write notes/sol-breakout-90d.md
|
|
381
378
|
|
|
382
|
-
|
|
379
|
+
Strategy +11.4% vs. hold +6.2% · max drawdown −8.9% · 14 trades
|
|
383
380
|
```
|
|
384
381
|
|
|
385
|
-
|
|
382
|
+
Files and shell are there for the work around a strategy — scripts, data, reports. They are tools, not the category.
|
|
386
383
|
|
|
387
384
|
Every tool call is itemized. Every token is priced. When the wallet hits zero, Franklin stops. No overdraft, no surprise bill, no rate-limit wall at 3 a.m. — this is YOPO in practice.
|
|
388
385
|
|
|
@@ -390,24 +387,24 @@ Every tool call is itemized. Every token is priced. When the wallet hits zero, F
|
|
|
390
387
|
|
|
391
388
|
## Smart Router
|
|
392
389
|
|
|
393
|
-
**<!-- br:models.chatVisible -->
|
|
390
|
+
**<!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models. One decision. Zero guesswork.**
|
|
394
391
|
|
|
395
392
|
You don't pick models. Franklin picks for you.
|
|
396
393
|
|
|
397
|
-
The Smart Router classifies every request —
|
|
394
|
+
The Smart Router classifies every request — trading, research, reasoning, creative — and selects the model with the best quality-to-cost ratio. Trained on **2M+ real requests** from the BlockRun gateway, continuously updated.
|
|
398
395
|
|
|
399
396
|
```text
|
|
400
|
-
>
|
|
397
|
+
> summarize this week's stablecoin news in five bullets
|
|
401
398
|
|
|
402
|
-
|
|
399
|
+
RESEARCH deepseek-v4-pro · 9.6K in / 0.8K out
|
|
403
400
|
|
|
404
401
|
> what's the BTC outlook for the week?
|
|
405
402
|
|
|
406
|
-
TRADING
|
|
403
|
+
TRADING claude-opus-5 · 8.2K in / 1.8K out
|
|
407
404
|
|
|
408
|
-
>
|
|
405
|
+
> is this funding-rate arbitrage actually risk-free? walk through the cases
|
|
409
406
|
|
|
410
|
-
REASONING claude-
|
|
407
|
+
REASONING claude-opus-5 · 15.1K in / 3.4K out
|
|
411
408
|
```
|
|
412
409
|
|
|
413
410
|
Every response shows which model was chosen, why, and how much you saved vs. always using the most expensive option.
|
|
@@ -419,18 +416,18 @@ Every response shows which model was chosen, why, and how much you saved vs. alw
|
|
|
419
416
|
| `auto` | Best quality-to-cost ratio | Default — smart spend |
|
|
420
417
|
| `eco` | Cheapest model with decent quality | Budget-conscious |
|
|
421
418
|
| `premium` | Highest quality regardless of cost | Mission-critical |
|
|
422
|
-
| `free` | Free
|
|
419
|
+
| `free` | Free models only | Zero wallet balance |
|
|
423
420
|
|
|
424
421
|
**Per-session breakdown** — run `/cost` to see exactly where your USDC went:
|
|
425
422
|
|
|
426
423
|
```text
|
|
427
424
|
Session Cost: $0.0847 (23 requests)
|
|
428
|
-
gemini-2.5-flash $0.0012 14 req
|
|
429
|
-
|
|
430
|
-
claude-
|
|
425
|
+
gemini-2.5-flash $0.0012 14 req CHAT
|
|
426
|
+
deepseek-v4-pro $0.0201 6 req RESEARCH
|
|
427
|
+
claude-opus-5 $0.0634 3 req TRADING
|
|
431
428
|
```
|
|
432
429
|
|
|
433
|
-
The router also learns from **your** usage. If you keep retrying a model for
|
|
430
|
+
The router also learns from **your** usage. If you keep retrying a model for research tasks, Franklin adapts and picks a better one next time. Your router gets smarter the more you use it.
|
|
434
431
|
|
|
435
432
|
---
|
|
436
433
|
|
|
@@ -449,7 +446,7 @@ You don't subscribe to electricity, you pay for what you use. Franklin brings th
|
|
|
449
446
|
|
|
450
447
|
### 🧠 Multi-model is the future
|
|
451
448
|
|
|
452
|
-
No single model is best at everything.
|
|
449
|
+
No single model is best at everything. Opus reasons deeper, Gemini handles longer context, DeepSeek costs 20x less for simple tasks. The Smart Router routes every request to the optimal model in <1ms — <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% cheaper than pinning Claude Opus 5 for every request.
|
|
453
450
|
|
|
454
451
|
</td>
|
|
455
452
|
<td width="33%" valign="top">
|
|
@@ -466,19 +463,17 @@ No email. No phone. No KYC. Your Solana, Base or Arc address is your account —
|
|
|
466
463
|
|
|
467
464
|
## The comparison
|
|
468
465
|
|
|
469
|
-
| |
|
|
470
|
-
| -------------------------------------- | ---------------- |
|
|
471
|
-
|
|
|
472
|
-
| **
|
|
473
|
-
|
|
|
474
|
-
|
|
|
475
|
-
|
|
|
476
|
-
|
|
|
477
|
-
|
|
|
478
|
-
|
|
|
479
|
-
|
|
|
480
|
-
| Start free, no KYC | ❌ | ❌ | ❌ | ✅ |
|
|
481
|
-
| Source | Closed | Closed | Closed | **Apache 2.0, local-first** |
|
|
466
|
+
| | AI chat apps | Agent frameworks | Trading bots | **Franklin** |
|
|
467
|
+
| -------------------------------------- | ---------------- | ----------------------- | -------------------- | ------------------------------- |
|
|
468
|
+
| **Spends money for you** | ❌ | ⚠️ you wire payments | ⚠️ trades only | ✅ **USDC wallet or prepaid key** |
|
|
469
|
+
| **Buys data + APIs + images + search** | ❌ | ⚠️ one key per service | ❌ | ✅ **one wallet pays for all** |
|
|
470
|
+
| Picks best model per task | ❌ single-vendor | ⚠️ you pick | ❌ | ✅ **Smart Router, <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models** |
|
|
471
|
+
| **Money moves only on your approval** | — | ⚠️ build it yourself | ❌ runs on rules | ✅ **trade plan, every mode** |
|
|
472
|
+
| Spend guardrails | — | ⚠️ build it yourself | ⚠️ per-bot limits | ✅ **budget caps + hooks** |
|
|
473
|
+
| Works when a provider goes down | ❌ | ⚠️ if you code it | ❌ | ✅ **routes to another** |
|
|
474
|
+
| Pricing | Subscription | Your separate API bills | Subscription or fees | **YOPO** — per outcome |
|
|
475
|
+
| Identity | Vendor account | A key per vendor | Exchange account | ✅ **wallet, no signup** |
|
|
476
|
+
| Source | Closed | Mixed | Mostly closed | **Apache 2.0, local-first** |
|
|
482
477
|
|
|
483
478
|
**Franklin is the economic agent category in one sentence:** software with a wallet that can spend toward a result.
|
|
484
479
|
|
|
@@ -499,20 +494,20 @@ Ask "what's BTC looking like?" — Franklin fetches live price data, computes RS
|
|
|
499
494
|
**🎨 AI image generation**
|
|
500
495
|
Ask "generate a logo" — Franklin calls DALL-E / GPT Image, saves the result locally, paid from your wallet.
|
|
501
496
|
|
|
502
|
-
**🧠 <!-- br:models.chatVisible -->
|
|
503
|
-
Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax,
|
|
497
|
+
**🧠 <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> models via one wallet**
|
|
498
|
+
Anthropic, OpenAI, Google, xAI, DeepSeek, GLM, Kimi, Minimax, plus a free tier. One wallet, one interface, automatic fallback.
|
|
504
499
|
|
|
505
500
|
**💳 x402 micropayments (YOPO)**
|
|
506
501
|
HTTP 402 native. Every paid action is a signed USDC micropayment — an EIP-712 authorization on Base and Arc, a signed SPL transfer on Solana. Non-custodial: your keys never leave your machine. YOPO: you pay only for outcomes.
|
|
507
502
|
|
|
508
503
|
**🧠 Learned model router**
|
|
509
|
-
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->
|
|
504
|
+
Trained on 2M+ real requests. Classifies your task and picks the best model from <!-- br:models.chatVisible -->86<!-- /br:models.chatVisible --> LLMs. Four profiles (auto/eco/premium/free). Adapts to your usage over time.
|
|
510
505
|
|
|
511
506
|
</td>
|
|
512
507
|
<td width="50%" valign="top">
|
|
513
508
|
|
|
514
|
-
**🛠
|
|
515
|
-
|
|
509
|
+
**🛠 60+ built-in tools**
|
|
510
|
+
Trading and DeFi (signals, portfolio, trade plans, Jupiter and 0x swaps, Polymarket, DeFiLlama), research (Exa, web search and fetch, X search, on-chain and market data), media (image, video, music), autonomy (goals, scheduler, monitors, sub-agents, mixture of agents), phone and voice calls, cloud sandboxes, and general files and shell.
|
|
516
511
|
|
|
517
512
|
**💾 Persistent sessions**
|
|
518
513
|
Every turn is streamed to disk with metadata. Resume any session by ID. Survives crashes, reboots, and compaction.
|
|
@@ -526,6 +521,9 @@ Every turn is streamed to disk with metadata. Resume any session by ID. Survives
|
|
|
526
521
|
**⚡ Anthropic prompt caching**
|
|
527
522
|
Multi-turn Sonnet/Opus sessions use ephemeral cache breakpoints to reduce input spend on long conversations.
|
|
528
523
|
|
|
524
|
+
**🔒 Guarded by default**
|
|
525
|
+
Trades need your approved plan, the wallet key never reaches the model, and every network call the agent makes is checked. See [Safety and security](#safety-and-security).
|
|
526
|
+
|
|
529
527
|
**🔌 Plugin SDK + MCP**
|
|
530
528
|
Core is workflow-agnostic. Add new verticals without touching the loop. Discover external tools automatically through MCP.
|
|
531
529
|
|
|
@@ -540,14 +538,16 @@ Core is workflow-agnostic. Add new verticals without touching the loop. Discover
|
|
|
540
538
|
| Command | What it does |
|
|
541
539
|
| -------------------------------- | ---------------------------------------------------- |
|
|
542
540
|
| `/model [name]` | Interactive model picker, or switch directly |
|
|
541
|
+
| `/goal <objective>` | Work an objective across turns, verified at the end |
|
|
542
|
+
| `/loop <interval> <prompt>` | Run a prompt on a schedule (`/loop list`, `cancel`) |
|
|
543
|
+
| `/market` | Browse and hire paid skills from the marketplace |
|
|
544
|
+
| `/moa` | Ask several models the same question, compare |
|
|
543
545
|
| `/plan` / `/execute` | Read-only planning mode / execution mode |
|
|
544
546
|
| `/ultrathink <q>` | Deep reasoning mode for hard problems |
|
|
547
|
+
| `/remember` / `/flush` / `/dream`| Save a note / capture learnings / consolidate memory |
|
|
545
548
|
| `/compact` | Structured context compression |
|
|
546
|
-
| `/search <q>` | Search the codebase |
|
|
547
549
|
| `/session-search <q>` | Search past sessions |
|
|
548
550
|
| `/history` / `/resume [id]` | Inspect or restore conversation state |
|
|
549
|
-
| `/commit` / `/push` / `/pr` | Git workflow helpers |
|
|
550
|
-
| `/review` / `/fix` / `/test` | One-shot code review, bugfix, or test runs |
|
|
551
551
|
| `/cost` / `/wallet` | Session cost, wallet address, and balance |
|
|
552
552
|
| `/insights [--days N]` | Rich usage analytics |
|
|
553
553
|
| `/help` | Full command list |
|
|
@@ -560,6 +560,19 @@ like `opus`, `gpt` and `grok` keep their current targets.
|
|
|
560
560
|
|
|
561
561
|
---
|
|
562
562
|
|
|
563
|
+
## Safety and security
|
|
564
|
+
|
|
565
|
+
Franklin holds money, so the defaults assume a model can be steered by what it reads — a fetched page, a search result, an MCP response.
|
|
566
|
+
|
|
567
|
+
- **Money moves only on your approval.** Trades need a trade plan you approve, in every permission mode. `--max-spend` sets a spending ceiling, and [lifecycle hooks](docs/examples/hooks/) can veto any paid action before it runs.
|
|
568
|
+
- **The wallet key never reaches the model.** File, search and browser tools refuse the key store and the machine's own credential stores (`~/.ssh`, `~/.aws`, cloud and Solana CLI keys). The exact key values are also scrubbed from every tool result.
|
|
569
|
+
- **Network calls stay public.** Model-driven requests (web fetch, webhooks, the browser) refuse loopback, private and cloud-metadata addresses, and re-check every redirect.
|
|
570
|
+
- **The local panel answers only you.** It listens on loopback, checks the `Host` header, and its wallet and spend routes require a token that only the page it serves knows.
|
|
571
|
+
|
|
572
|
+
Found a vulnerability? Please report it privately — see [SECURITY.md](SECURITY.md).
|
|
573
|
+
|
|
574
|
+
---
|
|
575
|
+
|
|
563
576
|
## How it works
|
|
564
577
|
|
|
565
578
|
```text
|
|
@@ -568,13 +581,13 @@ like `opus`, `gpt` and `grok` keep their current targets.
|
|
|
568
581
|
│ Intent → Smart Router → Tool Use → Spend Control → Result │
|
|
569
582
|
├──────────────────────────────────────────────────────────────┤
|
|
570
583
|
│ Learned Router │
|
|
571
|
-
│ 2M+ requests · <!-- br:models.chatVisible@live -->
|
|
584
|
+
│ 2M+ requests · <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models · category detection · Elo scores │
|
|
572
585
|
├──────────────────────────────────────────────────────────────┤
|
|
573
586
|
│ Agent Loop │
|
|
574
|
-
│
|
|
587
|
+
│ 60+ tools · Sessions · Compaction · Pricing · Plugin SDK │
|
|
575
588
|
├──────────────────────────────────────────────────────────────┤
|
|
576
589
|
│ BlockRun Gateway │
|
|
577
|
-
│ <!-- br:models.chatVisible@live -->
|
|
590
|
+
│ <!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> LLMs · CoinGecko · Search · Image APIs · paid services │
|
|
578
591
|
├──────────────────────────────────────────────────────────────┤
|
|
579
592
|
│ x402 Micropayment Protocol │
|
|
580
593
|
│ HTTP 402 · USDC on Solana, Base & Arc · signed payloads │
|
|
@@ -604,10 +617,15 @@ src/
|
|
|
604
617
|
├── index.ts CLI entry (franklin)
|
|
605
618
|
├── banner.ts Ben Franklin portrait + FRANKLIN gradient text
|
|
606
619
|
├── agent/ Agent loop, LLM client, compaction, commands
|
|
607
|
-
├── tools/
|
|
608
|
-
│
|
|
609
|
-
│ MemoryRecall/AskUser/SubAgent/Trading*/Content*)
|
|
620
|
+
├── tools/ 60+ built-in tools (trading, DeFi, research, media,
|
|
621
|
+
│ phone, sandboxes, files and shell)
|
|
610
622
|
├── trading/ Market data (CoinGecko) + technical indicators
|
|
623
|
+
├── goal/ /goal objectives + adversarial verification
|
|
624
|
+
├── hooks/ Lifecycle hooks (PreSpend and friends)
|
|
625
|
+
├── scheduler/ Durable /loop scheduler
|
|
626
|
+
├── memory/ Wallet-keyed memory and trading journal
|
|
627
|
+
├── panel/ Local dashboard (franklin panel)
|
|
628
|
+
├── serve/ Agent host for the panel's Agents tab
|
|
611
629
|
├── content/ Content library with budget-bound media generation
|
|
612
630
|
├── brain/ Cross-session entity knowledge graph
|
|
613
631
|
├── channel/ Non-CLI ingress drivers (Telegram today)
|
|
@@ -618,7 +636,7 @@ src/
|
|
|
618
636
|
├── stats/ Usage tracking + insights engine
|
|
619
637
|
├── ui/ Ink-based terminal UI
|
|
620
638
|
├── proxy/ Payment proxy for external tools
|
|
621
|
-
├── router/ Learned model router (<!-- br:models.chatVisible@live -->
|
|
639
|
+
├── router/ Learned model router (<!-- br:models.chatVisible@live -->86<!-- /br:models.chatVisible@live --> models, Elo scoring)
|
|
622
640
|
├── wallet/ Wallet management (Base/Arc + Solana)
|
|
623
641
|
├── mcp/ MCP server auto-discovery
|
|
624
642
|
└── commands/ CLI subcommands
|
|
@@ -628,7 +646,7 @@ src/
|
|
|
628
646
|
|
|
629
647
|
## Free tier, for real
|
|
630
648
|
|
|
631
|
-
Start with **zero dollars**. Franklin defaults to free
|
|
649
|
+
Start with **zero dollars**. Franklin defaults to free models that need **no wallet and no API key** — nothing to fund, nothing to sign up for.
|
|
632
650
|
|
|
633
651
|
```bash
|
|
634
652
|
franklin --model free
|
|
@@ -698,7 +716,7 @@ npm install
|
|
|
698
716
|
npm run build
|
|
699
717
|
npm test # deterministic local tests — no API calls
|
|
700
718
|
npm run test:e2e # live e2e tests — free smoke works unfunded; paid tools need network + funded wallet
|
|
701
|
-
npm run test:free-models # live matrix across current free
|
|
719
|
+
npm run test:free-models # live matrix across the current free models
|
|
702
720
|
node dist/index.js --help
|
|
703
721
|
```
|
|
704
722
|
|
|
@@ -720,7 +738,7 @@ npm run desktop:package:win
|
|
|
720
738
|
Packaged builds create a private, per-launch credential for the local Franklin
|
|
721
739
|
service, keep cloud session sync off unless the user explicitly enables it, and
|
|
722
740
|
use `Documents/Franklin` as the default workspace. Files outside that workspace
|
|
723
|
-
remain available after an explicit approval
|
|
741
|
+
remain available after an explicit approval.
|
|
724
742
|
Team Mode is being developed separately and is not part of this stable integration.
|
|
725
743
|
|
|
726
744
|
For the recommended live validation order and failure triage, see [docs/live-e2e-checklist.md](docs/live-e2e-checklist.md).
|
|
@@ -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 };
|
package/dist/mcp/oauth.d.ts
CHANGED
|
@@ -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 {
|
|
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
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
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}`);
|
package/dist/panel/html.d.ts
CHANGED
package/dist/panel/html.js
CHANGED
|
@@ -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.
|
package/dist/panel/server.js
CHANGED
|
@@ -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';
|
|
@@ -83,8 +84,25 @@ function isLocalHostHeader(req) {
|
|
|
83
84
|
return false;
|
|
84
85
|
}
|
|
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
|
+
}
|
|
86
104
|
function isLocalPanelRequest(req) {
|
|
87
|
-
return isLoopback(req) && isTrustedPanelOrigin(req);
|
|
105
|
+
return isLoopback(req) && isTrustedPanelOrigin(req) && hasPanelToken(req);
|
|
88
106
|
}
|
|
89
107
|
async function readBody(req, maxBytes = 16 * 1024) {
|
|
90
108
|
return new Promise((resolve, reject) => {
|
|
@@ -134,7 +152,7 @@ async function currentWalletAddress() {
|
|
|
134
152
|
return client.getWalletAddress();
|
|
135
153
|
}
|
|
136
154
|
export function createPanelServer(port) {
|
|
137
|
-
const html = getHTML();
|
|
155
|
+
const html = getHTML(PANEL_TOKEN);
|
|
138
156
|
const server = http.createServer(async (req, res) => {
|
|
139
157
|
try {
|
|
140
158
|
const url = new URL(req.url || '/', `http://localhost:${port}`);
|
|
@@ -148,6 +166,12 @@ export function createPanelServer(port) {
|
|
|
148
166
|
res.end('Forbidden');
|
|
149
167
|
return;
|
|
150
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
|
+
}
|
|
151
175
|
// ─── HTML ──
|
|
152
176
|
if (p === '/') {
|
|
153
177
|
res.writeHead(200, {
|
|
@@ -376,7 +400,9 @@ export function createPanelServer(port) {
|
|
|
376
400
|
// ─── Wallet secret (loopback only) ──────────────────────────────────
|
|
377
401
|
// Returns the private key so the user can back it up / move it.
|
|
378
402
|
// Hardened: loopback-only (belt-and-suspenders on the 127.0.0.1 bind),
|
|
379
|
-
// same-origin for browser requests,
|
|
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.
|
|
380
406
|
if (p === '/api/wallet/secret') {
|
|
381
407
|
if (!isLocalPanelRequest(req)) {
|
|
382
408
|
json(res, { error: 'forbidden' }, 403);
|
package/dist/tools/browsex.d.ts
CHANGED
|
@@ -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;
|
package/dist/tools/browsex.js
CHANGED
|
@@ -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);
|
package/dist/tools/edit.js
CHANGED
|
@@ -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) {
|
package/dist/tools/glob.js
CHANGED
|
@@ -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
|
}
|
package/dist/tools/grep.js
CHANGED
|
@@ -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(':');
|
package/dist/tools/read.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import {
|
|
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
|
|
62
|
-
|
|
63
|
-
|
|
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
|
+
}
|
package/dist/tools/ssrf.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
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
|
|
8
|
-
*
|
|
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.
|
package/dist/tools/webhook.d.ts
CHANGED
|
@@ -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.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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;
|
package/dist/tools/webhook.js
CHANGED
|
@@ -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.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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 (
|
|
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
|
|
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
|
-
|
|
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);
|
package/dist/tools/write.js
CHANGED
|
@@ -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
|
-
|
|
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