@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.
- package/README.md +7 -7
- package/package.json +1 -13
- package/scripts/sync-channels.mjs +8 -90
- package/scripts/sync-events.mjs +7 -78
- package/scripts/sync-pii.mjs +7 -68
- package/src/api-compat.js +5 -294
- package/src/channels/adapters/telegram.js +3 -298
- package/src/channels/bridge.js +1 -59
- package/src/channels/eventlog.js +3 -57
- package/src/channels/gateway.js +1 -114
- package/src/channels/invoke.js +1 -172
- package/src/channels/normalize.js +1 -58
- package/src/channels/pairing.js +1 -95
- package/src/channels/service.js +1 -329
- package/src/channels/stream.js +5 -104
- package/src/cli-errors.js +3 -136
- package/src/connections.js +1 -160
- package/src/connectors.js +1 -100
- package/src/engines/antigravity.js +5 -235
- package/src/engines/args.js +1 -47
- package/src/engines/claude.js +6 -586
- package/src/engines/cli-agents.js +7 -312
- package/src/engines/codex.js +6 -463
- package/src/engines/custom.js +17 -577
- package/src/engines/prompt.js +6 -32
- package/src/engines/stream-formats.js +2 -222
- package/src/entitlement.js +1 -77
- package/src/env.js +3 -628
- package/src/events/capability.js +1 -134
- package/src/events/event.js +1 -183
- package/src/events/reach.js +1 -31
- package/src/events/ref.js +1 -63
- package/src/events/scm-connection.js +1 -188
- package/src/events/scopes.js +1 -20
- package/src/events/skill-manifest.js +1 -338
- package/src/events/skill-scan.js +3 -217
- package/src/events/view.js +1 -96
- package/src/mcp-capabilities.js +2 -139
- package/src/mcp-local.js +0 -0
- package/src/mcp-quarantine.js +1 -110
- package/src/net.js +1 -107
- package/src/pii/index.js +1 -29
- package/src/pii/net.js +1 -111
- package/src/pii/pii-detect.js +2 -296
- package/src/pii/pii-redact.js +1 -470
- package/src/pii/pipeline.js +1 -137
- package/src/pii/sanitize.js +2 -179
- package/src/pii/tool-harness.js +1 -184
- package/src/pii/tool-rank.js +1 -110
- package/src/proc.js +2 -91
- package/src/relay-timeout.js +1 -21
- package/src/runs.js +1 -49
- package/src/sanitize.js +1 -7
- package/src/scm.js +1 -76
- package/src/server.js +10 -1492
- package/src/service.js +11 -176
- package/src/sign-in.js +1 -91
- package/src/skills.js +1 -399
- package/src/ssrf.js +1 -70
- package/src/update.js +1 -216
- package/src/workdir.js +1 -108
- package/src/worktree.js +3 -125
package/src/events/view.js
CHANGED
|
@@ -1,96 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-events/view.js (npm @chatpanel/events).
|
|
3
|
-
// Edit there, then run: npm run sync:events
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// CAPABILITY VIEWS — a capability may ship its own UI, so a result can be an interactive
|
|
10
|
-
// component instead of a paragraph of text.
|
|
11
|
-
//
|
|
12
|
-
// This is NOT the model writing HTML. That already exists (an ```html artifact runs in the
|
|
13
|
-
// sandbox) and is deliberately powerless: it is untrusted text, so it can only draw. A view
|
|
14
|
-
// is declared by a capability that a user or admin approved at load time, which is what
|
|
15
|
-
// makes it safe to give it something a model-authored page can never have — the ability to
|
|
16
|
-
// ACT, by invoking capabilities.
|
|
17
|
-
//
|
|
18
|
-
// The rule that keeps that safe is one line: a view may invoke only what its own capability
|
|
19
|
-
// is already allowed to invoke. A calculator view can compute because its capability may; it
|
|
20
|
-
// cannot read history unless that capability was granted `history` in the first place. There
|
|
21
|
-
// is no path here that widens a permission — `mayInvoke` can only ever name capabilities the
|
|
22
|
-
// declaring capability already lists in `requires`, and validateViewInvocation refuses
|
|
23
|
-
// anything outside that set before the kernel is ever consulted.
|
|
24
|
-
//
|
|
25
|
-
// Pure and host-free by design: no DOM, no postMessage, no chrome.*. The client owns the
|
|
26
|
-
// transport; this owns what is legal to say over it.
|
|
27
|
-
|
|
28
|
-
import { EventError } from './event.js';
|
|
29
|
-
|
|
30
|
-
const str = (v) => typeof v === 'string' && v.length > 0;
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Validate a view DECLARATION. Like the rest of the capability contract this must be
|
|
34
|
-
* readable — and therefore approvable — without executing anything.
|
|
35
|
-
*/
|
|
36
|
-
export function validateView(view, capability = null) {
|
|
37
|
-
if (!view || typeof view !== 'object') throw new EventError('SHAPE', 'view must be an object');
|
|
38
|
-
if (!str(view.id)) throw new EventError('SHAPE', 'view.id required');
|
|
39
|
-
if (!str(view.html)) throw new EventError('SHAPE', 'view.html required — a self-contained document');
|
|
40
|
-
if (view.mayInvoke != null && !(Array.isArray(view.mayInvoke) && view.mayInvoke.every(str))) {
|
|
41
|
-
throw new EventError('SHAPE', 'view.mayInvoke must be string[]');
|
|
42
|
-
}
|
|
43
|
-
// NO PRIVILEGE ESCALATION BY DECLARATION. A view is part of its capability, so it cannot
|
|
44
|
-
// reach past it: every id it wants to call must already be in that capability's `requires`
|
|
45
|
-
// (or be the capability itself). Caught here, at approval time, rather than at call time.
|
|
46
|
-
if (capability && view.mayInvoke?.length) {
|
|
47
|
-
const allowed = new Set([capability.id, ...(capability.requires || [])]);
|
|
48
|
-
const extra = view.mayInvoke.filter((id) => !allowed.has(id));
|
|
49
|
-
if (extra.length) {
|
|
50
|
-
throw new EventError('CONTRADICTION',
|
|
51
|
-
`view.mayInvoke exceeds its capability: ${extra.join(', ')} not in requires`);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
if (view.height != null && !(Number.isInteger(view.height) && view.height > 0 && view.height <= 2000)) {
|
|
55
|
-
throw new EventError('SHAPE', 'view.height must be a positive integer <= 2000');
|
|
56
|
-
}
|
|
57
|
-
return view;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Turn a message a VIEW sent into a capability invocation the kernel can judge — or refuse
|
|
62
|
-
* it. The view is sandboxed and its messages are untrusted input, so nothing here trusts a
|
|
63
|
-
* field: the capability id is checked against what the declaration allows, not against what
|
|
64
|
-
* the message claims to be entitled to.
|
|
65
|
-
*
|
|
66
|
-
* Returns { capability, args, callId }. Throws EventError otherwise.
|
|
67
|
-
*/
|
|
68
|
-
export function validateViewInvocation(msg, capability) {
|
|
69
|
-
if (!capability?.view) throw new EventError('SHAPE', 'capability declares no view');
|
|
70
|
-
if (!msg || typeof msg !== 'object') throw new EventError('SHAPE', 'view message must be an object');
|
|
71
|
-
if (!str(msg.callId)) throw new EventError('SHAPE', 'view message needs a callId to correlate its result');
|
|
72
|
-
if (!str(msg.capability)) throw new EventError('SHAPE', 'view message must name a capability');
|
|
73
|
-
|
|
74
|
-
const allowed = new Set([capability.id, ...(capability.view.mayInvoke || [])]);
|
|
75
|
-
if (!allowed.has(msg.capability)) {
|
|
76
|
-
// The important refusal. A compromised or buggy view asking for something else stops
|
|
77
|
-
// here, before any kernel guard has to have an opinion about it.
|
|
78
|
-
throw new EventError('DENIED',
|
|
79
|
-
`view of "${capability.id}" may not invoke "${msg.capability}"`);
|
|
80
|
-
}
|
|
81
|
-
if (msg.args != null && (typeof msg.args !== 'object' || Array.isArray(msg.args))) {
|
|
82
|
-
throw new EventError('SHAPE', 'view invocation args must be an object');
|
|
83
|
-
}
|
|
84
|
-
return { capability: msg.capability, args: msg.args || {}, callId: msg.callId };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* The state a view is mounted with, as it appears on a capability RESULT. Kept separate from
|
|
89
|
-
* the canonical value: `value` is what the capability computed and what everything else
|
|
90
|
-
* reasons about; `view`/`state` are only how it is shown. A host that cannot render views
|
|
91
|
-
* ignores these two fields and still has the whole answer.
|
|
92
|
-
*/
|
|
93
|
-
export function viewResult(value, capability, state = null) {
|
|
94
|
-
if (!capability?.view) return { value };
|
|
95
|
-
return { value, view: capability.view.id, state: state ?? value };
|
|
96
|
-
}
|
|
1
|
+
import{EventError as t}from"./event.js";const i=e=>typeof e=="string"&&e.length>0;function w(e,n=null){if(!e||typeof e!="object")throw new t("SHAPE","view must be an object");if(!i(e.id))throw new t("SHAPE","view.id required");if(!i(e.html))throw new t("SHAPE","view.html required — a self-contained document");if(e.mayInvoke!=null&&!(Array.isArray(e.mayInvoke)&&e.mayInvoke.every(i)))throw new t("SHAPE","view.mayInvoke must be string[]");if(n&&e.mayInvoke?.length){const r=new Set([n.id,...n.requires||[]]),o=e.mayInvoke.filter(a=>!r.has(a));if(o.length)throw new t("CONTRADICTION",`view.mayInvoke exceeds its capability: ${o.join(", ")} not in requires`)}if(e.height!=null&&!(Number.isInteger(e.height)&&e.height>0&&e.height<=2e3))throw new t("SHAPE","view.height must be a positive integer <= 2000");return e}function s(e,n){if(!n?.view)throw new t("SHAPE","capability declares no view");if(!e||typeof e!="object")throw new t("SHAPE","view message must be an object");if(!i(e.callId))throw new t("SHAPE","view message needs a callId to correlate its result");if(!i(e.capability))throw new t("SHAPE","view message must name a capability");if(!new Set([n.id,...n.view.mayInvoke||[]]).has(e.capability))throw new t("DENIED",`view of "${n.id}" may not invoke "${e.capability}"`);if(e.args!=null&&(typeof e.args!="object"||Array.isArray(e.args)))throw new t("SHAPE","view invocation args must be an object");return{capability:e.capability,args:e.args||{},callId:e.callId}}function h(e,n,r=null){return n?.view?{value:e,view:n.view.id,state:r??e}:{value:e}}export{w as validateView,s as validateViewInvocation,h as viewResult};
|
package/src/mcp-capabilities.js
CHANGED
|
@@ -1,140 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// The /mcp endpoint used to relay ONLY the page tools of an active browser chat: nothing
|
|
4
|
-
// to offer unless ChatPanel was open and driving. That makes ChatPanel a thing you drive,
|
|
5
|
-
// never a thing another agent can draw on. This is the other direction — a Codex or a
|
|
6
|
-
// Claude Code that adds the ChatPanel MCP server once gets ChatPanel's bridge-native
|
|
7
|
-
// capabilities as ordinary tools, whether or not a browser is open.
|
|
8
|
-
//
|
|
9
|
-
// A REGISTRY, so a new capability becomes an MCP tool by being registered — not by editing
|
|
10
|
-
// the MCP handler. That is the whole point of the ask "future capabilities should be
|
|
11
|
-
// available automatically": the handler enumerates this list, it does not hardcode a set.
|
|
12
|
-
//
|
|
13
|
-
// WHAT BELONGS HERE: capabilities the bridge can serve on its own — skills (on disk),
|
|
14
|
-
// redaction (the vendored pii engine), local MCP proxying. Notes, meetings and chat history
|
|
15
|
-
// live in the browser's encrypted on-device store; the bridge cannot read them, so they are
|
|
16
|
-
// NOT here — they stay behind the active-session relay (or a future shared store), and
|
|
17
|
-
// exposing on-device history to an external CLI is a privacy decision to make deliberately,
|
|
18
|
-
// not a tool to switch on by default.
|
|
1
|
+
import{skillIndex as s,listRecords as c,readRecord as d,readPackageFile as h}from"./skills.js";import{sanitizeUnicode as p,hasHiddenChars as u}from"./sanitize.js";const a=24e3;function o(){return[{name:"chatpanel_skill_list",description:"List the skills installed on this machine that ChatPanel can see — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes, ~/.agents) and any configured folder. Returns each skill's name and one-line description. Call this first, then chatpanel_skill_open to load the instructions of the one that fits.",schema:{type:"object",properties:{}},async run(){const{index:t}=await s(),n=c(t).map(e=>({name:e.command||e.id,title:e.name,description:e.description||"",from:e.origin?.source||"local",references:(e.files?.references||[]).length||void 0}));return r(JSON.stringify({skills:n},null,2))}},{name:"chatpanel_skill_open",description:"Load one skill's full instructions by name (from chatpanel_skill_list). Follow what it returns. If the instructions point at reference files, read one with chatpanel_skill_read.",schema:{type:"object",properties:{name:{type:"string",description:"The skill name from chatpanel_skill_list."}},required:["name"]},async run(t){const{index:n}=await s(),e=d(n,String(t?.name||"").trim());return e?r(e.prompt||"(this skill has no extra instructions — just apply it.)"):r(`No such skill "${t?.name}". Use chatpanel_skill_list to see what is available.`,!0)}},{name:"chatpanel_skill_read",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",schema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]},async run(t){const{index:n}=await s(),e=await h(n,String(t?.name||"").trim(),String(t?.path||"").trim());if(e.error)return r(`Could not read it: ${e.error}`,!0);const i=e.text.length>a?`${e.text.slice(0,a)}
|
|
19
2
|
|
|
20
|
-
|
|
21
|
-
import { sanitizeUnicode, hasHiddenChars } from './sanitize.js';
|
|
22
|
-
|
|
23
|
-
const MAX_REF = 24_000;
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* The always-on capability tools. Each: { name, description, schema, run(args) -> content }.
|
|
27
|
-
* `run` returns MCP content parts. Kept small and pure-ish; the store calls are the only IO.
|
|
28
|
-
*/
|
|
29
|
-
export function capabilityTools() {
|
|
30
|
-
return [
|
|
31
|
-
{
|
|
32
|
-
name: 'chatpanel_skill_list',
|
|
33
|
-
description:
|
|
34
|
-
'List the skills installed on this machine that ChatPanel can see — across every '
|
|
35
|
-
+ 'agent harness (Claude Code, Codex, Copilot, Gemini, Hermes, ~/.agents) and any '
|
|
36
|
-
+ 'configured folder. Returns each skill\'s name and one-line description. Call this '
|
|
37
|
-
+ 'first, then chatpanel_skill_open to load the instructions of the one that fits.',
|
|
38
|
-
schema: { type: 'object', properties: {} },
|
|
39
|
-
async run() {
|
|
40
|
-
const { index } = await skillIndex();
|
|
41
|
-
const rows = listRecords(index).map((s) => ({
|
|
42
|
-
name: s.command || s.id,
|
|
43
|
-
title: s.name,
|
|
44
|
-
description: s.description || '',
|
|
45
|
-
from: s.origin?.source || 'local',
|
|
46
|
-
references: (s.files?.references || []).length || undefined,
|
|
47
|
-
}));
|
|
48
|
-
return text(JSON.stringify({ skills: rows }, null, 2));
|
|
49
|
-
},
|
|
50
|
-
},
|
|
51
|
-
{
|
|
52
|
-
name: 'chatpanel_skill_open',
|
|
53
|
-
description:
|
|
54
|
-
'Load one skill\'s full instructions by name (from chatpanel_skill_list). Follow what '
|
|
55
|
-
+ 'it returns. If the instructions point at reference files, read one with '
|
|
56
|
-
+ 'chatpanel_skill_read.',
|
|
57
|
-
schema: {
|
|
58
|
-
type: 'object',
|
|
59
|
-
properties: { name: { type: 'string', description: 'The skill name from chatpanel_skill_list.' } },
|
|
60
|
-
required: ['name'],
|
|
61
|
-
},
|
|
62
|
-
async run(args) {
|
|
63
|
-
const { index } = await skillIndex();
|
|
64
|
-
const skill = readRecord(index, String(args?.name || '').trim());
|
|
65
|
-
if (!skill) return text(`No such skill "${args?.name}". Use chatpanel_skill_list to see what is available.`, true);
|
|
66
|
-
return text(skill.prompt || '(this skill has no extra instructions — just apply it.)');
|
|
67
|
-
},
|
|
68
|
-
},
|
|
69
|
-
{
|
|
70
|
-
name: 'chatpanel_skill_read',
|
|
71
|
-
description:
|
|
72
|
-
'Read one reference file a skill\'s instructions point at (any path inside the skill\'s '
|
|
73
|
-
+ 'own folder). Use only when the task needs it.',
|
|
74
|
-
schema: {
|
|
75
|
-
type: 'object',
|
|
76
|
-
properties: {
|
|
77
|
-
name: { type: 'string', description: 'The skill name.' },
|
|
78
|
-
path: { type: 'string', description: 'The reference path as written in the instructions, e.g. references/auth.md.' },
|
|
79
|
-
},
|
|
80
|
-
required: ['name', 'path'],
|
|
81
|
-
},
|
|
82
|
-
async run(args) {
|
|
83
|
-
const { index } = await skillIndex();
|
|
84
|
-
const out = await readPackageFile(index, String(args?.name || '').trim(), String(args?.path || '').trim());
|
|
85
|
-
if (out.error) return text(`Could not read it: ${out.error}`, true);
|
|
86
|
-
const body = out.text.length > MAX_REF ? `${out.text.slice(0, MAX_REF)}\n\n…[truncated]` : out.text;
|
|
87
|
-
return text(body);
|
|
88
|
-
},
|
|
89
|
-
},
|
|
90
|
-
{
|
|
91
|
-
// Bridge-native security hygiene: strip the invisible and look-alike characters used to
|
|
92
|
-
// smuggle instructions past a human reader — a real risk for a CLI processing pasted or
|
|
93
|
-
// fetched text. This is the unicode layer, honestly scoped: it is NOT full PII redaction
|
|
94
|
-
// (names, emails), which lives in the gateway with the complete engine. Naming it
|
|
95
|
-
// precisely matters more than sounding capable.
|
|
96
|
-
name: 'chatpanel_sanitize_text',
|
|
97
|
-
description:
|
|
98
|
-
'Remove hidden and look-alike Unicode characters from text (zero-width joiners, '
|
|
99
|
-
+ 'bidirectional overrides, the tag block, homoglyphs) — the tricks used to hide '
|
|
100
|
-
+ 'instructions from a human while a model still sees them. Returns the cleaned text and '
|
|
101
|
-
+ 'what was removed. Use before trusting text pasted or fetched from an untrusted source. '
|
|
102
|
-
+ 'This is not full PII redaction (names, emails) — that lives in the ChatPanel gateway.',
|
|
103
|
-
schema: {
|
|
104
|
-
type: 'object',
|
|
105
|
-
properties: { text: { type: 'string', description: 'The text to sanitize.' } },
|
|
106
|
-
required: ['text'],
|
|
107
|
-
},
|
|
108
|
-
async run(args) {
|
|
109
|
-
const input = String(args?.text ?? '');
|
|
110
|
-
const { clean, removed, findings } = sanitizeUnicode(input);
|
|
111
|
-
return text(JSON.stringify({
|
|
112
|
-
clean,
|
|
113
|
-
hadHiddenCharacters: hasHiddenChars(input),
|
|
114
|
-
removed: removed || 0,
|
|
115
|
-
findings: findings || {}, // per-category counts, e.g. { bidi: 1, zeroWidth: 2 }
|
|
116
|
-
}, null, 2));
|
|
117
|
-
},
|
|
118
|
-
},
|
|
119
|
-
];
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function text(s, isError = false) {
|
|
123
|
-
return { content: [{ type: 'text', text: String(s) }], ...(isError ? { isError: true } : {}) };
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** MCP tools/list shape for the capability tools. */
|
|
127
|
-
export function capabilityToolSpecs() {
|
|
128
|
-
return capabilityTools().map((t) => ({ name: t.name, description: t.description, inputSchema: t.schema }));
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** Run one capability tool by name, or null if it is not one of ours. */
|
|
132
|
-
export async function runCapabilityTool(name, args) {
|
|
133
|
-
const tool = capabilityTools().find((t) => t.name === name);
|
|
134
|
-
if (!tool) return null;
|
|
135
|
-
try {
|
|
136
|
-
return await tool.run(args || {});
|
|
137
|
-
} catch (e) {
|
|
138
|
-
return text(`error: ${e?.message || e}`, true);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
3
|
+
…[truncated]`:e.text;return r(i)}},{name:"chatpanel_sanitize_text",description:"Remove hidden and look-alike Unicode characters from text (zero-width joiners, bidirectional overrides, the tag block, homoglyphs) — the tricks used to hide instructions from a human while a model still sees them. Returns the cleaned text and what was removed. Use before trusting text pasted or fetched from an untrusted source. This is not full PII redaction (names, emails) — that lives in the ChatPanel gateway.",schema:{type:"object",properties:{text:{type:"string",description:"The text to sanitize."}},required:["text"]},async run(t){const n=String(t?.text??""),{clean:e,removed:i,findings:l}=p(n);return r(JSON.stringify({clean:e,hadHiddenCharacters:u(n),removed:i||0,findings:l||{}},null,2))}}]}function r(t,n=!1){return{content:[{type:"text",text:String(t)}],...n?{isError:!0}:{}}}function y(){return o().map(t=>({name:t.name,description:t.description,inputSchema:t.schema}))}async function k(t,n){const e=o().find(i=>i.name===t);if(!e)return null;try{return await e.run(n||{})}catch(i){return r(`error: ${i?.message||i}`,!0)}}export{y as capabilityToolSpecs,o as capabilityTools,k as runCapabilityTool};
|
package/src/mcp-local.js
CHANGED
|
Binary file
|
package/src/mcp-quarantine.js
CHANGED
|
@@ -1,110 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// A CLI agent loads EVERY MCP server in the user's own config on every single run. One that
|
|
4
|
-
// cannot authenticate — an expired OAuth token, a VPN-only host seen from a coffee shop —
|
|
5
|
-
// takes the whole turn down with it, even when the question had nothing to do with that
|
|
6
|
-
// server. The user is then told to go re-login to something they never asked for.
|
|
7
|
-
//
|
|
8
|
-
// So: read the failure, name the server, drop it, run again. Two ways in —
|
|
9
|
-
// 1. the user's own deny list (`options.mcpDisabled`), for servers they know they don't
|
|
10
|
-
// want ChatPanel to load at all; and
|
|
11
|
-
// 2. QUARANTINE — a server that just killed a run is dropped automatically and stays
|
|
12
|
-
// dropped for the rest of the bridge's session, since it will not have healed in the
|
|
13
|
-
// twenty seconds before the next message.
|
|
14
|
-
//
|
|
15
|
-
// Two rules keep this honest. It is never silent: dropping a tool without saying so is worse
|
|
16
|
-
// than failing loudly, so the engine emits a status line naming what it skipped. And it never
|
|
17
|
-
// drops ChatPanel's OWN injected server — that one failing is our bug to surface, not a
|
|
18
|
-
// nuisance to route around (silently disabling it would take "Act on page" with it).
|
|
19
|
-
//
|
|
20
|
-
// Engine-agnostic on purpose: Codex renders this as `-c mcp_servers.X.enabled=false`, Claude
|
|
21
|
-
// Code and Copilot as their own flags, but the POLICY — which servers may load this turn —
|
|
22
|
-
// is one decision, made here, not re-derived per engine.
|
|
23
|
-
|
|
24
|
-
import { mcpFailure } from './cli-errors.js';
|
|
25
|
-
|
|
26
|
-
// A server that failed is dropped for this long. Long enough that a chat session never pays
|
|
27
|
-
// the same failed startup twice; short enough that reconnecting the VPN and waiting a while
|
|
28
|
-
// brings the server back without restarting the bridge.
|
|
29
|
-
const TTL_MS = Number(process.env.CHATPANEL_MCP_QUARANTINE_MS) || 30 * 60_000;
|
|
30
|
-
|
|
31
|
-
const dropped = new Map(); // `${agent} ${server}` -> expiry epoch ms
|
|
32
|
-
|
|
33
|
-
const key = (agent, server) => `${agent} ${server}`;
|
|
34
|
-
|
|
35
|
-
function prune(now = Date.now()) {
|
|
36
|
-
for (const [k, expiry] of dropped) if (expiry <= now) dropped.delete(k);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Server names are interpolated into a config override key (`mcp_servers.<name>.enabled`),
|
|
41
|
-
* so they are validated rather than escaped: anything that isn't a plain MCP server name is
|
|
42
|
-
* dropped. Dots are excluded too — Codex's `-c` parser reads them as further path segments
|
|
43
|
-
* and rejects the quoted form. Accepts an array or a comma/space-separated string (what the
|
|
44
|
-
* settings field holds).
|
|
45
|
-
*/
|
|
46
|
-
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
47
|
-
|
|
48
|
-
/** One name, validated whole — no splitting, so junk is rejected rather than chopped valid. */
|
|
49
|
-
export function validName(value) {
|
|
50
|
-
const name = String(value || '').trim();
|
|
51
|
-
return NAME_RE.test(name) ? name : null;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export function normalizeNames(value) {
|
|
55
|
-
const list = Array.isArray(value) ? value : String(value || '').split(/[,\s]+/);
|
|
56
|
-
const out = [];
|
|
57
|
-
for (const raw of list) {
|
|
58
|
-
const name = validName(raw);
|
|
59
|
-
if (name && !out.includes(name)) out.push(name);
|
|
60
|
-
}
|
|
61
|
-
return out;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** The servers currently quarantined for an agent. */
|
|
65
|
-
export function quarantined(agent) {
|
|
66
|
-
prune();
|
|
67
|
-
const prefix = key(agent, '');
|
|
68
|
-
return [...dropped.keys()].filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length));
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Drop a server for this agent. Returns false when it was already dropped. */
|
|
72
|
-
export function quarantine(agent, server) {
|
|
73
|
-
const name = validName(server);
|
|
74
|
-
if (!name) return false;
|
|
75
|
-
const k = key(agent, name);
|
|
76
|
-
const fresh = !dropped.has(k);
|
|
77
|
-
dropped.set(k, Date.now() + TTL_MS);
|
|
78
|
-
return fresh;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** Test seam — the store is process-global by design. */
|
|
82
|
-
export function resetQuarantine() {
|
|
83
|
-
dropped.clear();
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Every server this run must not load: the user's deny list plus anything quarantined,
|
|
88
|
-
* minus the servers ChatPanel itself injected (never route around our own).
|
|
89
|
-
*/
|
|
90
|
-
export function disabledMcpServers(agent, options = {}, protect = []) {
|
|
91
|
-
const guard = new Set(normalizeNames(protect));
|
|
92
|
-
const names = [...normalizeNames(options.mcpDisabled), ...quarantined(agent)];
|
|
93
|
-
return [...new Set(names)].filter((n) => !guard.has(n));
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Should this failed run be retried without one of the agent's own MCP servers?
|
|
98
|
-
* Returns the server to drop, or null — and null is the safe answer: a failure that names no
|
|
99
|
-
* server, or names one we already dropped, means retrying would only fail the same way.
|
|
100
|
-
* @returns {{server: string, kind: string, short: string}|null}
|
|
101
|
-
*/
|
|
102
|
-
export function planMcpRetry({ agent = '', text = '', protect = [], already = [] } = {}) {
|
|
103
|
-
const failure = mcpFailure(text);
|
|
104
|
-
if (!failure?.server) return null;
|
|
105
|
-
if (!validName(failure.server)) return null; // a name we could never write as an override
|
|
106
|
-
if (normalizeNames(protect).includes(failure.server)) return null;
|
|
107
|
-
if (normalizeNames(already).includes(failure.server)) return null;
|
|
108
|
-
if (quarantined(agent).includes(failure.server)) return null;
|
|
109
|
-
return { server: failure.server, kind: failure.kind, short: failure.short };
|
|
110
|
-
}
|
|
1
|
+
import{mcpFailure as f}from"./cli-errors.js";const p=Number(process.env.CHATPANEL_MCP_QUARANTINE_MS)||30*6e4,o=new Map,c=(e,r)=>`${e} ${r}`;function d(e=Date.now()){for(const[r,n]of o)n<=e&&o.delete(r)}const m=/^[A-Za-z0-9_-]{1,64}$/;function u(e){const r=String(e||"").trim();return m.test(r)?r:null}function i(e){const r=Array.isArray(e)?e:String(e||"").split(/[,\s]+/),n=[];for(const s of r){const t=u(s);t&&!n.includes(t)&&n.push(t)}return n}function a(e){d();const r=c(e,"");return[...o.keys()].filter(n=>n.startsWith(r)).map(n=>n.slice(r.length))}function h(e,r){const n=u(r);if(!n)return!1;const s=c(e,n),t=!o.has(s);return o.set(s,Date.now()+p),t}function v(){o.clear()}function A(e,r={},n=[]){const s=new Set(i(n)),t=[...i(r.mcpDisabled),...a(e)];return[...new Set(t)].filter(l=>!s.has(l))}function M({agent:e="",text:r="",protect:n=[],already:s=[]}={}){const t=f(r);return!t?.server||!u(t.server)||i(n).includes(t.server)||i(s).includes(t.server)||a(e).includes(t.server)?null:{server:t.server,kind:t.kind,short:t.short}}export{A as disabledMcpServers,i as normalizeNames,M as planMcpRetry,h as quarantine,a as quarantined,v as resetQuarantine,u as validName};
|
package/src/net.js
CHANGED
|
@@ -1,107 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// (the bridge stays dependency-free, so this is a copy, not an import). Regenerate
|
|
3
|
-
// by copying ../chatpanel-pii/net.js over this file (then re-add this header).
|
|
4
|
-
//
|
|
5
|
-
// Shared host classifier + outbound-URL guard — the SSRF primitive.
|
|
6
|
-
//
|
|
7
|
-
// One implementation of "what is a loopback / cloud-metadata / private host",
|
|
8
|
-
// delivered the way the rest of @chatpanel/pii is: npm dependency for the
|
|
9
|
-
// gateway/bridge, vendorable into the browser extension (pure — only URL + string
|
|
10
|
-
// ops, no node APIs, so it runs in a Worker/service-worker too). Replaces the
|
|
11
|
-
// hand-maintained copies in the bridge (src/ssrf.js) and the extension
|
|
12
|
-
// (js/context.js isBlockedHost) so a security guard can't silently drift between
|
|
13
|
-
// the direct client path and the proxied path. See docs/secure-data-plane.md.
|
|
14
|
-
//
|
|
15
|
-
// The policy knobs cover the two legitimate trust contexts:
|
|
16
|
-
// • A MODEL / API / MCP endpoint (gateway upstream, bridge MCP proxy) may live on
|
|
17
|
-
// loopback (Ollama, LM Studio) or the LAN (a homelab GPU box) — so those are
|
|
18
|
-
// allowed by default — but must NEVER reach cloud instance metadata.
|
|
19
|
-
// • A WEB PAGE fetch (link title, page context) has no business touching loopback
|
|
20
|
-
// or any private host at all — call with { allowLoopback:false, allowPrivate:false }.
|
|
21
|
-
// Cloud metadata (169.254.169.254 & friends) and non-http(s) schemes are blocked in
|
|
22
|
-
// BOTH contexts, unconditionally. Re-run the assert on every redirect hop.
|
|
23
|
-
|
|
24
|
-
function ipv4(h) {
|
|
25
|
-
const m = String(h).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
26
|
-
if (!m) return null;
|
|
27
|
-
const o = m.slice(1).map(Number);
|
|
28
|
-
if (o.some((n) => n > 255)) return null;
|
|
29
|
-
return o;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const norm = (hostname) => String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
|
|
33
|
-
|
|
34
|
-
// Loopback = this host's own services (127.0.0.0/8, ::1, localhost, *.localhost).
|
|
35
|
-
export function isLoopbackHost(hostname) {
|
|
36
|
-
const h = norm(hostname);
|
|
37
|
-
if (!h) return false;
|
|
38
|
-
if (h === 'localhost' || h.endsWith('.localhost')) return true;
|
|
39
|
-
if (h === '::1') return true;
|
|
40
|
-
const o = ipv4(h);
|
|
41
|
-
return !!(o && o[0] === 127);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Cloud instance metadata — the sharpest SSRF target (credential theft). Covers the
|
|
45
|
-
// link-local IMDS address used by AWS/GCP/Azure/DO (169.254.169.254), Alibaba's
|
|
46
|
-
// 100.100.100.200, and the GCP/name-based metadata hosts. ALWAYS blocked.
|
|
47
|
-
export function isMetadataHost(hostname) {
|
|
48
|
-
const h = norm(hostname);
|
|
49
|
-
if (h === 'metadata.google.internal' || h === 'metadata') return true;
|
|
50
|
-
const o = ipv4(h);
|
|
51
|
-
if (!o) return false;
|
|
52
|
-
if (o[0] === 169 && o[1] === 254) return true; // 169.254.169.254 (+ link-local)
|
|
53
|
-
if (o[0] === 100 && o[1] === 100 && o[2] === 100 && o[3] === 200) return true; // Alibaba IMDS
|
|
54
|
-
return false;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Private / internal address space, EXCLUDING loopback + metadata (checked
|
|
58
|
-
// separately): RFC1918, CGNAT, IPv6 ULA/link-local, mDNS .local, this-host 0.x/::.
|
|
59
|
-
export function isPrivateHost(hostname) {
|
|
60
|
-
const h = norm(hostname);
|
|
61
|
-
if (!h) return true;
|
|
62
|
-
if (h.endsWith('.local')) return true;
|
|
63
|
-
if (
|
|
64
|
-
h === '::' || h.startsWith('fc') || h.startsWith('fd') // IPv6 ULA
|
|
65
|
-
|| h.startsWith('fe8') || h.startsWith('fe9') || h.startsWith('fea') || h.startsWith('feb') // link-local
|
|
66
|
-
) return true;
|
|
67
|
-
const o = ipv4(h);
|
|
68
|
-
if (o) {
|
|
69
|
-
const [a, b] = o;
|
|
70
|
-
if (a === 0 || a === 10) return true; // this-host / RFC1918
|
|
71
|
-
if (a === 169 && b === 254) return true; // link-local
|
|
72
|
-
if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918
|
|
73
|
-
if (a === 192 && b === 168) return true; // RFC1918
|
|
74
|
-
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
|
75
|
-
}
|
|
76
|
-
return false;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// Policy-driven classifier. Returns true if `hostname` must be blocked under `policy`.
|
|
80
|
-
// Defaults model the ENDPOINT context (loopback + LAN allowed, metadata never).
|
|
81
|
-
export function isBlockedHost(hostname, { allowLoopback = true, allowPrivate = true } = {}) {
|
|
82
|
-
const h = norm(hostname);
|
|
83
|
-
if (!h) return true;
|
|
84
|
-
if (isMetadataHost(h)) return true; // never, in any context
|
|
85
|
-
if (isLoopbackHost(h)) return !allowLoopback;
|
|
86
|
-
if (isPrivateHost(h)) return !allowPrivate;
|
|
87
|
-
return false; // public host
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// Assert a URL is fetchable under `policy`; returns the parsed URL or throws.
|
|
91
|
-
// Call on the initial URL AND after every redirect hop.
|
|
92
|
-
export function assertFetchableUrl(u, policy = {}) {
|
|
93
|
-
let parsed;
|
|
94
|
-
try { parsed = new URL(u); } catch { throw new Error(`invalid URL: ${u}`); }
|
|
95
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
96
|
-
throw new Error(`only http(s) URLs allowed (got "${parsed.protocol}")`);
|
|
97
|
-
}
|
|
98
|
-
if (isBlockedHost(parsed.hostname, policy)) {
|
|
99
|
-
throw new Error(`refusing to reach a blocked address (${parsed.hostname})`);
|
|
100
|
-
}
|
|
101
|
-
return parsed;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// Endpoint context: model/API/MCP upstream — loopback + LAN OK, metadata never.
|
|
105
|
-
export const assertEndpointUrl = (u, opts = {}) => assertFetchableUrl(u, { allowLoopback: true, allowPrivate: true, ...opts });
|
|
106
|
-
// Web-page context: no loopback, no private, no metadata — genuinely public only.
|
|
107
|
-
export const assertPublicWebUrl = (u) => assertFetchableUrl(u, { allowLoopback: false, allowPrivate: false });
|
|
1
|
+
function u(e){const t=String(e).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(o=>o>255)?null:r}const s=e=>String(e||"").toLowerCase().replace(/^\[|\]$/g,"");function i(e){const t=s(e);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost")||t==="::1")return!0;const r=u(t);return!!(r&&r[0]===127)}function f(e){const t=s(e);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=u(t);return r?r[0]===169&&r[1]===254||r[0]===100&&r[1]===100&&r[2]===100&&r[3]===200:!1}function l(e){const t=s(e);if(!t||t.endsWith(".local")||t==="::"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb"))return!0;const r=u(t);if(r){const[o,n]=r;if(o===0||o===10||o===169&&n===254||o===172&&n>=16&&n<=31||o===192&&n===168||o===100&&n>=64&&n<=127)return!0}return!1}function c(e,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const o=s(e);return!o||f(o)?!0:i(o)?!t:l(o)?!r:!1}function a(e,t={}){let r;try{r=new URL(e)}catch{throw new Error(`invalid URL: ${e}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(c(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const h=(e,t={})=>a(e,{allowLoopback:!0,allowPrivate:!0,...t}),p=e=>a(e,{allowLoopback:!1,allowPrivate:!1});export{h as assertEndpointUrl,a as assertFetchableUrl,p as assertPublicWebUrl,c as isBlockedHost,i as isLoopbackHost,f as isMetadataHost,l as isPrivateHost};
|
package/src/pii/index.js
CHANGED
|
@@ -1,29 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-pii/index.js (npm @chatpanel/pii).
|
|
3
|
-
// Edit there, then run: npm run sync:pii
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// chatpanel-pii — the canonical ChatPanel privacy engine. Single source of truth
|
|
10
|
-
// for reversible PII redaction + pseudonymization, shared by the extension, the
|
|
11
|
-
// gateway, and the bridge. Pure + dependency-free ESM.
|
|
12
|
-
//
|
|
13
|
-
// import { createVault, redactText, restoreText, detectEntities } from 'chatpanel-pii';
|
|
14
|
-
//
|
|
15
|
-
// Submodules are also importable directly:
|
|
16
|
-
// 'chatpanel-pii/pii-redact.js' deterministic redact/restore + vault
|
|
17
|
-
// 'chatpanel-pii/pii-detect.js' local NER / LLM entity detection
|
|
18
|
-
// 'chatpanel-pii/pipeline.js' pure turn orchestration + tier/scope selection
|
|
19
|
-
// 'chatpanel-pii/tool-rank.js' deterministic tool narrowing (auto mode)
|
|
20
|
-
// 'chatpanel-pii/sanitize.js' Unicode de-steganography (strip invisible/format chars)
|
|
21
|
-
// 'chatpanel-pii/net.js' SSRF host classifier + outbound-URL guard
|
|
22
|
-
|
|
23
|
-
export * from './pii-redact.js';
|
|
24
|
-
export * from './pii-detect.js';
|
|
25
|
-
export * from './pipeline.js';
|
|
26
|
-
export * from './tool-rank.js';
|
|
27
|
-
export * from './tool-harness.js';
|
|
28
|
-
export * from './sanitize.js';
|
|
29
|
-
export * from './net.js';
|
|
1
|
+
export*from"./pii-redact.js";export*from"./pii-detect.js";export*from"./pipeline.js";export*from"./tool-rank.js";export*from"./tool-harness.js";export*from"./sanitize.js";export*from"./net.js";
|
package/src/pii/net.js
CHANGED
|
@@ -1,111 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-pii/net.js (npm @chatpanel/pii).
|
|
3
|
-
// Edit there, then run: npm run sync:pii
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// Shared host classifier + outbound-URL guard — the SSRF primitive.
|
|
10
|
-
//
|
|
11
|
-
// One implementation of "what is a loopback / cloud-metadata / private host",
|
|
12
|
-
// delivered the way the rest of @chatpanel/pii is: npm dependency for the
|
|
13
|
-
// gateway/bridge, vendorable into the browser extension (pure — only URL + string
|
|
14
|
-
// ops, no node APIs, so it runs in a Worker/service-worker too). Replaces the
|
|
15
|
-
// hand-maintained copies in the bridge (src/ssrf.js) and the extension
|
|
16
|
-
// (js/context.js isBlockedHost) so a security guard can't silently drift between
|
|
17
|
-
// the direct client path and the proxied path. See docs/secure-data-plane.md.
|
|
18
|
-
//
|
|
19
|
-
// The policy knobs cover the two legitimate trust contexts:
|
|
20
|
-
// • A MODEL / API / MCP endpoint (gateway upstream, bridge MCP proxy) may live on
|
|
21
|
-
// loopback (Ollama, LM Studio) or the LAN (a homelab GPU box) — so those are
|
|
22
|
-
// allowed by default — but must NEVER reach cloud instance metadata.
|
|
23
|
-
// • A WEB PAGE fetch (link title, page context) has no business touching loopback
|
|
24
|
-
// or any private host at all — call with { allowLoopback:false, allowPrivate:false }.
|
|
25
|
-
// Cloud metadata (169.254.169.254 & friends) and non-http(s) schemes are blocked in
|
|
26
|
-
// BOTH contexts, unconditionally. Re-run the assert on every redirect hop.
|
|
27
|
-
|
|
28
|
-
function ipv4(h) {
|
|
29
|
-
const m = String(h).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
30
|
-
if (!m) return null;
|
|
31
|
-
const o = m.slice(1).map(Number);
|
|
32
|
-
if (o.some((n) => n > 255)) return null;
|
|
33
|
-
return o;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const norm = (hostname) => String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
|
|
37
|
-
|
|
38
|
-
// Loopback = this host's own services (127.0.0.0/8, ::1, localhost, *.localhost).
|
|
39
|
-
export function isLoopbackHost(hostname) {
|
|
40
|
-
const h = norm(hostname);
|
|
41
|
-
if (!h) return false;
|
|
42
|
-
if (h === 'localhost' || h.endsWith('.localhost')) return true;
|
|
43
|
-
if (h === '::1') return true;
|
|
44
|
-
const o = ipv4(h);
|
|
45
|
-
return !!(o && o[0] === 127);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// Cloud instance metadata — the sharpest SSRF target (credential theft). Covers the
|
|
49
|
-
// link-local IMDS address used by AWS/GCP/Azure/DO (169.254.169.254), Alibaba's
|
|
50
|
-
// 100.100.100.200, and the GCP/name-based metadata hosts. ALWAYS blocked.
|
|
51
|
-
export function isMetadataHost(hostname) {
|
|
52
|
-
const h = norm(hostname);
|
|
53
|
-
if (h === 'metadata.google.internal' || h === 'metadata') return true;
|
|
54
|
-
const o = ipv4(h);
|
|
55
|
-
if (!o) return false;
|
|
56
|
-
if (o[0] === 169 && o[1] === 254) return true; // 169.254.169.254 (+ link-local)
|
|
57
|
-
if (o[0] === 100 && o[1] === 100 && o[2] === 100 && o[3] === 200) return true; // Alibaba IMDS
|
|
58
|
-
return false;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Private / internal address space, EXCLUDING loopback + metadata (checked
|
|
62
|
-
// separately): RFC1918, CGNAT, IPv6 ULA/link-local, mDNS .local, this-host 0.x/::.
|
|
63
|
-
export function isPrivateHost(hostname) {
|
|
64
|
-
const h = norm(hostname);
|
|
65
|
-
if (!h) return true;
|
|
66
|
-
if (h.endsWith('.local')) return true;
|
|
67
|
-
if (
|
|
68
|
-
h === '::' || h.startsWith('fc') || h.startsWith('fd') // IPv6 ULA
|
|
69
|
-
|| h.startsWith('fe8') || h.startsWith('fe9') || h.startsWith('fea') || h.startsWith('feb') // link-local
|
|
70
|
-
) return true;
|
|
71
|
-
const o = ipv4(h);
|
|
72
|
-
if (o) {
|
|
73
|
-
const [a, b] = o;
|
|
74
|
-
if (a === 0 || a === 10) return true; // this-host / RFC1918
|
|
75
|
-
if (a === 169 && b === 254) return true; // link-local
|
|
76
|
-
if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918
|
|
77
|
-
if (a === 192 && b === 168) return true; // RFC1918
|
|
78
|
-
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
|
79
|
-
}
|
|
80
|
-
return false;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// Policy-driven classifier. Returns true if `hostname` must be blocked under `policy`.
|
|
84
|
-
// Defaults model the ENDPOINT context (loopback + LAN allowed, metadata never).
|
|
85
|
-
export function isBlockedHost(hostname, { allowLoopback = true, allowPrivate = true } = {}) {
|
|
86
|
-
const h = norm(hostname);
|
|
87
|
-
if (!h) return true;
|
|
88
|
-
if (isMetadataHost(h)) return true; // never, in any context
|
|
89
|
-
if (isLoopbackHost(h)) return !allowLoopback;
|
|
90
|
-
if (isPrivateHost(h)) return !allowPrivate;
|
|
91
|
-
return false; // public host
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// Assert a URL is fetchable under `policy`; returns the parsed URL or throws.
|
|
95
|
-
// Call on the initial URL AND after every redirect hop.
|
|
96
|
-
export function assertFetchableUrl(u, policy = {}) {
|
|
97
|
-
let parsed;
|
|
98
|
-
try { parsed = new URL(u); } catch { throw new Error(`invalid URL: ${u}`); }
|
|
99
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
100
|
-
throw new Error(`only http(s) URLs allowed (got "${parsed.protocol}")`);
|
|
101
|
-
}
|
|
102
|
-
if (isBlockedHost(parsed.hostname, policy)) {
|
|
103
|
-
throw new Error(`refusing to reach a blocked address (${parsed.hostname})`);
|
|
104
|
-
}
|
|
105
|
-
return parsed;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Endpoint context: model/API/MCP upstream — loopback + LAN OK, metadata never.
|
|
109
|
-
export const assertEndpointUrl = (u, opts = {}) => assertFetchableUrl(u, { allowLoopback: true, allowPrivate: true, ...opts });
|
|
110
|
-
// Web-page context: no loopback, no private, no metadata — genuinely public only.
|
|
111
|
-
export const assertPublicWebUrl = (u) => assertFetchableUrl(u, { allowLoopback: false, allowPrivate: false });
|
|
1
|
+
function u(e){const t=String(e).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(o=>o>255)?null:r}const s=e=>String(e||"").toLowerCase().replace(/^\[|\]$/g,"");function i(e){const t=s(e);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost")||t==="::1")return!0;const r=u(t);return!!(r&&r[0]===127)}function f(e){const t=s(e);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=u(t);return r?r[0]===169&&r[1]===254||r[0]===100&&r[1]===100&&r[2]===100&&r[3]===200:!1}function l(e){const t=s(e);if(!t||t.endsWith(".local")||t==="::"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb"))return!0;const r=u(t);if(r){const[o,n]=r;if(o===0||o===10||o===169&&n===254||o===172&&n>=16&&n<=31||o===192&&n===168||o===100&&n>=64&&n<=127)return!0}return!1}function c(e,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const o=s(e);return!o||f(o)?!0:i(o)?!t:l(o)?!r:!1}function a(e,t={}){let r;try{r=new URL(e)}catch{throw new Error(`invalid URL: ${e}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(c(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const h=(e,t={})=>a(e,{allowLoopback:!0,allowPrivate:!0,...t}),p=e=>a(e,{allowLoopback:!1,allowPrivate:!1});export{h as assertEndpointUrl,a as assertFetchableUrl,p as assertPublicWebUrl,c as isBlockedHost,i as isLoopbackHost,f as isMetadataHost,l as isPrivateHost};
|