surfcad-mcp 0.2.0 → 0.2.1
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 +34 -3
- package/data/commands.json +1404 -171
- package/package.json +1 -1
- package/src/bridge/bridgePage.mjs +132 -0
- package/src/bridge/bridgePopup.mjs +261 -0
- package/src/bridge/localAddress.mjs +1 -1
- package/src/bridge/relayHub.mjs +229 -33
- package/src/bridge/relayServer.mjs +56 -11
- package/src/errors.mjs +24 -1
- package/src/nodeClient.mjs +27 -6
- package/src/relay.mjs +267 -59
- package/src/server.mjs +77 -16
package/package.json
CHANGED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP responses for the loopback popup bridge (`/bridge`, `/bridge.js`).
|
|
3
|
+
* See `bridgePopup.mjs` for the browser side.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
|
|
8
|
+
export const BRIDGE_PAGE_PATH = '/bridge';
|
|
9
|
+
export const BRIDGE_SCRIPT_PATH = '/bridge.js';
|
|
10
|
+
|
|
11
|
+
let cachedScript = null;
|
|
12
|
+
|
|
13
|
+
function bridgeScriptSource() {
|
|
14
|
+
if (cachedScript == null) {
|
|
15
|
+
cachedScript = readFileSync(new URL('./bridgePopup.mjs', import.meta.url), 'utf8');
|
|
16
|
+
}
|
|
17
|
+
return cachedScript;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function escapeHtmlAttr(value) {
|
|
21
|
+
return String(value)
|
|
22
|
+
.replace(/&/g, '&')
|
|
23
|
+
.replace(/"/g, '"')
|
|
24
|
+
.replace(/</g, '<')
|
|
25
|
+
.replace(/>/g, '>');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The page must stay a top-level window: it cannot be framed, it does not
|
|
30
|
+
* isolate its opener (COOP would null `window.opener`), and it sends no
|
|
31
|
+
* Referer back out.
|
|
32
|
+
*
|
|
33
|
+
* @param {number} port
|
|
34
|
+
*/
|
|
35
|
+
export function bridgeSecurityHeaders(port) {
|
|
36
|
+
return {
|
|
37
|
+
'Content-Security-Policy': [
|
|
38
|
+
"default-src 'none'",
|
|
39
|
+
"script-src 'self'",
|
|
40
|
+
"style-src 'unsafe-inline'",
|
|
41
|
+
`connect-src ws://127.0.0.1:${port} ws://localhost:${port}`,
|
|
42
|
+
"base-uri 'none'",
|
|
43
|
+
"form-action 'none'",
|
|
44
|
+
"frame-ancestors 'none'",
|
|
45
|
+
].join('; '),
|
|
46
|
+
'X-Frame-Options': 'DENY',
|
|
47
|
+
'X-Content-Type-Options': 'nosniff',
|
|
48
|
+
'Referrer-Policy': 'no-referrer',
|
|
49
|
+
'Cross-Origin-Opener-Policy': 'unsafe-none',
|
|
50
|
+
'Cache-Control': 'no-store',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* DNS-rebinding guard: only answer for the loopback host names the
|
|
56
|
+
* SurfCAD tab actually opens.
|
|
57
|
+
*
|
|
58
|
+
* @param {string | undefined} hostHeader
|
|
59
|
+
* @param {number} port
|
|
60
|
+
*/
|
|
61
|
+
export function isBridgeHostAllowed(hostHeader, port) {
|
|
62
|
+
if (typeof hostHeader !== 'string') return false;
|
|
63
|
+
const host = hostHeader.trim().toLowerCase();
|
|
64
|
+
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {{ extraOrigins?: string[] }} [opts]
|
|
69
|
+
*/
|
|
70
|
+
export function bridgePageHtml(opts = {}) {
|
|
71
|
+
const extra = escapeHtmlAttr(JSON.stringify(opts.extraOrigins || []));
|
|
72
|
+
return `<!doctype html>
|
|
73
|
+
<html lang="en" data-surfcad-bridge="1" data-extra-origins="${extra}">
|
|
74
|
+
<head>
|
|
75
|
+
<meta charset="utf-8">
|
|
76
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
77
|
+
<title>SurfCAD local agent bridge</title>
|
|
78
|
+
<style>
|
|
79
|
+
:root { color-scheme: dark; }
|
|
80
|
+
body { margin: 0; font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #15171a; color: #e6e8eb; }
|
|
81
|
+
main { padding: 20px 22px; max-width: 420px; }
|
|
82
|
+
h1 { font-size: 16px; margin: 0 0 8px; }
|
|
83
|
+
p { margin: 0 0 10px; color: #b3b8bf; }
|
|
84
|
+
#bridge-status { color: #e6e8eb; padding: 8px 10px; border: 1px solid #2c3036; border-radius: 6px; background: #1c1f23; }
|
|
85
|
+
html[data-status="connected"] #bridge-status { border-color: #1f6f4a; color: #7ee2b0; }
|
|
86
|
+
html[data-status="forbidden"] #bridge-status, html[data-status="invalid"] #bridge-status { border-color: #7a2d2d; color: #f2a7a7; }
|
|
87
|
+
</style>
|
|
88
|
+
</head>
|
|
89
|
+
<body>
|
|
90
|
+
<main>
|
|
91
|
+
<h1>SurfCAD local agent bridge</h1>
|
|
92
|
+
<p>This window connects your SurfCAD tab to the local agent running on this computer (<code>npx surfcad-mcp</code>).</p>
|
|
93
|
+
<p><strong>Keep it open</strong> while the agent works. Closing it disconnects the agent.</p>
|
|
94
|
+
<p id="bridge-status" role="status" aria-live="polite">Starting…</p>
|
|
95
|
+
</main>
|
|
96
|
+
<script type="module" src="${BRIDGE_SCRIPT_PATH}"></script>
|
|
97
|
+
</body>
|
|
98
|
+
</html>
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* @param {import('node:http').IncomingMessage} req
|
|
104
|
+
* @param {import('node:http').ServerResponse} res
|
|
105
|
+
* @param {{ port: number, extraOrigins?: string[] }} opts
|
|
106
|
+
* @returns {boolean} true when the request was a bridge route and has been answered
|
|
107
|
+
*/
|
|
108
|
+
export function handleBridgeRequest(req, res, opts) {
|
|
109
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
|
|
110
|
+
let pathname;
|
|
111
|
+
try {
|
|
112
|
+
pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
if (pathname !== BRIDGE_PAGE_PATH && pathname !== BRIDGE_SCRIPT_PATH) return false;
|
|
117
|
+
|
|
118
|
+
if (!isBridgeHostAllowed(req.headers.host, opts.port)) {
|
|
119
|
+
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
120
|
+
res.end('Host not allowed\n');
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const isPage = pathname === BRIDGE_PAGE_PATH;
|
|
125
|
+
const body = isPage ? bridgePageHtml({ extraOrigins: opts.extraOrigins }) : bridgeScriptSource();
|
|
126
|
+
res.writeHead(200, {
|
|
127
|
+
...bridgeSecurityHeaders(opts.port),
|
|
128
|
+
'Content-Type': isPage ? 'text/html; charset=utf-8' : 'text/javascript; charset=utf-8',
|
|
129
|
+
});
|
|
130
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loopback popup bridge (browser side). The relay serves this file at
|
|
3
|
+
* `/bridge.js` for the page at `http://127.0.0.1:<port>/bridge`.
|
|
4
|
+
*
|
|
5
|
+
* Safari blocks `ws://127.0.0.1` from https://surfcad.com as mixed content.
|
|
6
|
+
* A top-level page on the relay's own origin can open that socket, so the
|
|
7
|
+
* SurfCAD tab opens this page as a popup and the two exchange frames with
|
|
8
|
+
* postMessage. Nothing here touches the socket until the opener proves it is
|
|
9
|
+
* an allowlisted SurfCAD origin holding the session nonce.
|
|
10
|
+
*
|
|
11
|
+
* Must stay dependency-free: it runs in the browser and is imported by tests.
|
|
12
|
+
* Kept in sync with `src/agent/ws/bridgeMessages.js`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const BRIDGE_CHANNEL = 'surfcad-agent-bridge';
|
|
16
|
+
|
|
17
|
+
export const BRIDGE_MSG = Object.freeze({
|
|
18
|
+
/** popup → opener: page loaded, waiting for hello */
|
|
19
|
+
READY: 'bridge_ready',
|
|
20
|
+
/** opener → popup: open the relay socket */
|
|
21
|
+
HELLO: 'bridge_hello',
|
|
22
|
+
/** popup → opener: relay socket is open */
|
|
23
|
+
OPEN: 'bridge_open',
|
|
24
|
+
/** both ways: one relay frame (string) */
|
|
25
|
+
FRAME: 'bridge_frame',
|
|
26
|
+
/** both ways: socket closed / please close it */
|
|
27
|
+
CLOSE: 'bridge_close',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export const BRIDGE_NONCE_RE = /^[A-Za-z0-9_-]{22,128}$/;
|
|
31
|
+
|
|
32
|
+
const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
33
|
+
const PROD_SURFCAD_HOSTS = new Set(['surfcad.com', 'www.surfcad.com']);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Same rule as the relay's `isAllowedHttpOrigin`, but an opener must always
|
|
37
|
+
* present an origin, and it must be a bare origin (no path, query or `null`).
|
|
38
|
+
*
|
|
39
|
+
* @param {unknown} origin
|
|
40
|
+
* @param {Iterable<string>} [extraOrigins]
|
|
41
|
+
*/
|
|
42
|
+
export function isAllowedOpenerOrigin(origin, extraOrigins = []) {
|
|
43
|
+
if (typeof origin !== 'string' || !origin) return false;
|
|
44
|
+
let url;
|
|
45
|
+
try {
|
|
46
|
+
url = new URL(origin);
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
if (url.origin !== origin) return false;
|
|
51
|
+
for (const extra of extraOrigins) {
|
|
52
|
+
if (extra === origin) return true;
|
|
53
|
+
}
|
|
54
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
55
|
+
if (LOCAL_HOSTNAMES.has(url.hostname) || url.hostname.startsWith('127.')) return true;
|
|
56
|
+
return PROD_SURFCAD_HOSTS.has(url.hostname);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {string} hash `location.hash`, with or without `#`
|
|
61
|
+
* @returns {{ nonce: string, origin: string } | null}
|
|
62
|
+
*/
|
|
63
|
+
export function parseBridgeFragment(hash) {
|
|
64
|
+
const raw = typeof hash === 'string' ? hash.replace(/^#/, '') : '';
|
|
65
|
+
const params = new URLSearchParams(raw);
|
|
66
|
+
const nonce = params.get('nonce') || '';
|
|
67
|
+
const origin = params.get('origin') || '';
|
|
68
|
+
if (!BRIDGE_NONCE_RE.test(nonce) || !origin) return null;
|
|
69
|
+
return { nonce, origin };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {{ nonce: string, origin: string }} session */
|
|
73
|
+
export function formatBridgeFragment({ nonce, origin }) {
|
|
74
|
+
return `nonce=${encodeURIComponent(nonce)}&origin=${encodeURIComponent(origin)}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @typedef {'invalid' | 'forbidden' | 'no_opener' | 'waiting' | 'connecting' | 'connected' | 'closed' | 'opener_gone'} PopupBridgeStatus
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {{
|
|
83
|
+
* win: Window,
|
|
84
|
+
* WebSocketCtor?: typeof WebSocket,
|
|
85
|
+
* wsUrl?: string,
|
|
86
|
+
* extraOrigins?: string[],
|
|
87
|
+
* onStatus?: (status: PopupBridgeStatus) => void,
|
|
88
|
+
* readyIntervalMs?: number,
|
|
89
|
+
* readyAttempts?: number,
|
|
90
|
+
* openerPollMs?: number,
|
|
91
|
+
* }} opts
|
|
92
|
+
*/
|
|
93
|
+
export function startPopupBridge(opts) {
|
|
94
|
+
const win = opts.win;
|
|
95
|
+
const WebSocketCtor = opts.WebSocketCtor || win.WebSocket;
|
|
96
|
+
const wsUrl = opts.wsUrl || `ws://${win.location.host}`;
|
|
97
|
+
const extraOrigins = opts.extraOrigins || [];
|
|
98
|
+
const onStatus = opts.onStatus || (() => {});
|
|
99
|
+
const readyIntervalMs = opts.readyIntervalMs ?? 200;
|
|
100
|
+
const readyAttempts = opts.readyAttempts ?? 50;
|
|
101
|
+
const openerPollMs = opts.openerPollMs ?? 1000;
|
|
102
|
+
|
|
103
|
+
const session = parseBridgeFragment(win.location.hash);
|
|
104
|
+
try {
|
|
105
|
+
win.history?.replaceState?.(null, '', `${win.location.pathname}${win.location.search}`);
|
|
106
|
+
} catch { /* fragment stays; harmless */ }
|
|
107
|
+
|
|
108
|
+
/** @type {{ stop: () => void, status: () => PopupBridgeStatus }} */
|
|
109
|
+
const inert = (status) => {
|
|
110
|
+
onStatus(status);
|
|
111
|
+
return { stop() {}, status: () => status };
|
|
112
|
+
};
|
|
113
|
+
if (!session) return inert('invalid');
|
|
114
|
+
if (!isAllowedOpenerOrigin(session.origin, extraOrigins)) return inert('forbidden');
|
|
115
|
+
const opener = win.opener;
|
|
116
|
+
if (!opener) return inert('no_opener');
|
|
117
|
+
|
|
118
|
+
const { nonce, origin } = session;
|
|
119
|
+
/** @type {WebSocket | null} */
|
|
120
|
+
let ws = null;
|
|
121
|
+
/** @type {PopupBridgeStatus} */
|
|
122
|
+
let status = 'waiting';
|
|
123
|
+
let stopped = false;
|
|
124
|
+
let readyTimer = null;
|
|
125
|
+
let openerTimer = null;
|
|
126
|
+
|
|
127
|
+
function setStatus(next) {
|
|
128
|
+
status = next;
|
|
129
|
+
onStatus(next);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function post(payload) {
|
|
133
|
+
try {
|
|
134
|
+
// targetOrigin pins delivery: an opener on any other origin never sees this.
|
|
135
|
+
opener.postMessage({ channel: BRIDGE_CHANNEL, nonce, ...payload }, origin);
|
|
136
|
+
} catch { /* opener gone */ }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function clearReady() {
|
|
140
|
+
if (readyTimer != null) win.clearInterval(readyTimer);
|
|
141
|
+
readyTimer = null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function closeSocket() {
|
|
145
|
+
if (!ws) return;
|
|
146
|
+
const s = ws;
|
|
147
|
+
ws = null;
|
|
148
|
+
try { s.close(); } catch { /* noop */ }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function openSocket() {
|
|
152
|
+
if (ws || stopped) return;
|
|
153
|
+
clearReady();
|
|
154
|
+
setStatus('connecting');
|
|
155
|
+
const socket = new WebSocketCtor(wsUrl);
|
|
156
|
+
ws = socket;
|
|
157
|
+
socket.addEventListener('open', () => {
|
|
158
|
+
if (ws !== socket) return;
|
|
159
|
+
setStatus('connected');
|
|
160
|
+
post({ type: BRIDGE_MSG.OPEN });
|
|
161
|
+
});
|
|
162
|
+
socket.addEventListener('message', (event) => {
|
|
163
|
+
if (ws !== socket) return;
|
|
164
|
+
post({ type: BRIDGE_MSG.FRAME, data: String(event.data) });
|
|
165
|
+
});
|
|
166
|
+
socket.addEventListener('close', (event) => {
|
|
167
|
+
if (ws !== socket) return;
|
|
168
|
+
ws = null;
|
|
169
|
+
post({ type: BRIDGE_MSG.CLOSE, code: event?.code ?? 1006, reason: event?.reason || '' });
|
|
170
|
+
if (!stopped) setStatus('closed');
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function onMessage(event) {
|
|
175
|
+
if (event.source !== opener || event.origin !== origin) return;
|
|
176
|
+
const msg = event.data;
|
|
177
|
+
if (!msg || typeof msg !== 'object' || msg.channel !== BRIDGE_CHANNEL || msg.nonce !== nonce) return;
|
|
178
|
+
if (msg.type === BRIDGE_MSG.HELLO) {
|
|
179
|
+
openSocket();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (msg.type === BRIDGE_MSG.FRAME) {
|
|
183
|
+
if (ws && ws.readyState === 1 && typeof msg.data === 'string') ws.send(msg.data);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (msg.type === BRIDGE_MSG.CLOSE) {
|
|
187
|
+
closeSocket();
|
|
188
|
+
post({ type: BRIDGE_MSG.CLOSE, code: 1000, reason: 'opener_close' });
|
|
189
|
+
setStatus('closed');
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function stop(nextStatus = 'closed') {
|
|
194
|
+
if (stopped) return;
|
|
195
|
+
stopped = true;
|
|
196
|
+
clearReady();
|
|
197
|
+
if (openerTimer != null) win.clearInterval(openerTimer);
|
|
198
|
+
win.removeEventListener('message', onMessage);
|
|
199
|
+
closeSocket();
|
|
200
|
+
setStatus(nextStatus);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
win.addEventListener('message', onMessage);
|
|
204
|
+
win.addEventListener('pagehide', () => stop('closed'));
|
|
205
|
+
setStatus('waiting');
|
|
206
|
+
|
|
207
|
+
let attempts = 0;
|
|
208
|
+
post({ type: BRIDGE_MSG.READY });
|
|
209
|
+
readyTimer = win.setInterval(() => {
|
|
210
|
+
attempts += 1;
|
|
211
|
+
if (ws || attempts >= readyAttempts) {
|
|
212
|
+
clearReady();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
post({ type: BRIDGE_MSG.READY });
|
|
216
|
+
}, readyIntervalMs);
|
|
217
|
+
|
|
218
|
+
openerTimer = win.setInterval(() => {
|
|
219
|
+
if (!opener || opener.closed) stop('opener_gone');
|
|
220
|
+
}, openerPollMs);
|
|
221
|
+
|
|
222
|
+
return { stop, status: () => status };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const STATUS_TEXT = {
|
|
226
|
+
invalid: 'This window only works when SurfCAD opens it. Close it and use the Local agent panel in SurfCAD.',
|
|
227
|
+
forbidden: 'This window was not opened by SurfCAD, so it will not connect. Close it.',
|
|
228
|
+
no_opener: 'This window lost its link to the SurfCAD tab. Close it, then click Reconnect in SurfCAD.',
|
|
229
|
+
waiting: 'Connecting to the SurfCAD tab…',
|
|
230
|
+
connecting: 'Connecting to the local agent…',
|
|
231
|
+
connected: 'Connected. Keep this window open while your agent works in SurfCAD.',
|
|
232
|
+
closed: 'The local agent disconnected. Keep this window open — SurfCAD will reconnect.',
|
|
233
|
+
opener_gone: 'The SurfCAD tab was closed. You can close this window.',
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/** @param {PopupBridgeStatus} status */
|
|
237
|
+
export function popupBridgeStatusText(status) {
|
|
238
|
+
return STATUS_TEXT[status] || '';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function bootFromDocument() {
|
|
242
|
+
const doc = globalThis.document;
|
|
243
|
+
const root = doc?.documentElement;
|
|
244
|
+
if (!root || root.dataset.surfcadBridge !== '1') return;
|
|
245
|
+
let extraOrigins = [];
|
|
246
|
+
try {
|
|
247
|
+
const parsed = JSON.parse(root.dataset.extraOrigins || '[]');
|
|
248
|
+
if (Array.isArray(parsed)) extraOrigins = parsed.filter((o) => typeof o === 'string');
|
|
249
|
+
} catch { /* none */ }
|
|
250
|
+
const statusEl = doc.getElementById('bridge-status');
|
|
251
|
+
startPopupBridge({
|
|
252
|
+
win: globalThis.window,
|
|
253
|
+
extraOrigins,
|
|
254
|
+
onStatus: (status) => {
|
|
255
|
+
root.dataset.status = status;
|
|
256
|
+
if (statusEl) statusEl.textContent = popupBridgeStatusText(status);
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
bootFromDocument();
|
|
@@ -22,7 +22,7 @@ export function isLoopbackAddress(address) {
|
|
|
22
22
|
* Extra origins (full origin strings) allowed in tests via env.
|
|
23
23
|
* @returns {Set<string>}
|
|
24
24
|
*/
|
|
25
|
-
function extraAllowedOrigins() {
|
|
25
|
+
export function extraAllowedOrigins() {
|
|
26
26
|
const raw = process.env.SURFCAD_AGENT_BRIDGE_EXTRA_ORIGINS || '';
|
|
27
27
|
const set = new Set();
|
|
28
28
|
for (const part of raw.split(',')) {
|