@chatpanel/bridge 0.10.10 → 0.10.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,13 +1,102 @@
1
- MIT License
1
+ # Functional Source License, Version 1.1, MIT Future License
2
2
 
3
- Copyright (c) 2026 ChatPanel
3
+ ## Abbreviation
4
4
 
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 ChatPanel
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
11
100
 
12
101
  The above copyright notice and this permission notice shall be included in all
13
102
  copies or substantial portions of the Software.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.10.10",
3
+ "version": "0.10.12",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Gemini CLI — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -17,7 +17,7 @@
17
17
  "type": "git",
18
18
  "url": "git+https://github.com/chatpanel/chatpanel-bridge.git"
19
19
  },
20
- "license": "MIT",
20
+ "license": "SEE LICENSE IN LICENSE",
21
21
  "bin": {
22
22
  "chatpanel-bridge": "src/server.js"
23
23
  },
@@ -244,7 +244,18 @@ export async function chat({ messages, system, options, images }, emit) {
244
244
  }: ${imageFiles.join(', ')}`;
245
245
  }
246
246
 
247
- if (options.extraArgs) args.push(...String(options.extraArgs).split(/\s+/).filter(Boolean));
247
+ if (options.extraArgs) {
248
+ const extra = String(options.extraArgs).split(/\s+/).filter(Boolean);
249
+ // Never let caller-supplied extras re-open the read-only boundary the mode
250
+ // flags above establish. If ANY security-sensitive flag is present, drop the
251
+ // whole extraArgs (these tokens take values, so partial filtering is unsafe).
252
+ const FORBIDDEN = /^--?(permission-mode|allowed-?tools|disallowed-?tools|dangerously|add-dir|mcp-config|setting-sources|permission-prompt-tool)/i;
253
+ if (extra.some((t) => FORBIDDEN.test(t))) {
254
+ emit({ type: 'status', text: '(ignored unsafe extraArgs)' });
255
+ } else {
256
+ args.push(...extra);
257
+ }
258
+ }
248
259
  const run = runClaude({ prompt, args, cwd, emit });
249
260
  if (run === null) {
250
261
  cleanup(); // SDK fallback doesn't take images yet
package/src/server.js CHANGED
@@ -12,11 +12,17 @@
12
12
  // {type:'done', text?} (text only if not streamed)
13
13
  // {type:'error', error}
14
14
  //
15
- // Binds to 127.0.0.1 only and accepts requests from the extension origin.
15
+ // Binds to 127.0.0.1 only. A request guard (see `guard()`) enforces a loopback
16
+ // Host (anti DNS-rebinding) and an allowlisted Origin; the command-spawning
17
+ // endpoints (/chat, /mcp-local, /update, …) additionally require the extension
18
+ // origin or the per-install bridge token, so a malicious web page can't drive
19
+ // local execution. The CLI-facing /mcp endpoints stay open to no-Origin clients.
16
20
 
17
21
  import { createServer } from 'node:http';
18
22
  import os from 'node:os';
19
- import { randomUUID } from 'node:crypto';
23
+ import { randomUUID, randomBytes, timingSafeEqual } from 'node:crypto';
24
+ import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
25
+ import { join } from 'node:path';
20
26
  import * as claude from './engines/claude.js';
21
27
  import * as codex from './engines/codex.js';
22
28
  import * as antigravity from './engines/antigravity.js';
@@ -30,7 +36,7 @@ import { callLocalMcp } from './mcp-local.js';
30
36
  // Hardcoded (not read from package.json) so it survives Bun's single-file
31
37
  // --compile, where package.json isn't on a readable FS. CI fails the publish if
32
38
  // this drifts from package.json, so the two can't silently diverge.
33
- const VERSION = '0.10.10';
39
+ const VERSION = '0.10.12';
34
40
  const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
35
41
  const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
36
42
 
@@ -115,18 +121,156 @@ function toMcpContent(result) {
115
121
 
116
122
  // --------------------------------------------------------------------------
117
123
  // CORS — allow the extension (chrome-extension://…) and localhost dev origins.
124
+ // NOTE: CORS only controls whether a *page* may READ the response; it does NOT
125
+ // stop a cross-origin request from running. The hard allow/deny gating that
126
+ // actually protects the command-spawning endpoints lives in `guard()` below.
118
127
  // --------------------------------------------------------------------------
119
- function cors(req, res) {
120
- const origin = req.headers.origin || '';
121
- const allow =
128
+ function originAllowed(origin) {
129
+ return (
122
130
  !origin ||
123
131
  origin.startsWith('chrome-extension://') ||
124
132
  origin.startsWith('moz-extension://') ||
125
133
  origin.startsWith('http://localhost') ||
126
- origin.startsWith('http://127.0.0.1');
134
+ origin.startsWith('http://127.0.0.1') ||
135
+ origin.startsWith('http://[::1]')
136
+ );
137
+ }
138
+
139
+ // An origin that identifies the ChatPanel extension (or a local dev build).
140
+ // Distinct from originAllowed(): this REQUIRES the header to be present, so a
141
+ // no-Origin local process cannot pose as the extension on privileged routes.
142
+ function isExtensionOrigin(origin) {
143
+ return (
144
+ origin.startsWith('chrome-extension://') ||
145
+ origin.startsWith('moz-extension://') ||
146
+ origin.startsWith('http://localhost') ||
147
+ origin.startsWith('http://127.0.0.1') ||
148
+ origin.startsWith('http://[::1]')
149
+ );
150
+ }
151
+
152
+ function cors(req, res) {
153
+ const origin = req.headers.origin || '';
154
+ const allow = originAllowed(origin);
127
155
  res.setHeader('Access-Control-Allow-Origin', allow ? origin || '*' : 'null');
128
156
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
129
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
157
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-ChatPanel-Token');
158
+ res.setHeader('Vary', 'Origin');
159
+ }
160
+
161
+ // --------------------------------------------------------------------------
162
+ // Security gates — defend the localhost server against a malicious web page.
163
+ //
164
+ // Two browser attack classes are in scope even though we bind to 127.0.0.1:
165
+ // 1. DNS rebinding — a page on http://evil.example rebinds that name to
166
+ // 127.0.0.1 and fetches http://evil.example:PORT/…; the request arrives
167
+ // with Host: evil.example, which a naïve server happily serves.
168
+ // 2. Cross-origin CSRF — a page POSTs a CORS "simple" request (text/plain)
169
+ // to http://127.0.0.1:PORT/…; no preflight fires and the side effect runs.
170
+ //
171
+ // hostAllowed() closes (1) by rejecting any non-loopback Host. The Origin
172
+ // checks close (2). Privileged endpoints additionally require the extension
173
+ // origin or the per-install token, so a no-Origin local process can't drive
174
+ // command execution either.
175
+ // --------------------------------------------------------------------------
176
+ const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '::1']);
177
+
178
+ function hostAllowed(req) {
179
+ // If the operator deliberately bound to a non-loopback/all interface
180
+ // (CHATPANEL_BRIDGE_HOST=0.0.0.0 / a LAN IP), don't second-guess their Host.
181
+ if (!LOOPBACK_HOSTNAMES.has(HOST)) return true;
182
+ const raw = String(req.headers.host || '');
183
+ if (!raw) return false; // HTTP/1.1 requires Host; absent → reject
184
+ const hostname = raw
185
+ .replace(/:\d+$/, '') // strip :port
186
+ .replace(/^\[|\]$/g, '') // strip IPv6 brackets
187
+ .toLowerCase();
188
+ return LOOPBACK_HOSTNAMES.has(hostname);
189
+ }
190
+
191
+ // Per-install bearer token — defense-in-depth so a non-browser local client can
192
+ // authenticate to privileged routes without relying on an Origin header. Written
193
+ // 0600 to ~/.chatpanel/bridge-token; the extension is allowed by origin and need
194
+ // not send it, so adding this never breaks the existing wire contract.
195
+ const TOKEN_PATH = join(os.homedir(), '.chatpanel', 'bridge-token');
196
+ let AUTH_TOKEN = '';
197
+ function ensureToken() {
198
+ try {
199
+ if (existsSync(TOKEN_PATH)) AUTH_TOKEN = readFileSync(TOKEN_PATH, 'utf8').trim();
200
+ if (!AUTH_TOKEN) {
201
+ AUTH_TOKEN = randomBytes(32).toString('hex');
202
+ mkdirSync(join(os.homedir(), '.chatpanel'), { recursive: true });
203
+ writeFileSync(TOKEN_PATH, AUTH_TOKEN, { mode: 0o600 });
204
+ }
205
+ } catch (e) {
206
+ // Token is optional hardening — never fail startup over it.
207
+ log('error', `could not initialise bridge token: ${e?.message || e}`);
208
+ }
209
+ }
210
+ function tokenOk(req) {
211
+ if (!AUTH_TOKEN) return false;
212
+ const h = String(req.headers['authorization'] || '');
213
+ const provided = (h.startsWith('Bearer ') ? h.slice(7) : String(req.headers['x-chatpanel-token'] || '')).trim();
214
+ if (!provided) return false;
215
+ const a = Buffer.from(provided);
216
+ const b = Buffer.from(AUTH_TOKEN);
217
+ return a.length === b.length && timingSafeEqual(a, b);
218
+ }
219
+
220
+ // POST sinks that spawn local agents/commands or self-update, plus GET /debug
221
+ // (leaks PATH/home). Only the extension (allowlisted origin) or a token-bearing
222
+ // client may reach these. The CLI-facing /mcp and /mcp/<id> routes are NOT here:
223
+ // local coding-agent CLIs connect to them with no Origin header by design.
224
+ const PRIVILEGED_POST = new Set([
225
+ '/chat',
226
+ '/mcp-local',
227
+ '/mcp-remote',
228
+ '/complete',
229
+ '/list-models',
230
+ '/agent-check',
231
+ '/update',
232
+ '/tool-result',
233
+ ]);
234
+ const PRIVILEGED_GET = new Set(['/debug']);
235
+
236
+ // SSRF guard for /mcp-remote: the bridge must not become an open relay into the
237
+ // local network. Block non-http(s) schemes and private/loopback/link-local/
238
+ // metadata hosts — on the initial URL AND after any redirect.
239
+ function isBlockedHttpHost(hostname) {
240
+ const h = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
241
+ if (!h || h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local')) return true;
242
+ if (h === '::1' || h === '::' || h.startsWith('fc') || h.startsWith('fd') || h.startsWith('fe8') || h.startsWith('fe9') || h.startsWith('fea') || h.startsWith('feb')) return true;
243
+ const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
244
+ if (m) {
245
+ const a = Number(m[1]), b = Number(m[2]);
246
+ if (a === 0 || a === 127 || a === 10) return true; // this-host / loopback / RFC1918
247
+ if (a === 169 && b === 254) return true; // link-local + cloud metadata
248
+ if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918
249
+ if (a === 192 && b === 168) return true; // RFC1918
250
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
251
+ }
252
+ return false;
253
+ }
254
+ function assertPublicHttpUrl(u) {
255
+ let parsed;
256
+ try { parsed = new URL(u); } catch { throw new Error(`invalid URL: ${u}`); }
257
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error(`only http(s) URLs allowed (got "${parsed.protocol}")`);
258
+ if (isBlockedHttpHost(parsed.hostname)) throw new Error(`refusing to proxy a private/loopback/metadata address (${parsed.hostname})`);
259
+ return parsed;
260
+ }
261
+
262
+ // Returns an error code if the request must be blocked, else null.
263
+ function guard(req, pathname) {
264
+ if (!hostAllowed(req)) return 'forbidden host';
265
+ const origin = req.headers.origin || '';
266
+ if (origin && !originAllowed(origin)) return 'forbidden origin';
267
+ const privileged =
268
+ (req.method === 'POST' && PRIVILEGED_POST.has(pathname)) ||
269
+ (req.method === 'GET' && PRIVILEGED_GET.has(pathname));
270
+ if (privileged && !(isExtensionOrigin(origin) || tokenOk(req))) {
271
+ return 'forbidden: this endpoint requires the ChatPanel extension or a valid bridge token';
272
+ }
273
+ return null;
130
274
  }
131
275
 
132
276
  function json(res, code, obj) {
@@ -324,6 +468,59 @@ async function handleMcpLocal(req, res) {
324
468
  }
325
469
  }
326
470
 
471
+ // POST /mcp-remote — proxy ONE JSON-RPC message to a remote Streamable-HTTP MCP
472
+ // server FROM the bridge (server-side, no browser Origin header), so the extension
473
+ // can reach servers that reject browser origins (their own DNS-rebinding/CORS
474
+ // protection). Body: { url, headers?, message }. Returns the upstream
475
+ // { status, sessionId, contentType, body } for the extension to parse. Privileged
476
+ // route + SSRF guard, so it can't be driven by a page or relay into the LAN.
477
+ async function handleMcpRemote(req, res) {
478
+ let body;
479
+ try {
480
+ body = await readBody(req);
481
+ } catch (e) {
482
+ return json(res, 400, { error: 'Bad JSON: ' + e.message });
483
+ }
484
+ const { url, headers: hdrs, message } = body || {};
485
+ if (!url || !message) return json(res, 400, { error: 'need url and message' });
486
+ let target;
487
+ try {
488
+ target = assertPublicHttpUrl(url);
489
+ } catch (e) {
490
+ return json(res, 400, { error: String(e?.message || e) });
491
+ }
492
+ // Forward only safe, MCP-relevant client headers (auth, session, protocol, x-*);
493
+ // never the Host/hop-by-hop headers. Content-Type/Accept are set by us.
494
+ const fwd = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
495
+ if (hdrs && typeof hdrs === 'object') {
496
+ for (const [k, v] of Object.entries(hdrs)) {
497
+ const lk = k.toLowerCase();
498
+ if (['authorization', 'mcp-session-id', 'mcp-protocol-version', 'x-api-key'].includes(lk) || lk.startsWith('x-')) {
499
+ fwd[k] = String(v);
500
+ }
501
+ }
502
+ }
503
+ const ac = new AbortController();
504
+ const t = setTimeout(() => ac.abort(), 30_000);
505
+ try {
506
+ const up = await fetch(target.href, { method: 'POST', headers: fwd, body: JSON.stringify(message), redirect: 'follow', signal: ac.signal });
507
+ // A redirect may have landed on an internal host — re-check the final URL.
508
+ try { if (up.url) assertPublicHttpUrl(up.url); } catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
509
+ const text = await up.text().catch(() => '');
510
+ return json(res, 200, {
511
+ status: up.status,
512
+ sessionId: up.headers.get('Mcp-Session-Id') || null,
513
+ contentType: up.headers.get('Content-Type') || '',
514
+ body: text,
515
+ });
516
+ } catch (e) {
517
+ const why = e?.name === 'AbortError' ? 'timed out' : String(e?.message || e);
518
+ return json(res, 502, { error: `couldn't reach MCP server ${target.host}: ${why}` });
519
+ } finally {
520
+ clearTimeout(t);
521
+ }
522
+ }
523
+
327
524
  // POST /tool-result — the extension returns a relayed tool's result.
