@chatpanel/bridge 0.11.23 → 0.11.25

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.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -463
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
package/src/skills.js CHANGED
@@ -1,399 +1 @@
1
- // skills.js — the skill package store.
2
- //
3
- // A ChatPanel skill has been a prompt in the extension's settings, which is fine until a
4
- // skill wants to carry the things the agentskills.io format carries: reference documents
5
- // loaded only when needed, templates, and scripts. None of those can live in a browser
6
- // extension — it has no filesystem, and running someone else's script inside it is on the
7
- // Never list. They live here.
8
- //
9
- // So the bridge becomes a skill HOST, not a skill consumer. It scans directories, parses
10
- // each SKILL.md into the shared record, and serves three levels on demand — the
11
- // progressive-disclosure ladder the format is built around:
12
- //
13
- // list() name + description + what files exist (cheap, every turn)
14
- // read(name) the full SKILL.md body (when it is chosen)
15
- // readFile(name, p) one reference/asset (when it is needed)
16
- //
17
- // It also scans ~/.agents/skills — the cross-tool convention several agent CLIs already
18
- // use — so a skill written in another tool appears here with no export step. That is the
19
- // point of putting the store in the bridge rather than in one client.
20
- //
21
- // ── SECURITY ──────────────────────────────────────────────────────────────────────────
22
- // This module turns HTTP request strings into filesystem reads, which makes it the most
23
- // dangerous file in the repo. Three rules, none of them optional:
24
- //
25
- // 1. A REQUESTED NAME IS NEVER A PATH. `read('../../.ssh/id_rsa')` resolves the name
26
- // against the scanned INDEX; a name that is not in the index does not exist. There
27
- // is no code path from a URL segment to a path join.
28
- // 2. A REQUESTED FILE PATH IS CHECKED TWICE — lexically (the shared `isSafeSkillPath`,
29
- // which refuses traversal, absolute paths, drive letters, backslashes and control
30
- // characters) and then again after resolution, because a SYMLINK inside a skill
31
- // directory passes every lexical check and still points at ~/.ssh.
32
- // 3. EVERY READ IS CAPPED. A skill directory is not necessarily authored by the person
33
- // running it, and an unbounded read of a file someone else chose is a denial of
34
- // service against the process the browser depends on.
35
-
36
- import { readFile as fsReadFile, readdir, stat, realpath } from 'node:fs/promises';
37
- import { createHash } from 'node:crypto';
38
- import os from 'node:os';
39
- import { delimiter, isAbsolute, join, resolve, sep } from 'node:path';
40
- import { isSafeSkillPath, normalizeSkill, SKILL_FILE_KINDS } from './events/skill-manifest.js';
41
- import { scanSkill, admits } from './events/skill-scan.js';
42
-
43
- const MAX_SKILL_MD = 512 * 1024; // a procedure document, not a corpus
44
- const MAX_ASSET = 4 * 1024 * 1024; // a reference doc or a template; images live elsewhere
45
- const MAX_SKILLS = 500; // a scan is bounded work, not "whatever is on disk"
46
- const MAX_DEPTH = 3; // <root>/<name>/, <root>/<category>/<name>/, and one
47
- // namespace above that (Codex: .system/<name>/)
48
-
49
- // Never a skill and never worth walking: version control and package metadata. Everything
50
- // else hidden IS walked — see the namespace note in scanSkills.
51
- const SKIP_DIRS = new Set(['.git', '.svn', '.hg', '.cache', '.DS_Store', 'node_modules']);
52
-
53
- /**
54
- * The agent CLIs that keep skills in a well-known directory, and what to call each one.
55
- *
56
- * Every one of these stores the SAME agentskills.io layout — `<name>/SKILL.md` plus
57
- * optional `references/`. In practice a machine ends up with the same skill copied into
58
- * several of them, which is the duplication the shared `~/.agents/skills` convention
59
- * exists to end and has not yet. Reading all of them is what lets ChatPanel show the
60
- * user's actual skills rather than the subset that happens to live in one folder.
61
- *
62
- * Ordered: ChatPanel's own directory, then the cross-tool convention, then each agent.
63
- * The order IS the precedence — see skillRoots.
64
- */
65
- export const AGENT_SKILL_DIRS = Object.freeze([
66
- { source: 'local', label: 'ChatPanel', segments: ['.chatpanel', 'skills'], writable: true },
67
- { source: 'agents-dir', label: 'Shared (~/.agents)', segments: ['.agents', 'skills'] },
68
- { source: 'claude', label: 'Claude Code', segments: ['.claude', 'skills'] },
69
- { source: 'codex', label: 'Codex', segments: ['.codex', 'skills'] },
70
- { source: 'copilot', label: 'GitHub Copilot', segments: ['.copilot', 'skills'] },
71
- { source: 'gemini', label: 'Antigravity / Gemini', segments: ['.gemini', 'skills'] },
72
- { source: 'opencode', label: 'OpenCode', segments: ['.opencode', 'skills'] },
73
- { source: 'kiro', label: 'Kiro', segments: ['.kiro', 'skills'] },
74
- { source: 'pi', label: 'Pi', segments: ['.pi', 'skills'] },
75
- { source: 'hermes', label: 'Hermes', segments: ['.hermes', 'skills'] },
76
- ]);
77
-
78
- /**
79
- * Where skills are scanned from, in precedence order — first hit wins on a name clash.
80
- *
81
- * ChatPanel's own directory is authoritative, then the shared cross-tool one, then each
82
- * agent's. That order matters because the same skill genuinely does exist in several of
83
- * these at once: whichever root answers first is the copy that gets shown, and a stable
84
- * order means the answer does not change between scans.
85
- *
86
- * Only the first is written. The rest belong to whatever else the user runs, and a tool
87
- * that edits another tool's configuration directory is a tool people uninstall.
88
- */
89
- // User-configured folders come from two places: CHATPANEL_SKILL_DIRS (env, for an operator)
90
- // and the extension's own setting, passed per request as `extraDirs`. Both are the user's
91
- // OWN paths on their OWN machine reached over an authed loopback call — so they are allowed,
92
- // but only if they are ABSOLUTE. A relative or empty entry is dropped rather than resolved
93
- // against the bridge's cwd, which would scan somewhere the user never named.
94
- function cleanDirs(list) {
95
- return (Array.isArray(list) ? list : [])
96
- .map((d) => String(d || '').trim())
97
- .filter(Boolean)
98
- .filter((d) => isAbsolute(d))
99
- .slice(0, 16); // a bound, not a limit anyone will hit
100
- }
101
-
102
- export function skillRoots(env = process.env, home = os.homedir(), extraDirs = []) {
103
- // Split on the PLATFORM's list separator, not a fixed set. Splitting on ':' everywhere
104
- // cut "C:\\Users\\me\\skills" into "C" and "\\Users\\me\\skills" on Windows, which is the
105
- // one platform where a drive letter makes that character part of an ordinary path.
106
- const fromEnv = String(env.CHATPANEL_SKILL_DIRS || '')
107
- .split(/\r?\n/)
108
- .flatMap((line) => line.split(delimiter))
109
- .map((s) => s.trim())
110
- .filter(Boolean);
111
- const extra = [...new Set([...fromEnv, ...cleanDirs(extraDirs)])];
112
- return [
113
- ...AGENT_SKILL_DIRS.map((d) => ({
114
- dir: join(home, ...d.segments),
115
- source: d.source,
116
- label: d.label,
117
- writable: !!d.writable,
118
- })),
119
- ...extra.map((dir) => ({ dir: resolve(dir), source: 'external', label: 'Custom folder', writable: false })),
120
- ];
121
- }
122
-
123
- /**
124
- * The YAML subset a SKILL.md frontmatter block actually uses: scalars, inline `[a, b]`
125
- * lists, and one level of nesting. Deliberately NOT a YAML parser — a real one is a
126
- * dependency the bridge does not take, and a full parser is a larger attack surface than
127
- * the five fields we read. Anything it does not understand is ignored, never guessed at.
128
- */
129
- export function parseFrontmatter(text) {
130
- const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(String(text || ''));
131
- if (!m) return { meta: {}, body: String(text || '') };
132
- const out = {};
133
- const stack = [{ indent: -1, obj: out }];
134
- for (const raw of m[1].split(/\r?\n/)) {
135
- if (!raw.trim() || raw.trim().startsWith('#')) continue;
136
- const indent = raw.length - raw.trimStart().length;
137
- const line = raw.trim();
138
- const kv = /^([A-Za-z_][\w.-]*)\s*:\s*(.*)$/.exec(line);
139
- if (!kv) continue;
140
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) stack.pop();
141
- const parent = stack[stack.length - 1].obj;
142
- const [, key, rest] = kv;
143
- if (rest === '') {
144
- const child = {};
145
- parent[key] = child;
146
- stack.push({ indent, obj: child });
147
- continue;
148
- }
149
- parent[key] = scalar(rest);
150
- }
151
- return { meta: out, body: String(text).slice(m[0].length) };
152
- }
153
-
154
- function scalar(v) {
155
- const s = v.trim().replace(/\s+#.*$/, '').trim();
156
- if (/^\[.*\]$/.test(s)) {
157
- return s.slice(1, -1).split(',').map((x) => unquote(x.trim())).filter(Boolean);
158
- }
159
- if (s === 'true') return true;
160
- if (s === 'false') return false;
161
- return unquote(s);
162
- }
163
-
164
- const unquote = (s) => (/^(['"]).*\1$/.test(s) ? s.slice(1, -1) : s);
165
-
166
- /** A directory name usable as a skill id when the frontmatter has no `name`. */
167
- const ID = /^[a-z0-9][a-z0-9_-]*$/;
168
-
169
- /**
170
- * Turn a parsed SKILL.md plus its directory listing into the shared record.
171
- *
172
- * Local skills carry an ORIGIN, and therefore read as `community` rather than `user`.
173
- * That is deliberate and it is the conservative answer: we cannot tell a skill the user
174
- * wrote from one that arrived in a synced or checked-out directory, and treating the
175
- * second as trusted is exactly the mistake. Only skills authored in ChatPanel itself are
176
- * the user's own.
177
- */
178
- export function skillRecord({ meta, body, dirName, relPath, source, files, hash }) {
179
- const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : dirName;
180
- const id = ID.test(String(name)) ? String(name) : dirName;
181
- const grouped = {};
182
- for (const kind of SKILL_FILE_KINDS) {
183
- const list = files.filter((f) => f.startsWith(`${kind}/`)).map((f) => f.slice(kind.length + 1));
184
- if (list.length) grouped[kind] = list;
185
- }
186
- return normalizeSkill({
187
- id,
188
- name: String(name),
189
- command: ID.test(id) ? id : '',
190
- description: typeof meta.description === 'string' ? meta.description : '',
191
- prompt: body.trim(),
192
- ...(typeof meta.version === 'string' ? { version: meta.version } : {}),
193
- ...(Array.isArray(meta.platforms) ? { platforms: meta.platforms } : {}),
194
- ...(Object.keys(grouped).length ? { files: grouped } : {}),
195
- origin: { source, id: relPath, hash },
196
- });
197
- }
198
-
199
- /** Does this skill run on the machine we are on? */
200
- export function platformOk(skill, platform = process.platform) {
201
- const want = skill?.platforms;
202
- if (!Array.isArray(want) || !want.length) return true;
203
- const here = platform === 'darwin' ? 'macos' : platform === 'win32' ? 'windows' : 'linux';
204
- return want.includes(here);
205
- }
206
-
207
- async function listDir(dir) {
208
- try {
209
- return await readdir(dir, { withFileTypes: true });
210
- } catch {
211
- return []; // a root that does not exist is not an error — most machines have neither
212
- }
213
- }
214
-
215
- /** Files a package carries, relative to its directory, capped and traversal-checked. */
216
- async function packageFiles(dir) {
217
- const out = [];
218
- for (const kind of SKILL_FILE_KINDS) {
219
- for (const entry of await listDir(join(dir, kind))) {
220
- if (!entry.isFile()) continue; // no recursion, and never a symlink or a device
221
- const rel = `${kind}/${entry.name}`;
222
- if (isSafeSkillPath(rel)) out.push(rel);
223
- if (out.length >= 200) return out;
224
- }
225
- }
226
- return out;
227
- }
228
-
229
- async function loadSkill(dir, relPath, source) {
230
- let text;
231
- try {
232
- const st = await stat(join(dir, 'SKILL.md'));
233
- if (!st.isFile() || st.size > MAX_SKILL_MD) return null;
234
- text = await fsReadFile(join(dir, 'SKILL.md'), 'utf8');
235
- } catch {
236
- return null;
237
- }
238
- const { meta, body } = parseFrontmatter(text);
239
- const hash = `sha256-${createHash('sha256').update(text).digest('hex').slice(0, 32)}`;
240
- // relPath is an IDENTITY, not a filesystem path: it is built with '/' on every platform
241
- // so a skill's origin.id is the same string on Windows and macOS. Do not "fix" this to
242
- // path.sep — that would make the same skill look like two different ones per platform.
243
- const dirName = relPath.split('/').pop();
244
- const files = await packageFiles(dir);
245
- const skill = skillRecord({ meta, body, dirName, relPath, source, files, hash });
246
- // Scanned before it can enter the index — even a local skill, because a folder synced
247
- // from elsewhere or pulled by another tool is not something the user wrote. The verdict
248
- // rides on the origin so a client can show it; the caller quarantines a dangerous one.
249
- const scan = scanSkill({ name: skill.name, prompt: skill.prompt, files: files || [] });
250
- skill.origin = { ...skill.origin, scanned: { verdict: scan.verdict, scanner: scan.scanner, findings: scan.findings.length } };
251
- return { skill, dir, scan };
252
- }
253
-
254
- /**
255
- * Scan every root. Returns an INDEX keyed by id — and that index is the only thing a
256
- * later read may resolve a requested name against.
257
- */
258
- export async function scanSkills({ roots, extraDirs = [], platform = process.platform } = {}) {
259
- roots = roots || skillRoots(process.env, os.homedir(), extraDirs);
260
- const index = new Map();
261
- const problems = [];
262
- const quarantined = [];
263
- for (const { dir: root, source } of roots) {
264
- const walk = async (dir, rel, depth) => {
265
- if (index.size >= MAX_SKILLS || depth > MAX_DEPTH) return;
266
- for (const entry of await listDir(dir)) {
267
- if (index.size >= MAX_SKILLS) return;
268
- if (!entry.isDirectory() || SKIP_DIRS.has(entry.name)) continue;
269
- const childRel = rel ? `${rel}/${entry.name}` : entry.name;
270
- const child = join(dir, entry.name);
271
- // A hidden directory is a NAMESPACE, not a skill. Codex ships its built-ins under
272
- // `~/.codex/skills/.system/<name>/SKILL.md`, so skipping every dot-directory —
273
- // which was aimed at `.git` — hid six real skills. Walk through it, but never let
274
- // it become a skill id of its own.
275
- const loaded = entry.name.startsWith('.')
276
- ? null
277
- : await loadSkill(child, childRel, source).catch((e) => {
278
- problems.push({ path: childRel, reason: String(e?.message || e) });
279
- return null;
280
- });
281
- if (loaded) {
282
- // A dangerous skill is kept on disk (the user may want to inspect or remove it)
283
- // but never enters the index — so it cannot be listed, read, offered as a slash
284
- // command, or handed to a model. Recorded so a client can say WHY it is missing.
285
- if (!admits(loaded.scan?.verdict)) {
286
- quarantined.push({ id: loaded.skill.id, path: childRel, verdict: loaded.scan.verdict, findings: loaded.scan.findings });
287
- } else if (!index.has(loaded.skill.id) && platformOk(loaded.skill, platform)) {
288
- // First root wins: ChatPanel's own directory is authoritative over a shared one.
289
- index.set(loaded.skill.id, { ...loaded, root, source });
290
- }
291
- } else {
292
- await walk(child, childRel, depth + 1);
293
- }
294
- }
295
- };
296
- await walk(root, '', 1);
297
- }
298
- return { index, problems, quarantined };
299
- }
300
-
301
- /** Level 0 — what exists, cheaply. No bodies. */
302
- export function listRecords(index) {
303
- return [...index.values()].map(({ skill }) => {
304
- const { prompt, ...rest } = skill;
305
- return { ...rest, promptChars: (prompt || '').length };
306
- });
307
- }
308
-
309
- /** Level 1 — one skill, body included. `name` is resolved against the index, never joined. */
310
- export function readRecord(index, name) {
311
- const hit = index.get(String(name || ''));
312
- return hit ? hit.skill : null;
313
- }
314
-
315
- /**
316
- * Level 2 — one file inside a package.
317
- *
318
- * The lexical check happens first and the resolved-path containment check happens after,
319
- * because they catch different things: the first stops `../`, the second stops a symlink
320
- * that points outside the package while looking perfectly ordinary.
321
- */
322
- export async function readPackageFile(index, name, relPath) {
323
- const hit = index.get(String(name || ''));
324
- if (!hit) return { error: 'unknown skill' };
325
- if (!isSafeSkillPath(relPath)) return { error: 'unsafe path' };
326
- // A skill's docs live wherever its author put them — a flat references/ for simple ones,
327
- // a deep tree (foundry-agent/deploy/deploy.md, rbac/, quota/…) for rich ones. The SKILL.md
328
- // IS the map, so the readable set is "any file inside this skill's own folder", enforced
329
- // below by realpath containment — not a fixed list of top-level directory names, which
330
- // silently refused every nested reference the skill's own instructions pointed at.
331
- //
332
- // The one exception is scripts/: tier-3 executable code is run behind a confirmation, never
333
- // handed to a model as text. '/' by wire contract — isSafeSkillPath already refuses
334
- // backslashes, so a Windows separator never reaches here.
335
- if (String(relPath).split('/')[0] === 'scripts') return { error: 'scripts are not readable as text' };
336
-
337
- const target = resolve(hit.dir, relPath);
338
- let real;
339
- try {
340
- real = await realpath(target);
341
- } catch {
342
- return { error: 'not found' };
343
- }
344
- // A symlink passes every string check ever written. Compare what the filesystem
345
- // actually resolved to against the package root, with a separator so `/skills-evil`
346
- // cannot pass as a child of `/skills`.
347
- const rootReal = await realpath(hit.dir).catch(() => hit.dir);
348
- if (real !== rootReal && !real.startsWith(rootReal + sep)) return { error: 'outside package' };
349
-
350
- const st = await stat(real).catch(() => null);
351
- if (!st?.isFile()) return { error: 'not found' };
352
- if (st.size > MAX_ASSET) return { error: 'file too large' };
353
- return { path: relPath, text: await fsReadFile(real, 'utf8') };
354
- }
355
-
356
- /**
357
- * A cached view, because /health and every turn ask "what skills exist" far more often
358
- * than the directories change. Short TTL rather than a watcher: a watcher on directories
359
- * that may not exist, across three roots, is more moving parts than a 5-second staleness
360
- * window is worth.
361
- */
362
- const CACHE_MS = 5000;
363
- let cached = null;
364
-
365
- export async function skillIndex({ force = false, now = Date.now, extraDirs = [] } = {}) {
366
- const t = now();
367
- // The cache key includes the custom folders — a scan with extra dirs must not serve, or be
368
- // served by, one without them.
369
- const key = cleanDirs(extraDirs).map((d) => resolve(d)).sort().join('|');
370
- if (!force && cached && cached.key === key && t - cached.at < CACHE_MS) return cached.value;
371
- const value = await scanSkills({ extraDirs });
372
- cached = { at: t, key, value };
373
- return value;
374
- }
375
-
376
- export function clearSkillCache() { cached = null; }
377
-
378
- /** The `/health` summary — counts and roots, never contents. */
379
- export async function skillsHealth(extraDirs = []) {
380
- const { index, problems, quarantined } = await skillIndex({ extraDirs });
381
- const used = new Set([...index.values()].map((v) => v.root));
382
- return {
383
- count: index.size,
384
- // Only roots that actually contributed. A list of every path we looked in would be
385
- // mostly absent directories, and would say nothing about what the user has.
386
- roots: skillRoots(process.env, os.homedir(), extraDirs).filter((r) => used.has(r.dir)).map((r) => r.dir),
387
- sources: [...new Set([...index.values()].map((v) => v.source))].sort(),
388
- ...(problems.length ? { problems: problems.length } : {}),
389
- // A count, not the contents. That there is a blocked skill is worth surfacing; the
390
- // findings are read on demand, not broadcast on every health poll.
391
- ...(quarantined?.length ? { quarantined: quarantined.length } : {}),
392
- };
393
- }
394
-
395
- /** The blocked skills, with their findings — for a client that wants to show them. */
396
- export async function quarantinedSkills(extraDirs = []) {
397
- const { quarantined } = await skillIndex({ extraDirs });
398
- return quarantined || [];
399
- }
1
+ import{readFile as b,readdir as K,stat as x,realpath as v}from"node:fs/promises";import{createHash as R}from"node:crypto";import S from"node:os";import{delimiter as M,isAbsolute as j,join as g,resolve as k,sep as E}from"node:path";import{isSafeSkillPath as A,normalizeSkill as H,SKILL_FILE_KINDS as _}from"./events/skill-manifest.js";import{scanSkill as q,admits as T}from"./events/skill-scan.js";const O=512*1024,W=4*1024*1024,L=500,X=3,B=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),G=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function I(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>j(e)).slice(0,16)}function C(t=process.env,e=S.homedir(),s=[]){const n=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(r=>r.split(M)).map(r=>r.trim()).filter(Boolean),i=[...new Set([...n,...I(s)])];return[...G.map(r=>({dir:g(e,...r.segments),source:r.source,label:r.label,writable:!!r.writable})),...i.map(r=>({dir:k(r),source:"external",label:"Custom folder",writable:!1}))]}function N(t){const e=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(String(t||""));if(!e)return{meta:{},body:String(t||"")};const s={},n=[{indent:-1,obj:s}];for(const i of e[1].split(/\r?\n/)){if(!i.trim()||i.trim().startsWith("#"))continue;const r=i.length-i.trimStart().length,c=i.trim(),a=/^([A-Za-z_][\w.-]*)\s*:\s*(.*)$/.exec(c);if(!a)continue;for(;n.length>1&&r<=n[n.length-1].indent;)n.pop();const u=n[n.length-1].obj,[,o,l]=a;if(l===""){const p={};u[o]=p,n.push({indent:r,obj:p});continue}u[o]=P(l)}return{meta:s,body:String(t).slice(e[0].length)}}function P(t){const e=t.trim().replace(/\s+#.*$/,"").trim();return/^\[.*\]$/.test(e)?e.slice(1,-1).split(",").map(s=>$(s.trim())).filter(Boolean):e==="true"?!0:e==="false"?!1:$(e)}const $=t=>/^(['"]).*\1$/.test(t)?t.slice(1,-1):t,z=/^[a-z0-9][a-z0-9_-]*$/;function Z({meta:t,body:e,dirName:s,relPath:n,source:i,files:r,hash:c}){const a=typeof t.name=="string"&&t.name.trim()?t.name.trim():s,u=z.test(String(a))?String(a):s,o={};for(const l of _){const p=r.filter(f=>f.startsWith(`${l}/`)).map(f=>f.slice(l.length+1));p.length&&(o[l]=p)}return H({id:u,name:String(a),command:z.test(u)?u:"",description:typeof t.description=="string"?t.description:"",prompt:e.trim(),...typeof t.version=="string"?{version:t.version}:{},...Array.isArray(t.platforms)?{platforms:t.platforms}:{},...Object.keys(o).length?{files:o}:{},origin:{source:i,id:n,hash:c}})}function J(t,e=process.platform){const s=t?.platforms;if(!Array.isArray(s)||!s.length)return!0;const n=e==="darwin"?"macos":e==="win32"?"windows":"linux";return s.includes(n)}async function D(t){try{return await K(t,{withFileTypes:!0})}catch{return[]}}async function Q(t){const e=[];for(const s of _)for(const n of await D(g(t,s))){if(!n.isFile())continue;const i=`${s}/${n.name}`;if(A(i)&&e.push(i),e.length>=200)return e}return e}async function U(t,e,s){let n;try{const p=await x(g(t,"SKILL.md"));if(!p.isFile()||p.size>O)return null;n=await b(g(t,"SKILL.md"),"utf8")}catch{return null}const{meta:i,body:r}=N(n),c=`sha256-${R("sha256").update(n).digest("hex").slice(0,32)}`,a=e.split("/").pop(),u=await Q(t),o=Z({meta:i,body:r,dirName:a,relPath:e,source:s,files:u,hash:c}),l=q({name:o.name,prompt:o.prompt,files:u||[]});return o.origin={...o.origin,scanned:{verdict:l.verdict,scanner:l.scanner,findings:l.findings.length}},{skill:o,dir:t,scan:l}}async function V({roots:t,extraDirs:e=[],platform:s=process.platform}={}){t=t||C(process.env,S.homedir(),e);const n=new Map,i=[],r=[];for(const{dir:c,source:a}of t){const u=async(o,l,p)=>{if(!(n.size>=L||p>X))for(const f of await D(o)){if(n.size>=L)return;if(!f.isDirectory()||B.has(f.name))continue;const h=l?`${l}/${f.name}`:f.name,w=g(o,f.name),m=f.name.startsWith(".")?null:await U(w,h,a).catch(y=>(i.push({path:h,reason:String(y?.message||y)}),null));m?T(m.scan?.verdict)?!n.has(m.skill.id)&&J(m.skill,s)&&n.set(m.skill.id,{...m,root:c,source:a}):r.push({id:m.skill.id,path:h,verdict:m.scan.verdict,findings:m.scan.findings}):await u(w,h,p+1)}};await u(c,"",1)}return{index:n,problems:i,quarantined:r}}function ot(t){return[...t.values()].map(({skill:e})=>{const{prompt:s,...n}=e;return{...n,promptChars:(s||"").length}})}function at(t,e){const s=t.get(String(e||""));return s?s.skill:null}async function lt(t,e,s){const n=t.get(String(e||""));if(!n)return{error:"unknown skill"};if(!A(s))return{error:"unsafe path"};if(String(s).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const i=k(n.dir,s);let r;try{r=await v(i)}catch{return{error:"not found"}}const c=await v(n.dir).catch(()=>n.dir);if(r!==c&&!r.startsWith(c+E))return{error:"outside package"};const a=await x(r).catch(()=>null);return a?.isFile()?a.size>W?{error:"file too large"}:{path:s,text:await b(r,"utf8")}:{error:"not found"}}const Y=5e3;let d=null;async function F({force:t=!1,now:e=Date.now,extraDirs:s=[]}={}){const n=e(),i=I(s).map(c=>k(c)).sort().join("|");if(!t&&d&&d.key===i&&n-d.at<Y)return d.value;const r=await V({extraDirs:s});return d={at:n,key:i,value:r},r}function ct(){d=null}async function ut(t=[]){const{index:e,problems:s,quarantined:n}=await F({extraDirs:t}),i=new Set([...e.values()].map(r=>r.root));return{count:e.size,roots:C(process.env,S.homedir(),t).filter(r=>i.has(r.dir)).map(r=>r.dir),sources:[...new Set([...e.values()].map(r=>r.source))].sort(),...s.length?{problems:s.length}:{},...n?.length?{quarantined:n.length}:{}}}async function pt(t=[]){const{quarantined:e}=await F({extraDirs:t});return e||[]}export{G as AGENT_SKILL_DIRS,ct as clearSkillCache,ot as listRecords,N as parseFrontmatter,J as platformOk,pt as quarantinedSkills,lt as readPackageFile,at as readRecord,V as scanSkills,F as skillIndex,Z as skillRecord,C as skillRoots,ut as skillsHealth};
package/src/ssrf.js CHANGED
@@ -1,70 +1 @@
1
- // SSRF guard for the bridge's outbound proxies (/mcp-remote, /fetch-title).
2
- //
3
- // The host CLASSIFICATION (what is loopback / cloud-metadata / RFC1918 / CGNAT /
4
- // ULA / link-local / .local) now lives in ONE shared place — src/net.js, a vendored
5
- // copy of @chatpanel/pii/net.js, the same classifier the gateway and extension use.
6
- // This file keeps only the bridge's two POLICIES + their exact error messages, so a
7
- // security guard can't drift between the direct client path and the proxied path.
8
- // See docs/secure-data-plane.md.
9
- //
10
- // Two policies:
11
- // • /mcp-remote (assertPublicHttpUrl): loopback ALLOWED (the user's own MCP
12
- // servers — the whole point of "via bridge"), cloud metadata ALWAYS blocked,
13
- // every other private/LAN range blocked UNLESS the operator opts in with
14
- // CHATPANEL_BRIDGE_ALLOW_PRIVATE_HOSTS=1 (reaching an MCP server on a trusted LAN).
15
- // • /fetch-title (assertPublicWebUrl): STRICTER — a page fetch has no business
16
- // touching loopback OR any private host, so loopback + metadata + every private
17
- // range are blocked unconditionally (the opt-in is deliberately NOT honored).
18
- //
19
- // Non-http(s) schemes are blocked in both. Run the assert on the initial URL AND
20
- // after every redirect hop.
21
-
22
- import { isLoopbackHost, isBlockedHost } from './net.js';
23
-
24
- export { isLoopbackHost };
25
-
26
- const ALLOW_PRIVATE_HOSTS = /^(1|true|yes|on)$/i.test(
27
- process.env.CHATPANEL_BRIDGE_ALLOW_PRIVATE_HOSTS || '',
28
- );
29
-
30
- // MCP-proxy policy: loopback ok, metadata never, other private only when opted in.
31
- export function isBlockedHttpHost(hostname) {
32
- return isBlockedHost(hostname, { allowLoopback: true, allowPrivate: ALLOW_PRIVATE_HOSTS });
33
- }
34
-
35
- export function assertPublicHttpUrl(u) {
36
- let parsed;
37
- try {
38
- parsed = new URL(u);
39
- } catch {
40
- throw new Error(`invalid URL: ${u}`);
41
- }
42
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
43
- throw new Error(`only http(s) URLs allowed (got "${parsed.protocol}")`);
44
- }
45
- if (isBlockedHttpHost(parsed.hostname)) {
46
- throw new Error(`refusing to proxy a private/metadata address (${parsed.hostname})`);
47
- }
48
- return parsed;
49
- }
50
-
51
- // Web-fetch policy (stricter): block loopback + metadata + all private, always.
52
- export function isDisallowedWebHost(hostname) {
53
- return isBlockedHost(hostname, { allowLoopback: false, allowPrivate: false });
54
- }
55
-
56
- export function assertPublicWebUrl(u) {
57
- let parsed;
58
- try {
59
- parsed = new URL(u);
60
- } catch {
61
- throw new Error(`invalid URL: ${u}`);
62
- }
63
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
64
- throw new Error(`only http(s) URLs allowed (got "${parsed.protocol}")`);
65
- }
66
- if (isDisallowedWebHost(parsed.hostname)) {
67
- throw new Error(`refusing to fetch a private/loopback/metadata address (${parsed.hostname})`);
68
- }
69
- return parsed;
70
- }
1
+ import{isLoopbackHost as e,isBlockedHost as r}from"./net.js";const a=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_ALLOW_PRIVATE_HOSTS||"");function s(t){return r(t,{allowLoopback:!0,allowPrivate:a})}function p(t){let o;try{o=new URL(t)}catch{throw new Error(`invalid URL: ${t}`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${o.protocol}")`);if(s(o.hostname))throw new Error(`refusing to proxy a private/metadata address (${o.hostname})`);return o}function l(t){return r(t,{allowLoopback:!1,allowPrivate:!1})}function i(t){let o;try{o=new URL(t)}catch{throw new Error(`invalid URL: ${t}`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${o.protocol}")`);if(l(o.hostname))throw new Error(`refusing to fetch a private/loopback/metadata address (${o.hostname})`);return o}export{p as assertPublicHttpUrl,i as assertPublicWebUrl,s as isBlockedHttpHost,l as isDisallowedWebHost,e as isLoopbackHost};