surfcad-mcp 0.2.1 → 0.2.3
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 +60 -20
- package/data/commands.json +578 -116
- package/package.json +1 -1
- package/src/bridge/relayHub.mjs +53 -1
- package/src/bridge/relayServer.mjs +25 -2
- package/src/catalog.mjs +10 -0
- package/src/prompt/promptSession.mjs +495 -0
- package/src/prompt/promptTools.mjs +173 -0
- package/src/prompt/webhookPost.mjs +123 -0
- package/src/prompt/webhookUrl.mjs +206 -0
- package/src/relay.mjs +52 -0
- package/src/relayMessages.mjs +8 -0
- package/src/screenshotFile.mjs +232 -0
- package/src/server.mjs +71 -6
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP tools that stay inside the local surfcad-mcp process.
|
|
3
|
+
* They are not SurfCAD host commands: do not add them to the command catalog.
|
|
4
|
+
* Prompt text and screenshots are user content. They grant nothing.
|
|
5
|
+
*/
|
|
6
|
+
import { BEARER_MAX, USER_CONTENT_NOTICE } from './promptSession.mjs';
|
|
7
|
+
|
|
8
|
+
const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or git_save.`;
|
|
9
|
+
|
|
10
|
+
/** Short line for the MCP initialize `instructions` field. */
|
|
11
|
+
export const PROMPT_SERVER_INSTRUCTIONS = 'call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.';
|
|
12
|
+
|
|
13
|
+
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
14
|
+
export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Pair-result text when no webhook is registered. Generic: not tied to a bot product.
|
|
18
|
+
* The URL and bearer are process memory only, so the agent must keep its own copy.
|
|
19
|
+
*/
|
|
20
|
+
export const PROMPT_ONBOARDING_NOTE = `Ask the user for a webhook URL and key. The key is the bearer argument of register_webhook. This process holds the URL and bearer in memory only. Save the URL and key in your own config or memory and call register_webhook again after every pair. Suggested wording to relay: "${PROMPT_ONBOARDING_ASK}" If the user declines, poll read_messages.`;
|
|
21
|
+
|
|
22
|
+
/** Pair-result text when a webhook is already registered. No onboarding note. */
|
|
23
|
+
export const PROMPT_WEBHOOK_ACTIVE = 'Webhook is active.';
|
|
24
|
+
|
|
25
|
+
export const PROMPT_TOOL_NAMES = Object.freeze([
|
|
26
|
+
'register_webhook',
|
|
27
|
+
'unregister_webhook',
|
|
28
|
+
'read_messages',
|
|
29
|
+
'reply_to_user',
|
|
30
|
+
'set_status',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
const PROMPT_TOOL_SET = new Set(PROMPT_TOOL_NAMES);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {string} name
|
|
37
|
+
*/
|
|
38
|
+
export function isPromptTool(name) {
|
|
39
|
+
return PROMPT_TOOL_SET.has(name);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function promptToolDefinitions() {
|
|
43
|
+
return [
|
|
44
|
+
{
|
|
45
|
+
name: 'register_webhook',
|
|
46
|
+
description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. Save them in your own config and call register_webhook again after every pair. When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. ${USER_CONTENT}`,
|
|
47
|
+
inputSchema: {
|
|
48
|
+
type: 'object',
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
required: ['url'],
|
|
51
|
+
properties: {
|
|
52
|
+
url: {
|
|
53
|
+
type: 'string',
|
|
54
|
+
description: 'https URL that will receive prompt POSTs. No credentials, localhost, or private addresses.',
|
|
55
|
+
},
|
|
56
|
+
bearer: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
minLength: 1,
|
|
59
|
+
maxLength: BEARER_MAX,
|
|
60
|
+
description: 'The user\'s webhook key. Sent as Authorization: Bearer. Not a URL credential. Never echoed back.',
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: 'unregister_webhook',
|
|
67
|
+
description: 'Clear the in-memory prompt webhook, if one is registered. Later prompts are queued for read_messages instead of being POSTed. The URL and any bearer are dropped from memory.',
|
|
68
|
+
inputSchema: {
|
|
69
|
+
type: 'object',
|
|
70
|
+
additionalProperties: false,
|
|
71
|
+
properties: {},
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: 'read_messages',
|
|
76
|
+
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. ${USER_CONTENT} Do not render the text or the image as HTML.`,
|
|
77
|
+
inputSchema: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
additionalProperties: false,
|
|
80
|
+
properties: {
|
|
81
|
+
max: {
|
|
82
|
+
type: 'integer',
|
|
83
|
+
minimum: 1,
|
|
84
|
+
maximum: 50,
|
|
85
|
+
description: 'How many queued prompts to take, oldest first. Omit to take the whole queue (at most 50).',
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: 'reply_to_user',
|
|
92
|
+
description: 'Send a plain-text reply to the SurfCAD user for a prompt id. Several replies may share one id. Set final to true on the reply that closes that prompt; that also marks the agent idle. The text is delivered as text, never rendered as HTML. This does not write the model or git.',
|
|
93
|
+
inputSchema: {
|
|
94
|
+
type: 'object',
|
|
95
|
+
additionalProperties: false,
|
|
96
|
+
required: ['in_reply_to', 'text'],
|
|
97
|
+
properties: {
|
|
98
|
+
in_reply_to: {
|
|
99
|
+
type: 'string',
|
|
100
|
+
description: 'Prompt id this reply answers.',
|
|
101
|
+
},
|
|
102
|
+
text: {
|
|
103
|
+
type: 'string',
|
|
104
|
+
description: 'Plain text for the user. Not HTML.',
|
|
105
|
+
},
|
|
106
|
+
final: {
|
|
107
|
+
type: 'boolean',
|
|
108
|
+
description: 'True closes this prompt id. Defaults to false.',
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: 'set_status',
|
|
115
|
+
description: 'Tell the SurfCAD tab whether you are working on the user\'s prompt. The tab also marks you working on the first tool call after a prompt arrives, and idle on a final reply or after 120 seconds without activity. This does not grant write access.',
|
|
116
|
+
inputSchema: {
|
|
117
|
+
type: 'object',
|
|
118
|
+
additionalProperties: false,
|
|
119
|
+
required: ['working'],
|
|
120
|
+
properties: {
|
|
121
|
+
working: { type: 'boolean' },
|
|
122
|
+
id: {
|
|
123
|
+
type: 'string',
|
|
124
|
+
description: 'Optional prompt id this status refers to.',
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* @param {ReturnType<import('./promptSession.mjs').createPromptSession>} prompts
|
|
134
|
+
* @param {string} name
|
|
135
|
+
* @param {Record<string, unknown>} args
|
|
136
|
+
*/
|
|
137
|
+
export async function callPromptTool(prompts, name, args) {
|
|
138
|
+
if (name === 'register_webhook') {
|
|
139
|
+
const result = await prompts.registerWebhook(args.url, args.bearer);
|
|
140
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
141
|
+
}
|
|
142
|
+
if (name === 'unregister_webhook') {
|
|
143
|
+
return { content: [{ type: 'text', text: JSON.stringify(prompts.unregisterWebhook(), null, 2) }] };
|
|
144
|
+
}
|
|
145
|
+
if (name === 'read_messages') {
|
|
146
|
+
const { messages, images } = prompts.readMessages(args.max);
|
|
147
|
+
if (messages.length === 0) {
|
|
148
|
+
return {
|
|
149
|
+
content: [{ type: 'text', text: JSON.stringify({ messages: [], acked: [] }, null, 2) }],
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
const content = [];
|
|
153
|
+
const acked = [];
|
|
154
|
+
for (let i = 0; i < messages.length; i += 1) {
|
|
155
|
+
const row = messages[i];
|
|
156
|
+
acked.push(row.id);
|
|
157
|
+
content.push({ type: 'text', text: JSON.stringify(row, null, 2) });
|
|
158
|
+
const image = images[i];
|
|
159
|
+
if (image) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
|
|
160
|
+
}
|
|
161
|
+
content.push({ type: 'text', text: JSON.stringify({ acked }, null, 2) });
|
|
162
|
+
return { content };
|
|
163
|
+
}
|
|
164
|
+
if (name === 'reply_to_user') {
|
|
165
|
+
const result = prompts.reply(args);
|
|
166
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
167
|
+
}
|
|
168
|
+
if (name === 'set_status') {
|
|
169
|
+
const result = prompts.setStatus(args);
|
|
170
|
+
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
171
|
+
}
|
|
172
|
+
throw Object.assign(new Error(`Unknown tool: ${name}`), { code: 'unknown_tool' });
|
|
173
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* POST a prompt to a registered webhook.
|
|
3
|
+
* Times out after 10s and retries once. Does not follow redirects.
|
|
4
|
+
* `insecureTls` is honored only when the caller already decided the test
|
|
5
|
+
* switch applies (loopback target, and not NODE_ENV=production).
|
|
6
|
+
*/
|
|
7
|
+
import https from 'node:https';
|
|
8
|
+
import { isIP } from 'node:net';
|
|
9
|
+
|
|
10
|
+
export const WEBHOOK_TIMEOUT_MS = 10_000;
|
|
11
|
+
export const WEBHOOK_ATTEMPTS = 2;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Pin the connection to the address we already allowed, so DNS cannot
|
|
15
|
+
* rebind to a private address between the check and the POST.
|
|
16
|
+
* @param {string} address
|
|
17
|
+
*/
|
|
18
|
+
export function pinLookup(address) {
|
|
19
|
+
const family = isIP(address) === 6 ? 6 : 4;
|
|
20
|
+
return (_hostname, options, callback) => {
|
|
21
|
+
const cb = typeof options === 'function' ? options : callback;
|
|
22
|
+
const all = typeof options === 'object' && options?.all === true;
|
|
23
|
+
if (all) cb(null, [{ address, family }]);
|
|
24
|
+
else cb(null, address, family);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {string} url
|
|
30
|
+
* @param {Buffer} payload
|
|
31
|
+
* @param {{ timeoutMs: number, insecureTls: boolean, pinAddress?: string, bearer?: string }} opts
|
|
32
|
+
*/
|
|
33
|
+
function defaultHttpsPost(url, payload, opts) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = new URL(url);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
reject(err);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (parsed.protocol !== 'https:') {
|
|
43
|
+
reject(new Error('https required'));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const headers = {
|
|
47
|
+
'content-type': 'application/json',
|
|
48
|
+
'content-length': String(payload.length),
|
|
49
|
+
accept: 'application/json',
|
|
50
|
+
};
|
|
51
|
+
if (typeof opts.bearer === 'string' && opts.bearer.length > 0) {
|
|
52
|
+
if (opts.bearer.includes('\r') || opts.bearer.includes('\n')) {
|
|
53
|
+
reject(new Error('webhook_failed'));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
headers.authorization = `Bearer ${opts.bearer}`;
|
|
57
|
+
}
|
|
58
|
+
const requestOptions = {
|
|
59
|
+
protocol: 'https:',
|
|
60
|
+
hostname: parsed.hostname,
|
|
61
|
+
port: parsed.port || 443,
|
|
62
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers,
|
|
65
|
+
rejectUnauthorized: opts.insecureTls !== true,
|
|
66
|
+
servername: parsed.hostname,
|
|
67
|
+
timeout: opts.timeoutMs,
|
|
68
|
+
};
|
|
69
|
+
if (opts.pinAddress) requestOptions.lookup = pinLookup(opts.pinAddress);
|
|
70
|
+
const req = https.request(requestOptions, (res) => {
|
|
71
|
+
res.resume();
|
|
72
|
+
const code = res.statusCode || 0;
|
|
73
|
+
if (code >= 200 && code < 300) resolve({ ok: true });
|
|
74
|
+
else resolve({ ok: false, error: 'webhook_failed' });
|
|
75
|
+
});
|
|
76
|
+
req.on('timeout', () => {
|
|
77
|
+
req.destroy();
|
|
78
|
+
const err = new Error('webhook timeout');
|
|
79
|
+
err.name = 'TimeoutError';
|
|
80
|
+
reject(err);
|
|
81
|
+
});
|
|
82
|
+
req.on('error', reject);
|
|
83
|
+
req.end(payload);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {string} url
|
|
89
|
+
* @param {unknown} body
|
|
90
|
+
* @param {{
|
|
91
|
+
* timeoutMs?: number,
|
|
92
|
+
* attempts?: number,
|
|
93
|
+
* insecureTls?: boolean,
|
|
94
|
+
* pinAddress?: string,
|
|
95
|
+
* bearer?: string,
|
|
96
|
+
* request?: typeof defaultHttpsPost,
|
|
97
|
+
* }} [options]
|
|
98
|
+
*/
|
|
99
|
+
export async function postPromptWebhook(url, body, options = {}) {
|
|
100
|
+
const timeoutMs = options.timeoutMs ?? WEBHOOK_TIMEOUT_MS;
|
|
101
|
+
const attempts = options.attempts ?? WEBHOOK_ATTEMPTS;
|
|
102
|
+
const request = options.request || defaultHttpsPost;
|
|
103
|
+
const payload = Buffer.from(JSON.stringify(body));
|
|
104
|
+
const opts = {
|
|
105
|
+
timeoutMs,
|
|
106
|
+
insecureTls: options.insecureTls === true,
|
|
107
|
+
pinAddress: options.pinAddress,
|
|
108
|
+
};
|
|
109
|
+
if (typeof options.bearer === 'string' && options.bearer.length > 0) {
|
|
110
|
+
opts.bearer = options.bearer;
|
|
111
|
+
}
|
|
112
|
+
let lastError = 'webhook_failed';
|
|
113
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
114
|
+
try {
|
|
115
|
+
const out = await request(url, payload, opts);
|
|
116
|
+
if (out?.ok === true) return { ok: true };
|
|
117
|
+
lastError = 'webhook_failed';
|
|
118
|
+
} catch (err) {
|
|
119
|
+
lastError = err?.name === 'TimeoutError' ? 'webhook_timeout' : 'webhook_failed';
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { ok: false, error: lastError };
|
|
123
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webhook URL checks for in-viewer prompts.
|
|
3
|
+
* The URL stays in process memory. Callers must not log it and must not write it to disk.
|
|
4
|
+
* `SURFCAD_WEBHOOK_TLS_INSECURE=1` is a test switch: it allows a loopback target and,
|
|
5
|
+
* for that loopback target only, a self-signed certificate. `NODE_ENV=production`
|
|
6
|
+
* ignores the switch, so production keeps rejecting localhost and private addresses.
|
|
7
|
+
*/
|
|
8
|
+
import { lookup } from 'node:dns/promises';
|
|
9
|
+
import { BlockList, isIP } from 'node:net';
|
|
10
|
+
|
|
11
|
+
export const WEBHOOK_TLS_INSECURE_ENV = 'SURFCAD_WEBHOOK_TLS_INSECURE';
|
|
12
|
+
|
|
13
|
+
const block = new BlockList();
|
|
14
|
+
for (const [addr, prefix] of [
|
|
15
|
+
['0.0.0.0', 8],
|
|
16
|
+
['10.0.0.0', 8],
|
|
17
|
+
['127.0.0.0', 8],
|
|
18
|
+
['169.254.0.0', 16],
|
|
19
|
+
['172.16.0.0', 12],
|
|
20
|
+
['192.0.0.0', 24],
|
|
21
|
+
['192.0.2.0', 24],
|
|
22
|
+
['192.168.0.0', 16],
|
|
23
|
+
['198.18.0.0', 15],
|
|
24
|
+
['198.51.100.0', 24],
|
|
25
|
+
['203.0.113.0', 24],
|
|
26
|
+
['100.64.0.0', 10],
|
|
27
|
+
['224.0.0.0', 4],
|
|
28
|
+
['240.0.0.0', 4],
|
|
29
|
+
]) {
|
|
30
|
+
block.addSubnet(addr, prefix, 'ipv4');
|
|
31
|
+
}
|
|
32
|
+
block.addAddress('::', 'ipv6');
|
|
33
|
+
block.addAddress('::1', 'ipv6');
|
|
34
|
+
block.addSubnet('fc00::', 7, 'ipv6');
|
|
35
|
+
block.addSubnet('fe80::', 10, 'ipv6');
|
|
36
|
+
block.addSubnet('ff00::', 8, 'ipv6');
|
|
37
|
+
block.addSubnet('2001:db8::', 32, 'ipv6');
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
41
|
+
*/
|
|
42
|
+
export function webhookInsecureTlsAllowed(env = process.env) {
|
|
43
|
+
if (!env || env.NODE_ENV === 'production') return false;
|
|
44
|
+
return env[WEBHOOK_TLS_INSECURE_ENV] === '1';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} hostname
|
|
49
|
+
*/
|
|
50
|
+
export function isLoopbackName(hostname) {
|
|
51
|
+
const host = String(hostname || '').toLowerCase().replace(/\.$/, '');
|
|
52
|
+
return host === 'localhost' || host === 'localhost.localdomain' || host.endsWith('.localhost');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {string} ip
|
|
57
|
+
*/
|
|
58
|
+
export function isLoopbackIp(ip) {
|
|
59
|
+
const lower = String(ip || '').toLowerCase();
|
|
60
|
+
if (lower === '::1') return true;
|
|
61
|
+
if (lower.startsWith('::ffff:')) {
|
|
62
|
+
const v4 = lower.slice('::ffff:'.length);
|
|
63
|
+
return isIP(v4) === 4 && v4.startsWith('127.');
|
|
64
|
+
}
|
|
65
|
+
return isIP(lower) === 4 && lower.startsWith('127.');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} hostname
|
|
70
|
+
*/
|
|
71
|
+
export function isLoopbackHost(hostname) {
|
|
72
|
+
const host = String(hostname || '').replace(/^\[|\]$/g, '');
|
|
73
|
+
return isLoopbackName(host) || isLoopbackIp(host);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* @param {string} hostname
|
|
78
|
+
*/
|
|
79
|
+
function isPrivateName(hostname) {
|
|
80
|
+
const host = String(hostname || '').toLowerCase().replace(/\.$/, '');
|
|
81
|
+
return isLoopbackName(host) || host.endsWith('.local');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {string} hostname
|
|
86
|
+
*/
|
|
87
|
+
function isObfuscatedIp(hostname) {
|
|
88
|
+
if (/^0x[0-9a-f]+$/i.test(hostname)) return true;
|
|
89
|
+
if (/^\d+$/.test(hostname)) return true;
|
|
90
|
+
const parts = hostname.split('.');
|
|
91
|
+
if (parts.length >= 2 && parts.length <= 4 && parts.every((part) => /^(0x[0-9a-f]+|\d+)$/i.test(part))) {
|
|
92
|
+
if (isIP(hostname) !== 4) return true;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @param {string} ip
|
|
99
|
+
*/
|
|
100
|
+
function expandedIps(ip) {
|
|
101
|
+
const lower = String(ip || '').toLowerCase();
|
|
102
|
+
const out = [lower];
|
|
103
|
+
if (lower.startsWith('::ffff:')) {
|
|
104
|
+
const v4 = lower.slice('::ffff:'.length);
|
|
105
|
+
if (isIP(v4) === 4) out.push(v4);
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @param {string} ip
|
|
112
|
+
*/
|
|
113
|
+
export function isBlockedIp(ip) {
|
|
114
|
+
for (const candidate of expandedIps(ip)) {
|
|
115
|
+
const kind = isIP(candidate);
|
|
116
|
+
if (kind === 0) return true;
|
|
117
|
+
if (block.check(candidate, kind === 4 ? 'ipv4' : 'ipv6')) return true;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @param {string} message
|
|
124
|
+
*/
|
|
125
|
+
function fail(message) {
|
|
126
|
+
return { ok: false, code: 'bad_webhook_url', message };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {string} hostname
|
|
131
|
+
*/
|
|
132
|
+
export async function defaultResolveHost(hostname) {
|
|
133
|
+
const pending = lookup(hostname, { all: true, verbatim: true });
|
|
134
|
+
let timer;
|
|
135
|
+
try {
|
|
136
|
+
return await Promise.race([
|
|
137
|
+
pending.then((rows) => rows.map((row) => row.address)),
|
|
138
|
+
new Promise((_, reject) => {
|
|
139
|
+
timer = setTimeout(() => reject(new Error('dns_timeout')), 5000);
|
|
140
|
+
}),
|
|
141
|
+
]);
|
|
142
|
+
} finally {
|
|
143
|
+
if (timer) clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* @param {unknown} raw
|
|
149
|
+
* @param {{ allowLoopback?: boolean, resolveHost?: (hostname: string) => Promise<string[]> }} [options]
|
|
150
|
+
* @returns {Promise<{ ok: true, host: string, addresses: string[] } | { ok: false, code: string, message: string }>}
|
|
151
|
+
*/
|
|
152
|
+
export async function validateWebhookUrl(raw, options = {}) {
|
|
153
|
+
if (typeof raw !== 'string') return fail('Webhook URL is required');
|
|
154
|
+
const text = raw.trim();
|
|
155
|
+
if (!text || text.length > 2048 || /\s/.test(text) || text.includes('\0')) {
|
|
156
|
+
return fail(text ? 'Webhook URL is not a valid URL' : 'Webhook URL is required');
|
|
157
|
+
}
|
|
158
|
+
let url;
|
|
159
|
+
try {
|
|
160
|
+
url = new URL(text);
|
|
161
|
+
} catch {
|
|
162
|
+
return fail('Webhook URL is not a valid URL');
|
|
163
|
+
}
|
|
164
|
+
if (url.protocol !== 'https:') return fail('Webhook URL must use https');
|
|
165
|
+
const authority = text.slice(text.indexOf('://') + 3).split('/')[0];
|
|
166
|
+
if (url.username || url.password || authority.includes('@')) {
|
|
167
|
+
return fail('Webhook URL must not include credentials');
|
|
168
|
+
}
|
|
169
|
+
if (url.port === '0') return fail('Webhook URL port is not allowed');
|
|
170
|
+
const hostname = url.hostname.replace(/\.$/, '').toLowerCase();
|
|
171
|
+
if (!hostname || isObfuscatedIp(hostname)) {
|
|
172
|
+
return fail(hostname ? 'Webhook URL must not target a private address' : 'Webhook URL is not a valid URL');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const allowLoopback = options.allowLoopback === true;
|
|
176
|
+
if (isPrivateName(hostname)) {
|
|
177
|
+
if (!(allowLoopback && isLoopbackName(hostname))) {
|
|
178
|
+
return fail('Webhook URL must not target localhost or a private address');
|
|
179
|
+
}
|
|
180
|
+
return { ok: true, host: hostname, addresses: ['127.0.0.1'] };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let addresses;
|
|
184
|
+
if (isIP(hostname) !== 0) {
|
|
185
|
+
addresses = [hostname];
|
|
186
|
+
} else {
|
|
187
|
+
const resolveHost = options.resolveHost || defaultResolveHost;
|
|
188
|
+
try {
|
|
189
|
+
addresses = await resolveHost(hostname);
|
|
190
|
+
} catch {
|
|
191
|
+
return fail('Webhook host could not be resolved');
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!Array.isArray(addresses) || addresses.length === 0) {
|
|
195
|
+
return fail('Webhook host could not be resolved');
|
|
196
|
+
}
|
|
197
|
+
for (const address of addresses) {
|
|
198
|
+
if (typeof address !== 'string' || isIP(address) === 0) {
|
|
199
|
+
return fail('Webhook host could not be resolved');
|
|
200
|
+
}
|
|
201
|
+
if (!isBlockedIp(address)) continue;
|
|
202
|
+
if (allowLoopback && isLoopbackIp(address)) continue;
|
|
203
|
+
return fail('Webhook URL must not target localhost or a private address');
|
|
204
|
+
}
|
|
205
|
+
return { ok: true, host: hostname, addresses };
|
|
206
|
+
}
|
package/src/relay.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { connectPeer } from './nodeClient.mjs';
|
|
|
3
3
|
import { PAIR_MSG } from './relayMessages.mjs';
|
|
4
4
|
import { redactToken } from './bridge/relayHub.mjs';
|
|
5
5
|
import { RECONNECT_HINT, pairPendingError, pairingLostError } from './errors.mjs';
|
|
6
|
+
import { createPromptSession } from './prompt/promptSession.mjs';
|
|
6
7
|
|
|
7
8
|
const DEFAULT_WS_URL = 'ws://127.0.0.1:17341';
|
|
8
9
|
|
|
@@ -77,6 +78,8 @@ export class RelaySession {
|
|
|
77
78
|
#ensureRelay;
|
|
78
79
|
/** @type {(line: string) => void} */
|
|
79
80
|
#log;
|
|
81
|
+
/** @type {ReturnType<typeof createPromptSession>} */
|
|
82
|
+
#prompts;
|
|
80
83
|
|
|
81
84
|
/**
|
|
82
85
|
* @param {{
|
|
@@ -84,6 +87,13 @@ export class RelaySession {
|
|
|
84
87
|
* reconnectDelaysMs?: readonly number[],
|
|
85
88
|
* ensureRelay?: () => Promise<unknown>,
|
|
86
89
|
* onLog?: (line: string) => void,
|
|
90
|
+
* promptSession?: ReturnType<typeof createPromptSession>,
|
|
91
|
+
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean, authorization?: string }) => Promise<{ ok: boolean, error?: string }>,
|
|
92
|
+
* testWebhookOverride?: () => boolean,
|
|
93
|
+
* resolveHost?: (hostname: string) => Promise<string[]>,
|
|
94
|
+
* now?: () => number,
|
|
95
|
+
* setTimer?: (fn: () => void, ms: number) => unknown,
|
|
96
|
+
* clearTimer?: (timer: unknown) => void,
|
|
87
97
|
* }} [options]
|
|
88
98
|
*/
|
|
89
99
|
constructor(options = {}) {
|
|
@@ -91,6 +101,15 @@ export class RelaySession {
|
|
|
91
101
|
this.#delays = options.reconnectDelaysMs?.length ? options.reconnectDelaysMs : DEFAULT_RECONNECT_DELAYS_MS;
|
|
92
102
|
this.#ensureRelay = options.ensureRelay || null;
|
|
93
103
|
this.#log = options.onLog || defaultSessionLog;
|
|
104
|
+
this.#prompts = options.promptSession || createPromptSession({
|
|
105
|
+
send: (payload) => this.#sendToTab(payload),
|
|
106
|
+
postWebhook: options.postWebhook,
|
|
107
|
+
testWebhookOverride: options.testWebhookOverride,
|
|
108
|
+
resolveHost: options.resolveHost,
|
|
109
|
+
now: options.now,
|
|
110
|
+
setTimer: options.setTimer,
|
|
111
|
+
clearTimer: options.clearTimer,
|
|
112
|
+
});
|
|
94
113
|
}
|
|
95
114
|
|
|
96
115
|
get url() {
|
|
@@ -118,6 +137,32 @@ export class RelaySession {
|
|
|
118
137
|
return this.#state === 'paired' && this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
|
|
119
138
|
}
|
|
120
139
|
|
|
140
|
+
/** In-memory prompt queue and webhook for this pairing. */
|
|
141
|
+
get prompts() {
|
|
142
|
+
return this.#prompts;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* First tool call after a prompt arrives marks the agent working.
|
|
147
|
+
* Best-effort: a dead socket does not fail the tool call.
|
|
148
|
+
*/
|
|
149
|
+
noteAgentToolCall() {
|
|
150
|
+
try {
|
|
151
|
+
this.#prompts.noteToolCall();
|
|
152
|
+
} catch {
|
|
153
|
+
/* status is advisory */
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @param {object} payload
|
|
159
|
+
*/
|
|
160
|
+
#sendToTab(payload) {
|
|
161
|
+
if (!this.isPaired()) throw notPaired();
|
|
162
|
+
const ws = /** @type {WebSocket} */ (this.#ws);
|
|
163
|
+
ws.send(JSON.stringify(payload));
|
|
164
|
+
}
|
|
165
|
+
|
|
121
166
|
/**
|
|
122
167
|
* @param {string} token
|
|
123
168
|
*/
|
|
@@ -197,6 +242,10 @@ export class RelaySession {
|
|
|
197
242
|
this.#lose(ws, typeof msg.detail === 'string' ? `${msg.reason}: ${msg.detail}` : String(msg.reason || 'unpaired'));
|
|
198
243
|
return;
|
|
199
244
|
}
|
|
245
|
+
if (msg.type === PAIR_MSG.AGENT_PROMPT) {
|
|
246
|
+
void this.#prompts.acceptPrompt(msg);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
200
249
|
const id = typeof msg.id === 'string' ? msg.id : null;
|
|
201
250
|
const waiter = id ? this.#pending.get(id) : undefined;
|
|
202
251
|
if (waiter) {
|
|
@@ -228,6 +277,7 @@ export class RelaySession {
|
|
|
228
277
|
*/
|
|
229
278
|
#lose(ws, reason) {
|
|
230
279
|
if (this.#ws !== ws) return;
|
|
280
|
+
this.#prompts.clear();
|
|
231
281
|
this.#ws = null;
|
|
232
282
|
try { ws.close(); } catch { /* noop */ }
|
|
233
283
|
this.#state = 'lost';
|
|
@@ -282,8 +332,10 @@ export class RelaySession {
|
|
|
282
332
|
* @param {string} code
|
|
283
333
|
*/
|
|
284
334
|
#detach(reason, code) {
|
|
335
|
+
const endPrompts = this.#state === 'paired' || this.#state === 'lost';
|
|
285
336
|
this.#generation += 1;
|
|
286
337
|
this.#pairing = null;
|
|
338
|
+
if (endPrompts) this.#prompts.clear();
|
|
287
339
|
const ws = this.#ws;
|
|
288
340
|
this.#ws = null;
|
|
289
341
|
if (ws) {
|
package/src/relayMessages.mjs
CHANGED
|
@@ -13,4 +13,12 @@ export const PAIR_MSG = Object.freeze({
|
|
|
13
13
|
UNPAIRED: 'unpaired',
|
|
14
14
|
CALL: 'call',
|
|
15
15
|
RESPONSE: 'response',
|
|
16
|
+
/** Page → paired agent. Contract v:1. */
|
|
17
|
+
AGENT_PROMPT: 'agent.prompt',
|
|
18
|
+
/** Agent → page. `{ id, delivery, error? }`. */
|
|
19
|
+
AGENT_PROMPT_ACK: 'agent.prompt.ack',
|
|
20
|
+
/** Agent → page. Contract v:1. Several replies may share one prompt id. */
|
|
21
|
+
AGENT_REPLY: 'agent.reply',
|
|
22
|
+
/** Agent → page. Contract v:1. */
|
|
23
|
+
AGENT_STATUS: 'agent.status',
|
|
16
24
|
});
|