@rubytech/create-maxy-code 0.1.350 → 0.1.352
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/dist/index.js +14 -0
- package/package.json +2 -2
- package/payload/platform/config/brand.json +1 -1
- package/payload/platform/plugins/.claude-plugin/marketplace.json +5 -0
- package/payload/platform/plugins/admin/PLUGIN.md +1 -0
- package/payload/platform/plugins/admin/hooks/lib/maxy-mcp-plugins.txt +1 -0
- package/payload/platform/plugins/admin/mcp/dist/__tests__/capabilities-here.test.js +27 -10
- package/payload/platform/plugins/admin/mcp/dist/__tests__/capabilities-here.test.js.map +1 -1
- package/payload/platform/plugins/admin/skills/agent-builder/SKILL.md +107 -0
- package/payload/platform/plugins/admin/skills/agent-builder/references/agent-pattern.md +103 -0
- package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +40 -2
- package/payload/platform/plugins/connector/.claude-plugin/plugin.json +21 -0
- package/payload/platform/plugins/connector/PLUGIN.md +55 -0
- package/payload/platform/plugins/connector/lib/mcp-spawn-tee/index.js +193 -0
- package/payload/platform/plugins/connector/lib/mcp-spawn-tee/package.json +3 -0
- package/payload/platform/plugins/connector/mcp/dist/index.d.ts +2 -0
- package/payload/platform/plugins/connector/mcp/dist/index.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/index.js +119 -0
- package/payload/platform/plugins/connector/mcp/dist/index.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/call.d.ts +36 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/call.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/call.js +84 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/call.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/redact.d.ts +10 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/redact.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/redact.js +29 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/redact.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.d.ts +18 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.js +94 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/ssrf.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/store.d.ts +25 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/store.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/store.js +63 -0
- package/payload/platform/plugins/connector/mcp/dist/lib/store.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/scripts/audit-connectors.d.ts +9 -0
- package/payload/platform/plugins/connector/mcp/dist/scripts/audit-connectors.d.ts.map +1 -0
- package/payload/platform/plugins/connector/mcp/dist/scripts/audit-connectors.js +63 -0
- package/payload/platform/plugins/connector/mcp/dist/scripts/audit-connectors.js.map +1 -0
- package/payload/platform/plugins/connector/mcp/package.json +10 -0
- package/payload/platform/plugins/docs/references/connector.md +33 -0
- package/payload/platform/plugins/docs/references/getting-started.md +1 -1
- package/payload/platform/scripts/check-agent-contract.mjs +97 -0
- package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.d.ts.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.js +5 -0
- package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.js.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/http-server.d.ts +6 -0
- package/payload/platform/services/claude-session-manager/dist/http-server.d.ts.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/http-server.js +165 -88
- package/payload/platform/services/claude-session-manager/dist/http-server.js.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/index.js +8 -0
- package/payload/platform/services/claude-session-manager/dist/index.js.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/pty-spawner.d.ts +21 -14
- package/payload/platform/services/claude-session-manager/dist/pty-spawner.d.ts.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/pty-spawner.js +12 -37
- package/payload/platform/services/claude-session-manager/dist/pty-spawner.js.map +1 -1
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-mcp.d.ts +35 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-mcp.d.ts.map +1 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-mcp.js +52 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-mcp.js.map +1 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-store.d.ts +29 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-store.d.ts.map +1 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-store.js +121 -0
- package/payload/platform/services/claude-session-manager/dist/telegram-channel-store.js.map +1 -0
- package/payload/platform/services/telegram-channel/package.json +20 -0
- package/payload/platform/templates/agents/admin/IDENTITY.md +4 -0
- package/payload/platform/templates/specialists/agents/citation-auditor.md +5 -1
- package/payload/platform/templates/specialists/agents/coding-assistant.md +8 -0
- package/payload/platform/templates/specialists/agents/compiled-truth-rewriter.md +4 -0
- package/payload/platform/templates/specialists/agents/content-producer.md +8 -0
- package/payload/platform/templates/specialists/agents/data-manager.md +9 -1
- package/payload/platform/templates/specialists/agents/database-operator.md +12 -0
- package/payload/platform/templates/specialists/agents/librarian.md +9 -1
- package/payload/platform/templates/specialists/agents/personal-assistant.md +8 -0
- package/payload/platform/templates/specialists/agents/project-manager.md +8 -0
- package/payload/platform/templates/specialists/agents/public-session-reviewer.md +9 -1
- package/payload/platform/templates/specialists/agents/research-assistant.md +8 -0
- package/payload/platform/templates/specialists/agents/typed-edge-classifier.md +4 -2
- package/payload/premium-plugins/writer-craft/agents/writer-craft--manuscript-reviewer.md +12 -0
- package/payload/server/public/assets/{AdminLoginScreens-BEzoTk56.js → AdminLoginScreens-lt72mYrz.js} +1 -1
- package/payload/server/public/assets/AdminShell-B-GeoG3j.js +1 -0
- package/payload/server/public/assets/{Checkbox-CvTFOczj.js → Checkbox-DoGMXVpF.js} +1 -1
- package/payload/server/public/assets/{OperatorConversations-CnP9Y6g2.css → OperatorConversations-C8G6Gfgu.css} +1 -1
- package/payload/server/public/assets/{admin-Bhxa1HOy.js → admin-DzLxv-nz.js} +1 -1
- package/payload/server/public/assets/admin-types-DJoj6VJv.js +1 -0
- package/payload/server/public/assets/{browser-BAQFuyma.js → browser-Cyi6v8BS.js} +1 -1
- package/payload/server/public/assets/{calendar-sSr6zUjW.js → calendar-CA3_Dm8j.js} +1 -1
- package/payload/server/public/assets/chat-B9aNK1FG.js +1 -0
- package/payload/server/public/assets/{data-CBrgiyPM.js → data-CrJZjlQ1.js} +1 -1
- package/payload/server/public/assets/{graph-DbGjFYPS.js → graph-CutaO0w1.js} +2 -2
- package/payload/server/public/assets/{graph-labels-IGIEr-uc.js → graph-labels-CH0sWvcA.js} +1 -1
- package/payload/server/public/assets/{operator-Ba5afDyM.js → operator-MASl7IqX.js} +1 -1
- package/payload/server/public/assets/page-CZy33qUH.js +30 -0
- package/payload/server/public/assets/{public-DikYWzOd.js → public-77Ubicd7.js} +1 -1
- package/payload/server/public/browser.html +4 -4
- package/payload/server/public/calendar.html +4 -4
- package/payload/server/public/chat.html +6 -6
- package/payload/server/public/data.html +4 -4
- package/payload/server/public/graph.html +6 -6
- package/payload/server/public/index.html +7 -7
- package/payload/server/public/operator.html +8 -8
- package/payload/server/public/public.html +6 -6
- package/payload/server/server.js +4755 -4595
- package/payload/server/public/assets/AdminShell-BG7YD4UO.js +0 -1
- package/payload/server/public/assets/admin-types-Dg11L4MQ.js +0 -1
- package/payload/server/public/assets/chat-ZH4Fsyu0.js +0 -1
- package/payload/server/public/assets/page-D7uwMUOy.js +0 -30
- /package/payload/server/public/assets/{OperatorConversations-DU8CqO-z.js → OperatorConversations-CfG1EYyP.js} +0 -0
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
/**
|
|
4
|
+
* MCP spawn-tee — in-process stderr capture + lifecycle observability.
|
|
5
|
+
*
|
|
6
|
+
* Claude Code spawns each MCP server itself; the platform never holds a
|
|
7
|
+
* ChildProcess handle. This shim sits between Claude Code and the real MCP
|
|
8
|
+
* server: Claude Code runs `node <this> <real-entry>`, and the shim runs the
|
|
9
|
+
* real entry IN ITS OWN PROCESS via dynamic import() — one node runtime, not
|
|
10
|
+
* two. Before importing, it replaces process.stderr.write with a tee so every
|
|
11
|
+
* stderr byte the server writes is mirrored to the log sinks; stdin and stdout
|
|
12
|
+
* (the JSON-RPC channel) are never touched.
|
|
13
|
+
*
|
|
14
|
+
* Claude Code CLI → shim (this file) = node running <real-entry> in-process
|
|
15
|
+
* stdin/stdout : untouched (JSON-RPC channel)
|
|
16
|
+
* stderr : process.stderr.write teed → per-date + per-session + passthrough
|
|
17
|
+
*
|
|
18
|
+
* Destinations (Task 706) — unchanged:
|
|
19
|
+
* - `${LOG_DIR}/mcp-<name>-stderr-<date>.log` — per-date raw (back-compat;
|
|
20
|
+
* the in-process mcp-stderr-tee and the [mcp-init-error] probe read it).
|
|
21
|
+
* - `${LOG_DIR}/mcp-<name>-<SESSION_ID>.log` — per-session raw + lifecycle
|
|
22
|
+
* lines. Authoritative sink. Absent when SESSION_ID is unset (enumeration
|
|
23
|
+
* spawn) — then the per-date file is the fallback.
|
|
24
|
+
* - `server.log` via the loopback log-ingest route — best-effort mirror of
|
|
25
|
+
* the [mcp-helper] lifecycle lines.
|
|
26
|
+
*
|
|
27
|
+
* Lifecycle lines, correlation key `session=<id8> server=<name>` — unchanged:
|
|
28
|
+
* [mcp-helper] op=spawn ... pid= entry=
|
|
29
|
+
* [mcp-helper] op=boot ... head=<first stderr bytes>
|
|
30
|
+
* [mcp-helper] op=exit ... code= signal= lifetimeMs= stderr-tail=
|
|
31
|
+
*
|
|
32
|
+
* Process model (Task 989): the shim IS the server's process. op=exit fires
|
|
33
|
+
* from process.on("exit"), so it covers a normal exit, a non-zero exit, an
|
|
34
|
+
* uncaught throw (code 1), and a catchable-signal exit (SIGTERM/SIGINT/SIGHUP,
|
|
35
|
+
* whose handlers record the signal name). An external SIGKILL is uncatchable
|
|
36
|
+
* and leaves no op=exit line — the per-session stderr tail already on disk and
|
|
37
|
+
* Claude Code's own transport-drop are the evidence for that death mode.
|
|
38
|
+
*
|
|
39
|
+
* The shim never writes to fd 1 (stdout) — that is the JSON-RPC channel.
|
|
40
|
+
*/
|
|
41
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
+
const node_fs_1 = require("node:fs");
|
|
43
|
+
const node_path_1 = require("node:path");
|
|
44
|
+
const node_url_1 = require("node:url");
|
|
45
|
+
const SERVER_NAME = process.env.MCP_SPAWN_TEE_NAME ?? "unknown";
|
|
46
|
+
const LOG_DIR = process.env.LOG_DIR;
|
|
47
|
+
const SESSION_ID = process.env.SESSION_ID;
|
|
48
|
+
const PLATFORM_PORT = process.env.PLATFORM_PORT;
|
|
49
|
+
const ENTRY = process.argv[2];
|
|
50
|
+
const SESSION_ID8 = SESSION_ID ? SESSION_ID.slice(0, 8) : "—";
|
|
51
|
+
const spawnStamp = Date.now();
|
|
52
|
+
// Per-session raw + lifecycle log (Task 706). Empty SESSION_ID (enumeration
|
|
53
|
+
// spawn) → undefined, and the per-date file is the fallback.
|
|
54
|
+
const perSessionPath = LOG_DIR && SESSION_ID
|
|
55
|
+
? (0, node_path_1.resolve)(LOG_DIR, `mcp-${SERVER_NAME}-${SESSION_ID}.log`)
|
|
56
|
+
: undefined;
|
|
57
|
+
const perDatePath = LOG_DIR
|
|
58
|
+
? (0, node_path_1.resolve)(LOG_DIR, `mcp-${SERVER_NAME}-stderr-${new Date(spawnStamp).toISOString().slice(0, 10)}.log`)
|
|
59
|
+
: undefined;
|
|
60
|
+
// Rolling tail of entry stderr for op=exit. Capped so a chatty server cannot
|
|
61
|
+
// grow the buffer without bound.
|
|
62
|
+
const TAIL_CAP = 2048;
|
|
63
|
+
let stderrTail = "";
|
|
64
|
+
let bootEmitted = false;
|
|
65
|
+
let exitEmitted = false;
|
|
66
|
+
let exitSignal;
|
|
67
|
+
// The real stderr writer, captured before the tee replaces it. Lifecycle lines
|
|
68
|
+
// and stderr passthrough both go through this so they are never re-teed into
|
|
69
|
+
// the per-date sink nor recursed back into the patched writer.
|
|
70
|
+
const rawStderrWrite = process.stderr.write.bind(process.stderr);
|
|
71
|
+
// LOG_DIR is created once, lazily, on the first successful append — not per
|
|
72
|
+
// chunk. teeWrite runs on the server's own stderr hot path now, so a per-call
|
|
73
|
+
// mkdirSync would be two syscalls per log line for nothing.
|
|
74
|
+
let logDirReady = false;
|
|
75
|
+
function appendSafe(path, data) {
|
|
76
|
+
if (!path || !LOG_DIR)
|
|
77
|
+
return;
|
|
78
|
+
try {
|
|
79
|
+
if (!logDirReady) {
|
|
80
|
+
(0, node_fs_1.mkdirSync)(LOG_DIR, { recursive: true });
|
|
81
|
+
logDirReady = true;
|
|
82
|
+
}
|
|
83
|
+
(0, node_fs_1.appendFileSync)(path, data);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
/* unwritable destination — never mask primary output */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// Best-effort mirror of a lifecycle line to server.log via the loopback
|
|
90
|
+
// log-ingest route. Fire-and-forget: the per-session file is authoritative, so
|
|
91
|
+
// a dropped POST loses nothing. On the "exit" event the loop is stopping, so
|
|
92
|
+
// the op=exit mirror may not flush — the per-session line, written sync, holds.
|
|
93
|
+
function postToServerLog(suffix, level) {
|
|
94
|
+
if (!PLATFORM_PORT)
|
|
95
|
+
return;
|
|
96
|
+
try {
|
|
97
|
+
const ctrl = new AbortController();
|
|
98
|
+
const t = setTimeout(() => ctrl.abort(), 500);
|
|
99
|
+
t.unref?.(); // never let the abort timer keep the shim's event loop alive
|
|
100
|
+
void fetch(`http://127.0.0.1:${PLATFORM_PORT}/api/admin/log-ingest`, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: { "content-type": "application/json" },
|
|
103
|
+
body: JSON.stringify({ tag: "mcp-helper", level, line: suffix }),
|
|
104
|
+
signal: ctrl.signal,
|
|
105
|
+
}).then(() => clearTimeout(t)).catch(() => clearTimeout(t));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
/* fetch threw synchronously — best-effort only */
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
// Emit one [mcp-helper] lifecycle line: authoritative per-session file (sync,
|
|
112
|
+
// survives process.exit), the shim's own stderr via the RAW writer (journald /
|
|
113
|
+
// Claude Code visibility, never re-teed), and a best-effort server.log mirror.
|
|
114
|
+
// `suffix` is the line body after the tag and carries no newline (the
|
|
115
|
+
// log-ingest route rejects newlines).
|
|
116
|
+
function emitLifecycle(suffix, level) {
|
|
117
|
+
const line = `[mcp-helper] ${suffix}\n`;
|
|
118
|
+
appendSafe(perSessionPath, line);
|
|
119
|
+
try {
|
|
120
|
+
rawStderrWrite(line);
|
|
121
|
+
}
|
|
122
|
+
catch { /* stderr closed */ }
|
|
123
|
+
postToServerLog(suffix, level);
|
|
124
|
+
}
|
|
125
|
+
if (!ENTRY) {
|
|
126
|
+
emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason="no entry given (argv[2] missing)"`, "error");
|
|
127
|
+
process.exit(2);
|
|
128
|
+
}
|
|
129
|
+
// Replace process.stderr.write with a tee: mirror every server stderr byte to
|
|
130
|
+
// the per-date and per-session sinks, keep a rolling tail for op=exit, emit
|
|
131
|
+
// op=boot on the first bytes, then pass the write through to the real stderr.
|
|
132
|
+
const teeWrite = ((...args) => {
|
|
133
|
+
const chunk = args[0];
|
|
134
|
+
appendSafe(perDatePath, chunk); // per-date raw (back-compat)
|
|
135
|
+
appendSafe(perSessionPath, chunk); // per-session raw (Task 706)
|
|
136
|
+
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
|
|
137
|
+
stderrTail = (stderrTail + text).slice(-TAIL_CAP);
|
|
138
|
+
if (!bootEmitted) {
|
|
139
|
+
bootEmitted = true;
|
|
140
|
+
const head = text.split("\n")[0].slice(0, 200);
|
|
141
|
+
emitLifecycle(`op=boot session=${SESSION_ID8} server=${SERVER_NAME} head=${JSON.stringify(head)}`, "info");
|
|
142
|
+
}
|
|
143
|
+
return rawStderrWrite(...args); // passthrough
|
|
144
|
+
});
|
|
145
|
+
process.stderr.write = teeWrite;
|
|
146
|
+
// Catchable-signal handling. The shim drives the exit ONLY when it is the sole
|
|
147
|
+
// listener for the signal — i.e. the imported entry installed no handler of its
|
|
148
|
+
// own. In that case it records the signal (so op=exit carries signal=<sig>) and
|
|
149
|
+
// exits with 128+signum, mirroring the prior wrapper's exit-status convention.
|
|
150
|
+
//
|
|
151
|
+
// When the entry DID install a handler, the shim defers entirely and records
|
|
152
|
+
// nothing: the entry's handler decides the exit code, and op=exit reflects that
|
|
153
|
+
// exit verbatim. This matches the prior two-process model, where a child that
|
|
154
|
+
// caught the signal and exited cleanly was observed as code=0 signal=— (a clean
|
|
155
|
+
// self-exit), not as a signal death. Setting exitSignal here unconditionally
|
|
156
|
+
// would mislabel every graceful signal-driven shutdown as a signal kill.
|
|
157
|
+
function onSignal(sig, code) {
|
|
158
|
+
return () => {
|
|
159
|
+
if (process.listenerCount(sig) === 1) {
|
|
160
|
+
exitSignal = sig;
|
|
161
|
+
process.exit(code);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
process.on("SIGTERM", onSignal("SIGTERM", 143));
|
|
166
|
+
process.on("SIGINT", onSignal("SIGINT", 130));
|
|
167
|
+
process.on("SIGHUP", onSignal("SIGHUP", 129));
|
|
168
|
+
// op=exit, emitted once from the process "exit" event. Sync-only — the loop is
|
|
169
|
+
// stopping. When a catchable signal caused the exit, report code=— signal=<sig>
|
|
170
|
+
// to match the prior wrapper's format; otherwise code=<exit code> signal=—.
|
|
171
|
+
process.on("exit", (code) => {
|
|
172
|
+
if (exitEmitted)
|
|
173
|
+
return;
|
|
174
|
+
exitEmitted = true;
|
|
175
|
+
const lifetimeMs = Date.now() - spawnStamp;
|
|
176
|
+
const tail = stderrTail.slice(-200);
|
|
177
|
+
const codeField = exitSignal ? "—" : String(code);
|
|
178
|
+
const level = exitSignal || code !== 0 ? "error" : "info";
|
|
179
|
+
emitLifecycle(`op=exit session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} ` +
|
|
180
|
+
`code=${codeField} signal=${exitSignal ?? "—"} lifetimeMs=${lifetimeMs} stderr-tail=${JSON.stringify(tail)}`, level);
|
|
181
|
+
});
|
|
182
|
+
emitLifecycle(`op=spawn session=${SESSION_ID8} server=${SERVER_NAME} pid=${process.pid} entry=${ENTRY}`, "info");
|
|
183
|
+
// Run the real MCP server in THIS process. Dynamic import() (not top-level
|
|
184
|
+
// await — this file compiles to CommonJS) loads the ESM entry; a load-time
|
|
185
|
+
// failure mirrors the old child spawn-error path (op=error, exit 127). The
|
|
186
|
+
// op=exit handler is suppressed on this path so op=error stays the sole record.
|
|
187
|
+
import((0, node_url_1.pathToFileURL)(ENTRY).href).catch((err) => {
|
|
188
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
189
|
+
exitEmitted = true;
|
|
190
|
+
emitLifecycle(`op=error session=${SESSION_ID8} server=${SERVER_NAME} reason=${JSON.stringify(`import error: ${msg}`)}`, "error");
|
|
191
|
+
process.exit(127);
|
|
192
|
+
});
|
|
193
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { initStderrTee } from "../../../../lib/mcp-stderr-tee/dist/index.js";
|
|
2
|
+
initStderrTee("connector");
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { lifelineTool } from "../../../../lib/mcp-lifeline/dist/index.js";
|
|
7
|
+
import { readRegistry, listConnectors, registerConnector, deregisterConnector, resolveConnector, } from "./lib/store.js";
|
|
8
|
+
import { performCall } from "./lib/call.js";
|
|
9
|
+
import { hostResolvesPrivate } from "./lib/ssrf.js";
|
|
10
|
+
// Plugin-system boot tolerance: module init must never throw. tools/list is enumerated
|
|
11
|
+
// with empty env, so account context is resolved per call; all tools are registered
|
|
12
|
+
// unconditionally and each handler refuses per-call when context is absent.
|
|
13
|
+
const ACCOUNT_ID = process.env.ACCOUNT_ID ?? null;
|
|
14
|
+
const PLATFORM_ROOT = process.env.PLATFORM_ROOT ?? null;
|
|
15
|
+
function countRegistered() {
|
|
16
|
+
if (!ACCOUNT_ID || !PLATFORM_ROOT)
|
|
17
|
+
return "n/a";
|
|
18
|
+
try {
|
|
19
|
+
return Object.keys(readRegistry(PLATFORM_ROOT, ACCOUNT_ID)).length;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return "n/a";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
process.stderr.write(`[connector] op=init account=${ACCOUNT_ID ?? "null"} connectors=${countRegistered()}\n`);
|
|
26
|
+
let callSeq = 0;
|
|
27
|
+
const nextReqId = () => (++callSeq).toString(16).padStart(6, "0");
|
|
28
|
+
function ok(data) {
|
|
29
|
+
return {
|
|
30
|
+
content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data, null, 2) }],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function fail(msg) {
|
|
34
|
+
return { content: [{ type: "text", text: msg }], isError: true };
|
|
35
|
+
}
|
|
36
|
+
function refuseNoAccount(tool) {
|
|
37
|
+
process.stderr.write(`[connector] tool=${tool} refuse reason=no-account-context\n`);
|
|
38
|
+
return fail(`${tool} cannot execute: launched without ACCOUNT_ID/PLATFORM_ROOT (metadata-only mode).`);
|
|
39
|
+
}
|
|
40
|
+
function ctx(tool) {
|
|
41
|
+
if (!ACCOUNT_ID || !PLATFORM_ROOT)
|
|
42
|
+
return { refusal: refuseNoAccount(tool) };
|
|
43
|
+
return { platformRoot: PLATFORM_ROOT, accountId: ACCOUNT_ID };
|
|
44
|
+
}
|
|
45
|
+
const server = new McpServer({ name: "connector", version: "0.1.0" });
|
|
46
|
+
lifelineTool(server, "connector-register", "Register a named third-party REST API: store its base URL and a static credential so the agent can call it. auth.scheme is bearer | api-key-header | basic; headerName is required for api-key-header. The credential is stored in the account secrets file and is never returned or logged. Returns the non-secret record only.", {
|
|
47
|
+
name: z.string().min(1),
|
|
48
|
+
baseUrl: z.string().min(1),
|
|
49
|
+
auth: z.object({
|
|
50
|
+
scheme: z.enum(["bearer", "api-key-header", "basic"]),
|
|
51
|
+
value: z.string().min(1),
|
|
52
|
+
headerName: z.string().min(1).optional(),
|
|
53
|
+
}),
|
|
54
|
+
}, async ({ name, baseUrl, auth }) => {
|
|
55
|
+
const c = ctx("connector-register");
|
|
56
|
+
if ("refusal" in c)
|
|
57
|
+
return c.refusal;
|
|
58
|
+
let url;
|
|
59
|
+
try {
|
|
60
|
+
url = new URL(baseUrl);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return fail("connector-register: baseUrl is not a valid URL.");
|
|
64
|
+
}
|
|
65
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
66
|
+
return fail("connector-register: baseUrl must be http(s).");
|
|
67
|
+
if (auth.scheme === "api-key-header" && !auth.headerName)
|
|
68
|
+
return fail("connector-register: headerName is required for the api-key-header scheme.");
|
|
69
|
+
if (await hostResolvesPrivate(url.hostname)) {
|
|
70
|
+
process.stderr.write(`[connector] op=register-refused name=${name} reason=private-ip target=${url.hostname}\n`);
|
|
71
|
+
return fail("connector-register: refused — baseUrl host resolves to a private or loopback address.");
|
|
72
|
+
}
|
|
73
|
+
const rec = {
|
|
74
|
+
baseUrl,
|
|
75
|
+
host: url.hostname,
|
|
76
|
+
authScheme: auth.scheme,
|
|
77
|
+
...(auth.scheme === "api-key-header" ? { headerName: auth.headerName } : {}),
|
|
78
|
+
};
|
|
79
|
+
registerConnector(c.platformRoot, c.accountId, name, rec, auth.value);
|
|
80
|
+
process.stderr.write(`[connector] op=register name=${name} host=${url.hostname} scheme=${auth.scheme}\n`);
|
|
81
|
+
return ok({ name, baseUrl, host: url.hostname, authScheme: auth.scheme });
|
|
82
|
+
});
|
|
83
|
+
lifelineTool(server, "connector-call", "Make an authenticated request to a registered connector. The credential is injected from the secret store; the request is confined to the registered host (a different host, a private address, or a cross-host redirect is refused). Returns { status, headers (redacted), body (capped) }.", {
|
|
84
|
+
name: z.string().min(1),
|
|
85
|
+
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
|
|
86
|
+
path: z.string(),
|
|
87
|
+
query: z.record(z.string()).optional(),
|
|
88
|
+
body: z.unknown().optional(),
|
|
89
|
+
headers: z.record(z.string()).optional(),
|
|
90
|
+
}, async ({ name, method, path, query, body, headers }) => {
|
|
91
|
+
const c = ctx("connector-call");
|
|
92
|
+
if ("refusal" in c)
|
|
93
|
+
return c.refusal;
|
|
94
|
+
const resolved = resolveConnector(c.platformRoot, c.accountId, name);
|
|
95
|
+
if (!resolved)
|
|
96
|
+
return fail(`connector-call: no connector named '${name}' is registered.`);
|
|
97
|
+
const reqId = nextReqId();
|
|
98
|
+
const result = await performCall(resolved.rec, resolved.secret, { method, path, query, body, headers }, { log: (line) => process.stderr.write(`[connector] ${line}\n`), reqId });
|
|
99
|
+
if (!result.ok)
|
|
100
|
+
return fail(`connector-call refused: ${result.refused}.`);
|
|
101
|
+
return ok({ status: result.status, headers: result.headers, body: result.body, truncated: result.truncated });
|
|
102
|
+
});
|
|
103
|
+
lifelineTool(server, "connector-list", "List the registered connectors for this account (names and base URLs only — never credentials).", {}, async () => {
|
|
104
|
+
const c = ctx("connector-list");
|
|
105
|
+
if ("refusal" in c)
|
|
106
|
+
return c.refusal;
|
|
107
|
+
return ok(listConnectors(c.platformRoot, c.accountId));
|
|
108
|
+
});
|
|
109
|
+
lifelineTool(server, "connector-deregister", "Remove a registered connector and its stored credential. Idempotent: removing an unknown name is reported, not an error.", { name: z.string().min(1) }, async ({ name }) => {
|
|
110
|
+
const c = ctx("connector-deregister");
|
|
111
|
+
if ("refusal" in c)
|
|
112
|
+
return c.refusal;
|
|
113
|
+
const had = deregisterConnector(c.platformRoot, c.accountId, name);
|
|
114
|
+
process.stderr.write(`[connector] op=deregister name=${name} existed=${had}\n`);
|
|
115
|
+
return ok(had ? `Deregistered connector '${name}'.` : `No connector named '${name}' was registered.`);
|
|
116
|
+
});
|
|
117
|
+
const transport = new StdioServerTransport();
|
|
118
|
+
await server.connect(transport);
|
|
119
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,8CAA8C,CAAC;AAC7E,aAAa,CAAC,WAAW,CAAC,CAAC;AAE3B,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAC;AAC1E,OAAO,EACL,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,GAEjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,uFAAuF;AACvF,oFAAoF;AACpF,4EAA4E;AAC5E,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,IAAI,CAAC;AAClD,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,IA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;AAEF,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type Refusal } from "./ssrf.js";
|
|
2
|
+
import type { ConnectorRecord } from "./store.js";
|
|
3
|
+
export interface CallParams {
|
|
4
|
+
method: string;
|
|
5
|
+
path: string;
|
|
6
|
+
query?: Record<string, string>;
|
|
7
|
+
body?: unknown;
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
export interface CallDeps {
|
|
11
|
+
/** Override for tests; defaults to global fetch. */
|
|
12
|
+
fetchImpl?: typeof fetch;
|
|
13
|
+
/** Override for tests so a loopback stub is reachable; defaults to the real SSRF guard. */
|
|
14
|
+
guard?: (targetHost: string, registeredHost: string, kind: "request" | "redirect") => Promise<Refusal | null>;
|
|
15
|
+
/** Sink for `[connector]` lifecycle lines; the secret is never passed to it. */
|
|
16
|
+
log?: (line: string) => void;
|
|
17
|
+
reqId?: string;
|
|
18
|
+
}
|
|
19
|
+
export type CallResult = {
|
|
20
|
+
ok: true;
|
|
21
|
+
status: number;
|
|
22
|
+
headers: Record<string, string>;
|
|
23
|
+
body: string;
|
|
24
|
+
truncated: boolean;
|
|
25
|
+
} | {
|
|
26
|
+
ok: false;
|
|
27
|
+
refused: Refusal;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Make one authenticated, host-bound request to a registered connector. The guard runs
|
|
31
|
+
* before the request and before every redirect hop; the credential is injected from the
|
|
32
|
+
* caller-supplied secret and never logged. Returns status + redacted headers + capped body,
|
|
33
|
+
* or a refusal when the guard rejects the target.
|
|
34
|
+
*/
|
|
35
|
+
export declare function performCall(rec: ConnectorRecord, secret: string, params: CallParams, deps?: CallDeps): Promise<CallResult>;
|
|
36
|
+
//# sourceMappingURL=call.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"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OAAO,CAAC,UAAU,CAAC,CA6DrB"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { redactHeaders, scrubSecret } from "./redact.js";
|
|
2
|
+
import { guardTarget } from "./ssrf.js";
|
|
3
|
+
const BODY_CAP = 262144; // 256 KiB
|
|
4
|
+
const MAX_REDIRECTS = 5;
|
|
5
|
+
/** Inject the credential per scheme. Returns the scheme label for the auth-applied log line. */
|
|
6
|
+
function applyAuth(headers, rec, secret) {
|
|
7
|
+
if (rec.authScheme === "bearer")
|
|
8
|
+
headers["Authorization"] = `Bearer ${secret}`;
|
|
9
|
+
else if (rec.authScheme === "basic")
|
|
10
|
+
headers["Authorization"] = `Basic ${Buffer.from(secret).toString("base64")}`;
|
|
11
|
+
else
|
|
12
|
+
headers[rec.headerName] = secret; // api-key-header (headerName validated at register)
|
|
13
|
+
return rec.authScheme;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Make one authenticated, host-bound request to a registered connector. The guard runs
|
|
17
|
+
* before the request and before every redirect hop; the credential is injected from the
|
|
18
|
+
* caller-supplied secret and never logged. Returns status + redacted headers + capped body,
|
|
19
|
+
* or a refusal when the guard rejects the target.
|
|
20
|
+
*/
|
|
21
|
+
export async function performCall(rec, secret, params, deps = {}) {
|
|
22
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
23
|
+
const guard = deps.guard ?? guardTarget;
|
|
24
|
+
const log = deps.log ?? (() => { });
|
|
25
|
+
const reqId = deps.reqId ?? "—";
|
|
26
|
+
const url = new URL(params.path, rec.baseUrl);
|
|
27
|
+
// A caller-supplied path may carry userinfo (user:pass@host); strip it so the only credential
|
|
28
|
+
// sent is the one the connector injects, and so userinfo cannot smuggle alternate auth.
|
|
29
|
+
url.username = "";
|
|
30
|
+
url.password = "";
|
|
31
|
+
if (params.query)
|
|
32
|
+
for (const [k, v] of Object.entries(params.query))
|
|
33
|
+
url.searchParams.set(k, v);
|
|
34
|
+
log(`op=call reqId=${reqId} method=${params.method} host=${url.hostname} path=${url.pathname}`);
|
|
35
|
+
const reqRefusal = await guard(url.hostname, rec.host, "request");
|
|
36
|
+
if (reqRefusal) {
|
|
37
|
+
log(`op=call-refused reqId=${reqId} reason=${reqRefusal} target=${url.hostname}`);
|
|
38
|
+
return { ok: false, refused: reqRefusal };
|
|
39
|
+
}
|
|
40
|
+
// Caller headers may not set the auth header or Host — those are ours to control.
|
|
41
|
+
const headers = {};
|
|
42
|
+
if (params.headers) {
|
|
43
|
+
for (const [k, v] of Object.entries(params.headers)) {
|
|
44
|
+
const lk = k.toLowerCase();
|
|
45
|
+
if (lk === "authorization" || lk === "host")
|
|
46
|
+
continue;
|
|
47
|
+
if (rec.headerName && lk === rec.headerName.toLowerCase())
|
|
48
|
+
continue;
|
|
49
|
+
headers[k] = v;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let bodyStr;
|
|
53
|
+
if (params.body !== undefined) {
|
|
54
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type"))
|
|
55
|
+
headers["Content-Type"] = "application/json";
|
|
56
|
+
bodyStr = typeof params.body === "string" ? params.body : JSON.stringify(params.body);
|
|
57
|
+
}
|
|
58
|
+
const scheme = applyAuth(headers, rec, secret);
|
|
59
|
+
log(`op=auth-applied reqId=${reqId} scheme=${scheme === "api-key-header" ? "api-key" : scheme}`);
|
|
60
|
+
const start = Date.now();
|
|
61
|
+
let current = url;
|
|
62
|
+
let hops = 0;
|
|
63
|
+
let res;
|
|
64
|
+
for (;;) {
|
|
65
|
+
res = await fetchImpl(current.toString(), { method: params.method, headers, body: bodyStr, redirect: "manual" });
|
|
66
|
+
const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
|
|
67
|
+
if (!location || hops++ >= MAX_REDIRECTS)
|
|
68
|
+
break;
|
|
69
|
+
const next = new URL(location, current);
|
|
70
|
+
const redirectRefusal = await guard(next.hostname, rec.host, "redirect");
|
|
71
|
+
if (redirectRefusal) {
|
|
72
|
+
log(`op=call-refused reqId=${reqId} reason=${redirectRefusal} target=${next.hostname}`);
|
|
73
|
+
return { ok: false, refused: redirectRefusal };
|
|
74
|
+
}
|
|
75
|
+
current = next;
|
|
76
|
+
}
|
|
77
|
+
const raw = await res.text();
|
|
78
|
+
const truncated = raw.length > BODY_CAP;
|
|
79
|
+
// Scrub the credential from the body in case the upstream reflects it (debug/echo endpoints).
|
|
80
|
+
const body = scrubSecret(truncated ? raw.slice(0, BODY_CAP) : raw, secret);
|
|
81
|
+
log(`op=response reqId=${reqId} status=${res.status} bytes=${raw.length} ms=${Date.now() - start}`);
|
|
82
|
+
return { ok: true, status: res.status, headers: redactHeaders(res.headers, rec.headerName, secret), body, truncated };
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=call.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/lib/call.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,WAAW,EAAgB,MAAM,WAAW,CAAC;AAyBtD,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,UAAU;AACnC,MAAM,aAAa,GAAG,CAAC,CAAC;AAExB,gGAAgG;AAChG,SAAS,SAAS,CAAC,OAA+B,EAAE,GAAoB,EAAE,MAAc;IACtF,IAAI,GAAG,CAAC,UAAU,KAAK,QAAQ;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,EAAE,CAAC;SAC1E,IAAI,GAAG,CAAC,UAAU,KAAK,OAAO;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;;QAC7G,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAC,GAAG,MAAM,CAAC,CAAC,oDAAoD;IACrG,OAAO,GAAG,CAAC,UAAU,CAAC;AACxB,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GAAG,EAAE,MAAM,CAAC,CAAC;IAC3E,GAAG,CAAC,qBAAqB,KAAK,WAAW,GAAG,CAAC,MAAM,UAAU,GAAG,CAAC,MAAM,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;IACpG,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AACxH,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Replace every occurrence of a credential (raw and base64 forms) with a marker. */
|
|
2
|
+
export declare function scrubSecret(text: string, secret: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Copy response headers into a plain object, masking the auth-bearing ones so a returned
|
|
5
|
+
* response never re-exposes a credential or session token. The connector's own api-key header
|
|
6
|
+
* (if any) is masked alongside Authorization and Set-Cookie, and the known secret value is
|
|
7
|
+
* scrubbed from every remaining header value in case the upstream reflects it.
|
|
8
|
+
*/
|
|
9
|
+
export declare function redactHeaders(headers: Headers, apiKeyHeader?: string, secret?: string): Record<string, string>;
|
|
10
|
+
//# sourceMappingURL=redact.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../src/lib/redact.ts"],"names":[],"mappings":"AAGA,qFAAqF;AACrF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ9G"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Header names always redacted from a returned response (case-insensitive). */
|
|
2
|
+
const ALWAYS_DROP = ["authorization", "set-cookie"];
|
|
3
|
+
/** Replace every occurrence of a credential (raw and base64 forms) with a marker. */
|
|
4
|
+
export function scrubSecret(text, secret) {
|
|
5
|
+
if (!secret)
|
|
6
|
+
return text;
|
|
7
|
+
let out = text.split(secret).join("<redacted>");
|
|
8
|
+
const b64 = Buffer.from(secret).toString("base64");
|
|
9
|
+
if (b64)
|
|
10
|
+
out = out.split(b64).join("<redacted>");
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Copy response headers into a plain object, masking the auth-bearing ones so a returned
|
|
15
|
+
* response never re-exposes a credential or session token. The connector's own api-key header
|
|
16
|
+
* (if any) is masked alongside Authorization and Set-Cookie, and the known secret value is
|
|
17
|
+
* scrubbed from every remaining header value in case the upstream reflects it.
|
|
18
|
+
*/
|
|
19
|
+
export function redactHeaders(headers, apiKeyHeader, secret) {
|
|
20
|
+
const drop = new Set(ALWAYS_DROP);
|
|
21
|
+
if (apiKeyHeader)
|
|
22
|
+
drop.add(apiKeyHeader.toLowerCase());
|
|
23
|
+
const out = {};
|
|
24
|
+
headers.forEach((value, key) => {
|
|
25
|
+
out[key] = drop.has(key.toLowerCase()) ? "<redacted>" : secret ? scrubSecret(value, secret) : value;
|
|
26
|
+
});
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=redact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact.js","sourceRoot":"","sources":["../../src/lib/redact.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,MAAM,WAAW,GAAG,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;AAEpD,qFAAqF;AACrF,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,MAAc;IACtD,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAChD,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACnD,IAAI,GAAG;QAAE,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACjD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,OAAgB,EAAE,YAAqB,EAAE,MAAe;IACpF,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IAClC,IAAI,YAAY;QAAE,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACvD,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QAC7B,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACtG,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** True for any loopback, private, link-local, or unique-local address (v4 or v6). */
|
|
2
|
+
export declare function isPrivateIp(ip: string): boolean;
|
|
3
|
+
/**
|
|
4
|
+
* Resolve a host and judge whether any of its addresses is private. IP literals (incl.
|
|
5
|
+
* bracketed IPv6) skip DNS. Fails closed: an unresolvable or lookup-erroring host is treated
|
|
6
|
+
* as unsafe (returns true), so the caller refuses rather than throwing.
|
|
7
|
+
*/
|
|
8
|
+
export declare function hostResolvesPrivate(host: string): Promise<boolean>;
|
|
9
|
+
export type Refusal = "host-mismatch" | "private-ip" | "redirect-escape";
|
|
10
|
+
/**
|
|
11
|
+
* Confirm a request/redirect target is the registered host and not a private address.
|
|
12
|
+
* Returns a refusal reason, or null when the target is allowed. Hosts are normalised
|
|
13
|
+
* (lowercased, brackets and a trailing FQDN dot stripped) before comparison. `kind`
|
|
14
|
+
* distinguishes the mismatch label: an off-host initial request is "host-mismatch", an
|
|
15
|
+
* off-host redirect is "redirect-escape".
|
|
16
|
+
*/
|
|
17
|
+
export declare function guardTarget(targetHost: string, registeredHost: string, kind: "request" | "redirect"): Promise<Refusal | null>;
|
|
18
|
+
//# sourceMappingURL=ssrf.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssrf.d.ts","sourceRoot":"","sources":["../../src/lib/ssrf.ts"],"names":[],"mappings":"AAwBA,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAqB/C;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAWxE;AAED,MAAM,MAAM,OAAO,GAAG,eAAe,GAAG,YAAY,GAAG,iBAAiB,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAsB,WAAW,CAC/B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,SAAS,GAAG,UAAU,GAC3B,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAMzB"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { lookup } from "node:dns/promises";
|
|
2
|
+
import { isIP } from "node:net";
|
|
3
|
+
/** Strip the `[ ]` that URL.hostname keeps around an IPv6 literal, and a trailing FQDN dot. */
|
|
4
|
+
function normalizeHost(host) {
|
|
5
|
+
let s = host.toLowerCase();
|
|
6
|
+
if (s.startsWith("[") && s.endsWith("]"))
|
|
7
|
+
s = s.slice(1, -1);
|
|
8
|
+
if (s.endsWith("."))
|
|
9
|
+
s = s.slice(0, -1);
|
|
10
|
+
return s;
|
|
11
|
+
}
|
|
12
|
+
/** True for an IPv4 address in any loopback/private/link-local/CGNAT/"this-host" range. */
|
|
13
|
+
function v4Private(ip) {
|
|
14
|
+
const o = ip.split(".").map((s) => Number(s));
|
|
15
|
+
if (o.length !== 4 || o.some((n) => Number.isNaN(n) || n < 0 || n > 255))
|
|
16
|
+
return false;
|
|
17
|
+
const [a, b] = o;
|
|
18
|
+
if (a === 10 || a === 127 || a === 0)
|
|
19
|
+
return true; // private, loopback, "this host"
|
|
20
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
21
|
+
return true; // private
|
|
22
|
+
if (a === 192 && b === 168)
|
|
23
|
+
return true; // private
|
|
24
|
+
if (a === 169 && b === 254)
|
|
25
|
+
return true; // link-local
|
|
26
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
27
|
+
return true; // CGNAT (100.64/10)
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
/** True for any loopback, private, link-local, or unique-local address (v4 or v6). */
|
|
31
|
+
export function isPrivateIp(ip) {
|
|
32
|
+
const bare = normalizeHost(ip);
|
|
33
|
+
const fam = isIP(bare);
|
|
34
|
+
if (fam === 4)
|
|
35
|
+
return v4Private(bare);
|
|
36
|
+
if (fam === 6) {
|
|
37
|
+
const lower = bare;
|
|
38
|
+
if (lower === "::1" || lower === "::")
|
|
39
|
+
return true; // loopback, unspecified
|
|
40
|
+
const dotted = lower.match(/::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); // IPv4-mapped, dotted
|
|
41
|
+
if (dotted)
|
|
42
|
+
return v4Private(dotted[1]);
|
|
43
|
+
const hex = lower.match(/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/); // IPv4-mapped, hex
|
|
44
|
+
if (hex) {
|
|
45
|
+
const hi = parseInt(hex[1], 16);
|
|
46
|
+
const lo = parseInt(hex[2], 16);
|
|
47
|
+
return v4Private(`${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`);
|
|
48
|
+
}
|
|
49
|
+
if (lower.startsWith("fc") || lower.startsWith("fd"))
|
|
50
|
+
return true; // fc00::/7 ULA
|
|
51
|
+
// fe80::/10 link-local spans fe80–febf, i.e. fe8/fe9/fea/feb prefixes.
|
|
52
|
+
if (/^fe[89ab]/.test(lower))
|
|
53
|
+
return true;
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolve a host and judge whether any of its addresses is private. IP literals (incl.
|
|
60
|
+
* bracketed IPv6) skip DNS. Fails closed: an unresolvable or lookup-erroring host is treated
|
|
61
|
+
* as unsafe (returns true), so the caller refuses rather than throwing.
|
|
62
|
+
*/
|
|
63
|
+
export async function hostResolvesPrivate(host) {
|
|
64
|
+
const bare = normalizeHost(host);
|
|
65
|
+
if (!bare)
|
|
66
|
+
return true; // empty/malformed host can never be a safe public target
|
|
67
|
+
if (isIP(bare))
|
|
68
|
+
return isPrivateIp(bare);
|
|
69
|
+
try {
|
|
70
|
+
const addrs = await lookup(bare, { all: true });
|
|
71
|
+
if (addrs.length === 0)
|
|
72
|
+
return true;
|
|
73
|
+
return addrs.some((a) => isPrivateIp(a.address));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return true; // DNS failure → fail closed
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Confirm a request/redirect target is the registered host and not a private address.
|
|
81
|
+
* Returns a refusal reason, or null when the target is allowed. Hosts are normalised
|
|
82
|
+
* (lowercased, brackets and a trailing FQDN dot stripped) before comparison. `kind`
|
|
83
|
+
* distinguishes the mismatch label: an off-host initial request is "host-mismatch", an
|
|
84
|
+
* off-host redirect is "redirect-escape".
|
|
85
|
+
*/
|
|
86
|
+
export async function guardTarget(targetHost, registeredHost, kind) {
|
|
87
|
+
if (normalizeHost(targetHost) !== normalizeHost(registeredHost)) {
|
|
88
|
+
return kind === "redirect" ? "redirect-escape" : "host-mismatch";
|
|
89
|
+
}
|
|
90
|
+
if (await hostResolvesPrivate(targetHost))
|
|
91
|
+
return "private-ip";
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=ssrf.js.map
|