@chatpanel/bridge 0.10.10 → 0.10.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.10.10",
3
+ "version": "0.10.11",
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": [
@@ -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.11';
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,129 @@ 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
+ '/complete',
228
+ '/list-models',
229
+ '/agent-check',
230
+ '/update',
231
+ '/tool-result',
232
+ ]);
233
+ const PRIVILEGED_GET = new Set(['/debug']);
234
+
235
+ // Returns an error code if the request must be blocked, else null.
236
+ function guard(req, pathname) {
237
+ if (!hostAllowed(req)) return 'forbidden host';
238
+ const origin = req.headers.origin || '';
239
+ if (origin && !originAllowed(origin)) return 'forbidden origin';
240
+ const privileged =
241
+ (req.method === 'POST' && PRIVILEGED_POST.has(pathname)) ||
242
+ (req.method === 'GET' && PRIVILEGED_GET.has(pathname));
243
+ if (privileged && !(isExtensionOrigin(origin) || tokenOk(req))) {
244
+ return 'forbidden: this endpoint requires the ChatPanel extension or a valid bridge token';
245
+ }
246
+ return null;
130
247
  }
131
248
 
132
249
  function json(res, code, obj) {
@@ -431,7 +548,15 @@ const server = createServer(async (req, res) => {
431
548
  res.writeHead(204);
432
549
  return res.end();
433
550
  }
434
- const url = new URL(req.url, `http://${req.headers.host}`);
551
+ let url;
552
+ try {
553
+ url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
554
+ } catch {
555
+ return json(res, 400, { error: 'bad request' });
556
+ }
557
+ // Block DNS-rebinding / cross-origin CSRF before any route runs.
558
+ const blocked = guard(req, url.pathname);
559
+ if (blocked) return json(res, 403, { error: blocked });
435
560
  try {
436
561
  if (req.method === 'GET' && url.pathname === '/health') return handleHealth(res);
437
562
  if (req.method === 'GET' && url.pathname === '/debug') {
@@ -527,6 +652,7 @@ function runMcpStdioProxy(url) {
527
652
 
528
653
  function startServer() {
529
654
  enrichPath(); // so codex/gemini are found even under a minimal service PATH
655
+ ensureToken(); // per-install bearer token for privileged routes (defense-in-depth)
530
656
  server.listen(PORT, HOST, async () => {
531
657
  log('info', `listening on http://${HOST}:${PORT}`);
532
658
  for (const [, { engine, label, hidden }] of Object.entries(ENGINES)) {