328
525
  async function handleToolResult(req, res) {
329
526
  let body;
@@ -431,7 +628,15 @@ const server = createServer(async (req, res) => {
431
628
  res.writeHead(204);
432
629
  return res.end();
433
630
  }
434
- const url = new URL(req.url, `http://${req.headers.host}`);
631
+ let url;
632
+ try {
633
+ url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
634
+ } catch {
635
+ return json(res, 400, { error: 'bad request' });
636
+ }
637
+ // Block DNS-rebinding / cross-origin CSRF before any route runs.
638
+ const blocked = guard(req, url.pathname);
639
+ if (blocked) return json(res, 403, { error: blocked });
435
640
  try {
436
641
  if (req.method === 'GET' && url.pathname === '/health') return handleHealth(res);
437
642
  if (req.method === 'GET' && url.pathname === '/debug') {
@@ -457,6 +662,7 @@ const server = createServer(async (req, res) => {
457
662
  }
458
663
  if (req.method === 'POST' && url.pathname === '/tool-result') return handleToolResult(req, res);
459
664
  if (req.method === 'POST' && url.pathname === '/mcp-local') return handleMcpLocal(req, res);
665
+ if (req.method === 'POST' && url.pathname === '/mcp-remote') return handleMcpRemote(req, res);
460
666
  if (req.method === 'POST' && url.pathname === '/complete') return handleComplete(req, res);
461
667
  if (req.method === 'POST' && url.pathname === '/list-models') return handleListModels(req, res);
462
668
  if (req.method === 'POST' && url.pathname === '/agent-check') return handleAgentCheck(req, res);
@@ -527,6 +733,7 @@ function runMcpStdioProxy(url) {
527
733
 
528
734
  function startServer() {
529
735
  enrichPath(); // so codex/gemini are found even under a minimal service PATH
736
+ ensureToken(); // per-install bearer token for privileged routes (defense-in-depth)
530
737
  server.listen(PORT, HOST, async () => {
531
738
  log('info', `listening on http://${HOST}:${PORT}`);
532
739
  for (const [, { engine, label, hidden }] of Object.entries(ENGINES)) {