@chatpanel/bridge 0.10.9 → 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 +1 -1
- package/src/engines/claude.js +12 -1
- package/src/env.js +160 -23
- package/src/server.js +137 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.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": [
|
package/src/engines/claude.js
CHANGED
|
@@ -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)
|
|
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/env.js
CHANGED
|
@@ -14,11 +14,11 @@ let enriched = false;
|
|
|
14
14
|
|
|
15
15
|
// The agent CLIs the bridge shells out to. Claude has its own richer resolution
|
|
16
16
|
// (resolveClaude: native / cli.js / WSL / SDK) below.
|
|
17
|
-
const AGENT_CLIS = ['codex', 'claude', 'agy', 'pi', 'opencode', 'kiro-cli'];
|
|
17
|
+
export const AGENT_CLIS = ['codex', 'claude', 'agy', 'pi', 'opencode', 'kiro-cli'];
|
|
18
18
|
|
|
19
19
|
// Is `name` executable somewhere on the current PATH?
|
|
20
20
|
function onPath(name) {
|
|
21
|
-
const dirs = (process.env.PATH || ''
|
|
21
|
+
const dirs = splitPathList(process.env.PATH || '', process.platform);
|
|
22
22
|
return dirs.some((d) => d && (existsSync(path.join(d, name)) || existsSync(path.join(d, name + '.exe'))));
|
|
23
23
|
}
|
|
24
24
|
|
|
@@ -27,14 +27,9 @@ function onPath(name) {
|
|
|
27
27
|
// "is it installed/findable", NOT "does `--version` exit 0" (which can fail for
|
|
28
28
|
// reasons unrelated to installation, e.g. the CLI needs login).
|
|
29
29
|
export function findAgentBin(name) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
for (const d of dirs) {
|
|
34
|
-
if (!d) continue;
|
|
35
|
-
for (const ext of exts) {
|
|
36
|
-
const p = path.join(d, name + ext);
|
|
37
|
-
if (existsSync(p)) return p;
|
|
30
|
+
for (const p of commandCandidateFiles(name)) {
|
|
31
|
+
if (existsSync(p)) {
|
|
32
|
+
return p;
|
|
38
33
|
}
|
|
39
34
|
}
|
|
40
35
|
return shellWhich(name) || null;
|
|
@@ -152,20 +147,20 @@ export function resolveCommand(command) {
|
|
|
152
147
|
// own Node/Bun — clean arg passing, no cmd.exe quoting), then a real .exe, then a
|
|
153
148
|
// .cmd/.bat shim launched safely via cmd.exe.
|
|
154
149
|
function findCommandWindows(name) {
|
|
155
|
-
const
|
|
156
|
-
for (const
|
|
157
|
-
if (!
|
|
158
|
-
const
|
|
159
|
-
|
|
150
|
+
const p = pathFor('win32');
|
|
151
|
+
for (const candidate of commandCandidateFiles(name, os.homedir(), 'win32', process.env)) {
|
|
152
|
+
if (!existsSync(candidate)) continue;
|
|
153
|
+
const d = p.dirname(candidate);
|
|
154
|
+
const ext = p.extname(candidate).toLowerCase();
|
|
160
155
|
// Running cli.js with our own interpreter only works under a real Node/Bun,
|
|
161
156
|
// not inside a compiled single-file binary (which is not a JS interpreter).
|
|
162
157
|
if (!isCompiledBinary()) {
|
|
163
158
|
const js = (name === 'claude' && claudeCliJs(d)) || shimTarget(d, name);
|
|
164
159
|
if (js) return { kind: 'script', script: js };
|
|
160
|
+
if (/^\.(c?js|mjs)$/.test(ext)) return { kind: 'script', script: candidate };
|
|
165
161
|
}
|
|
166
|
-
if (
|
|
167
|
-
if (
|
|
168
|
-
if (existsSync(path.join(d, name + '.bat'))) return { kind: 'cmd', bin: path.join(d, name + '.bat') };
|
|
162
|
+
if (ext === '.exe' || ext === '') return { kind: 'native', bin: candidate };
|
|
163
|
+
if (ext === '.cmd' || ext === '.bat') return { kind: 'cmd', bin: candidate };
|
|
169
164
|
}
|
|
170
165
|
return null;
|
|
171
166
|
}
|
|
@@ -290,14 +285,156 @@ function versionManagerBins(home) {
|
|
|
290
285
|
return bins;
|
|
291
286
|
}
|
|
292
287
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
288
|
+
function pathFor(platform) {
|
|
289
|
+
return platform === 'win32' ? path.win32 : path;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function pathDelimiterFor(platform) {
|
|
293
|
+
return platform === 'win32' ? ';' : path.delimiter;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function splitPathList(value, platform) {
|
|
297
|
+
return (value || '').split(pathDelimiterFor(platform)).filter(Boolean);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function unique(items) {
|
|
301
|
+
return [...new Set(items.filter(Boolean))];
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function agentInstallDirs(home, platform = process.platform, env = process.env) {
|
|
305
|
+
const p = pathFor(platform);
|
|
306
|
+
if (platform === 'win32') {
|
|
307
|
+
const appData = env.APPDATA || p.join(home, 'AppData', 'Roaming');
|
|
308
|
+
const localAppData = env.LOCALAPPDATA || p.join(home, 'AppData', 'Local');
|
|
309
|
+
const programFiles = env.ProgramFiles || 'C:\\Program Files';
|
|
310
|
+
const programFilesX86 = env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
|
|
311
|
+
const programData = env.ProgramData || 'C:\\ProgramData';
|
|
312
|
+
return [
|
|
313
|
+
p.join(home, '.local', 'bin'),
|
|
314
|
+
p.join(home, '.codex', 'bin'),
|
|
315
|
+
p.join(home, '.claude', 'bin'),
|
|
316
|
+
p.join(home, '.claude', 'local'),
|
|
317
|
+
p.join(home, '.claude', 'local', 'bin'),
|
|
318
|
+
p.join(appData, 'npm'),
|
|
319
|
+
p.join(localAppData, 'pnpm'),
|
|
320
|
+
p.join(localAppData, 'Yarn', 'bin'),
|
|
321
|
+
p.join(localAppData, 'Volta', 'bin'),
|
|
322
|
+
p.join(home, '.yarn', 'bin'),
|
|
323
|
+
p.join(home, '.bun', 'bin'),
|
|
324
|
+
p.join(home, '.deno', 'bin'),
|
|
325
|
+
p.join(home, 'scoop', 'shims'),
|
|
326
|
+
p.join(programData, 'chocolatey', 'bin'),
|
|
327
|
+
p.join(localAppData, 'Microsoft', 'WindowsApps'),
|
|
328
|
+
p.join(localAppData, 'Programs', 'Claude Code'),
|
|
329
|
+
p.join(localAppData, 'Anthropic', 'Claude Code'),
|
|
330
|
+
p.join(programFiles, 'Claude Code'),
|
|
331
|
+
p.join(programFiles, 'Anthropic', 'Claude Code'),
|
|
332
|
+
p.join(programFilesX86, 'Claude Code'),
|
|
333
|
+
p.join(programFilesX86, 'Anthropic', 'Claude Code'),
|
|
334
|
+
];
|
|
297
335
|
}
|
|
336
|
+
return [
|
|
337
|
+
path.join(home, '.local', 'bin'),
|
|
338
|
+
path.join(home, '.opencode', 'bin'),
|
|
339
|
+
path.join(home, '.codex', 'bin'),
|
|
340
|
+
path.join(home, '.claude', 'bin'),
|
|
341
|
+
path.join(home, '.claude', 'local'),
|
|
342
|
+
path.join(home, '.claude', 'local', 'bin'),
|
|
343
|
+
];
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function claudeNativeBins(home, platform = process.platform) {
|
|
347
|
+
const p = pathFor(platform);
|
|
348
|
+
const versionsDir = p.join(home, '.local', 'share', 'claude', 'versions');
|
|
349
|
+
let versions = [];
|
|
350
|
+
try {
|
|
351
|
+
versions = readdirSync(versionsDir)
|
|
352
|
+
.filter((v) => /^\d+\.\d+\.\d+/.test(v))
|
|
353
|
+
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
|
|
354
|
+
} catch {
|
|
355
|
+
/* native installer may not be present */
|
|
356
|
+
}
|
|
357
|
+
return versions.map((v) => p.join(versionsDir, v));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function withWindowsExts(file, platform) {
|
|
361
|
+
if (platform !== 'win32') return [file];
|
|
362
|
+
if (/\.(cmd|exe|bat|ps1)$/i.test(file)) return [file];
|
|
363
|
+
return [file, `${file}.cmd`, `${file}.exe`, `${file}.bat`, `${file}.ps1`];
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function agentCandidateBins(name, home = os.homedir(), platform = process.platform, env = process.env) {
|
|
367
|
+
const p = pathFor(platform);
|
|
368
|
+
const local = p.join(home, '.local', 'bin', name);
|
|
369
|
+
const localAppData = platform === 'win32' ? env.LOCALAPPDATA || p.join(home, 'AppData', 'Local') : null;
|
|
370
|
+
const programFiles = platform === 'win32' ? env.ProgramFiles || 'C:\\Program Files' : null;
|
|
371
|
+
const programFilesX86 = platform === 'win32' ? env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)' : null;
|
|
372
|
+
const map = {
|
|
373
|
+
claude: [
|
|
374
|
+
local,
|
|
375
|
+
p.join(home, '.claude', 'bin', 'claude'),
|
|
376
|
+
p.join(home, '.claude', 'local', 'claude'),
|
|
377
|
+
p.join(home, '.claude', 'local', 'bin', 'claude'),
|
|
378
|
+
...(platform === 'win32'
|
|
379
|
+
? [
|
|
380
|
+
p.join(localAppData, 'Microsoft', 'WindowsApps', 'claude.exe'),
|
|
381
|
+
p.join(localAppData, 'Programs', 'Claude Code', 'claude.exe'),
|
|
382
|
+
p.join(localAppData, 'Anthropic', 'Claude Code', 'claude.exe'),
|
|
383
|
+
p.join(programFiles, 'Claude Code', 'claude.exe'),
|
|
384
|
+
p.join(programFiles, 'Anthropic', 'Claude Code', 'claude.exe'),
|
|
385
|
+
p.join(programFilesX86, 'Claude Code', 'claude.exe'),
|
|
386
|
+
p.join(programFilesX86, 'Anthropic', 'Claude Code', 'claude.exe'),
|
|
387
|
+
...claudeNativeBins(home, platform),
|
|
388
|
+
]
|
|
389
|
+
: claudeNativeBins(home, platform)),
|
|
390
|
+
],
|
|
391
|
+
codex: [
|
|
392
|
+
local,
|
|
393
|
+
p.join(home, '.codex', 'bin', 'codex'),
|
|
394
|
+
],
|
|
395
|
+
agy: [
|
|
396
|
+
local,
|
|
397
|
+
'/Applications/Antigravity.app/Contents/MacOS/agy',
|
|
398
|
+
'/Applications/Antigravity IDE.app/Contents/MacOS/agy',
|
|
399
|
+
],
|
|
400
|
+
pi: [
|
|
401
|
+
local,
|
|
402
|
+
],
|
|
403
|
+
opencode: [
|
|
404
|
+
p.join(home, '.opencode', 'bin', 'opencode'),
|
|
405
|
+
local,
|
|
406
|
+
],
|
|
407
|
+
'kiro-cli': [
|
|
408
|
+
local,
|
|
409
|
+
'/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli',
|
|
410
|
+
],
|
|
411
|
+
};
|
|
412
|
+
return unique((map[name] || [local]).flatMap((file) => withWindowsExts(file, platform)));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function commandCandidateFiles(name, home = os.homedir(), platform = process.platform, env = process.env) {
|
|
416
|
+
const p = pathFor(platform);
|
|
417
|
+
const fromDirs = unique([
|
|
418
|
+
...splitPathList(env.PATH || '', platform),
|
|
419
|
+
...agentInstallDirs(home, platform, env),
|
|
420
|
+
]).flatMap((dir) => withWindowsExts(p.join(dir, name), platform));
|
|
421
|
+
return unique([...fromDirs, ...agentCandidateBins(name, home, platform, env)]);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export function enrichPath() {
|
|
425
|
+
if (enriched) return;
|
|
298
426
|
enriched = true;
|
|
299
427
|
|
|
300
428
|
const home = os.homedir();
|
|
429
|
+
if (process.platform === 'win32') {
|
|
430
|
+
const merged = unique([
|
|
431
|
+
...splitPathList(process.env.PATH || '', 'win32'),
|
|
432
|
+
...agentInstallDirs(home, 'win32', process.env),
|
|
433
|
+
]);
|
|
434
|
+
process.env.PATH = merged.join(pathDelimiterFor('win32'));
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
|
|
301
438
|
const common = [
|
|
302
439
|
'/opt/homebrew/bin',
|
|
303
440
|
'/opt/homebrew/sbin',
|
|
@@ -312,7 +449,7 @@ export function enrichPath() {
|
|
|
312
449
|
path.join(home, '.cargo', 'bin'),
|
|
313
450
|
path.join(home, '.deno', 'bin'),
|
|
314
451
|
path.join(home, '.bun', 'bin'),
|
|
315
|
-
|
|
452
|
+
...agentInstallDirs(home),
|
|
316
453
|
...versionManagerBins(home),
|
|
317
454
|
];
|
|
318
455
|
|
package/src/server.js
CHANGED
|
@@ -12,25 +12,31 @@
|
|
|
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
|
|
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';
|
|
23
29
|
import { pi, opencode, kiro } from './engines/cli-agents.js';
|
|
24
30
|
import * as custom from './engines/custom.js';
|
|
25
31
|
import { installService, uninstallService, serviceStatus, restartService } from './service.js';
|
|
26
|
-
import { enrichPath, findAgentBin, resolveCommand } from './env.js';
|
|
32
|
+
import { AGENT_CLIS, enrichPath, findAgentBin, resolveCommand } from './env.js';
|
|
27
33
|
import { checkForUpdate, selfUpdate } from './update.js';
|
|
28
34
|
import { callLocalMcp } from './mcp-local.js';
|
|
29
35
|
|
|
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.
|
|
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
|
|
120
|
-
|
|
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,15 +548,22 @@ const server = createServer(async (req, res) => {
|
|
|
431
548
|
res.writeHead(204);
|
|
432
549
|
return res.end();
|
|
433
550
|
}
|
|
434
|
-
|
|
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') {
|
|
438
563
|
return json(res, 200, {
|
|
439
564
|
version: VERSION,
|
|
440
565
|
home: os.homedir(),
|
|
441
|
-
|
|
442
|
-
agy: findAgentBin('agy') || null,
|
|
566
|
+
agents: Object.fromEntries(AGENT_CLIS.map((name) => [name, findAgentBin(name) || null])),
|
|
443
567
|
path: process.env.PATH,
|
|
444
568
|
});
|
|
445
569
|
}
|
|
@@ -528,6 +652,7 @@ function runMcpStdioProxy(url) {
|
|
|
528
652
|
|
|
529
653
|
function startServer() {
|
|
530
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)
|
|
531
656
|
server.listen(PORT, HOST, async () => {
|
|
532
657
|
log('info', `listening on http://${HOST}:${PORT}`);
|
|
533
658
|
for (const [, { engine, label, hidden }] of Object.entries(ENGINES)) {
|