surfcad-mcp 0.3.2 → 0.3.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.
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Command path used when the agent WebSocket cannot be opened.
3
+ * POST /agent/commands, then SSE, then long-poll. The bearer token is sent
4
+ * on the request and is never written into an error or a log line.
5
+ */
6
+
7
+ import { readCommandResponse } from '../commandProtocol.mjs';
8
+ import { asRemoteError, tokenRevokedError } from '../errors.mjs';
9
+
10
+ /** How long a command may sit unanswered, on the WebSocket and on HTTPS. */
11
+ export const COMMAND_WAIT_MS = 10 * 60 * 1000;
12
+ const STEP_TIMEOUT_MS = 30_000;
13
+
14
+ /** Same error for a WebSocket command and for the HTTPS wait. */
15
+ export function commandWaitTimeout() {
16
+ return Object.assign(new Error('Timed out waiting for the SurfCAD tab.'), {
17
+ code: 'bridge_error',
18
+ retryable: true,
19
+ });
20
+ }
21
+
22
+ /**
23
+ * @param {number} status
24
+ * @param {any} json
25
+ */
26
+ function httpFailure(status, json) {
27
+ if (status === 401) return tokenRevokedError();
28
+ const code = typeof json?.error === 'string' ? json.error : '';
29
+ const message = typeof json?.message === 'string' ? json.message : '';
30
+ return asRemoteError({ code, message: message || code });
31
+ }
32
+
33
+ /**
34
+ * @param {unknown} response
35
+ */
36
+ export function resultFromCommandResponse(response) {
37
+ const parsed = readCommandResponse(response);
38
+ if (!parsed) {
39
+ return {
40
+ ok: false,
41
+ error: Object.assign(new Error('Bad command response'), { code: 'bridge_error' }),
42
+ };
43
+ }
44
+ if (parsed.ok === true) return { ok: true, result: parsed.result };
45
+ return { ok: false, error: asRemoteError(parsed.error) };
46
+ }
47
+
48
+ /**
49
+ * @param {string} raw
50
+ */
51
+ export function parseSseBlock(raw) {
52
+ let event = 'message';
53
+ /** @type {string[]} */
54
+ const data = [];
55
+ for (const line of raw.split('\n')) {
56
+ if (line.startsWith('event:')) event = line.slice('event:'.length).trim();
57
+ else if (line.startsWith('data:')) data.push(line.slice('data:'.length).trim());
58
+ }
59
+ /** @type {unknown} */
60
+ let json = null;
61
+ if (data.length) {
62
+ try {
63
+ json = JSON.parse(data.join('\n'));
64
+ } catch {
65
+ json = null;
66
+ }
67
+ }
68
+ return { event, data: json };
69
+ }
70
+
71
+ /**
72
+ * @param {string} buffer
73
+ * @param {{ event: string, data: unknown }[]} events
74
+ */
75
+ function drainSse(buffer, events) {
76
+ let rest = buffer.replace(/\r\n/g, '\n');
77
+ let idx = rest.indexOf('\n\n');
78
+ while (idx !== -1) {
79
+ const raw = rest.slice(0, idx);
80
+ rest = rest.slice(idx + 2);
81
+ if (raw.trim()) events.push(parseSseBlock(raw));
82
+ idx = rest.indexOf('\n\n');
83
+ }
84
+ return rest;
85
+ }
86
+
87
+ /**
88
+ * @param {Response} res
89
+ */
90
+ async function readSseEvents(res) {
91
+ /** @type {{ event: string, data: unknown }[]} */
92
+ const events = [];
93
+ const reader = res.body?.getReader?.();
94
+ if (!reader) {
95
+ const text = await res.text();
96
+ drainSse(`${text.replace(/\r\n/g, '\n')}\n\n`, events);
97
+ return events;
98
+ }
99
+ const decoder = new TextDecoder();
100
+ let buffer = '';
101
+ let done = false;
102
+ try {
103
+ while (!done) {
104
+ const next = await reader.read();
105
+ done = next.done === true;
106
+ if (done) break;
107
+ buffer += decoder.decode(next.value, { stream: true });
108
+ buffer = drainSse(buffer, events);
109
+ }
110
+ buffer += decoder.decode();
111
+ drainSse(`${buffer}\n\n`, events);
112
+ } finally {
113
+ try { reader.releaseLock(); } catch { /* already released */ }
114
+ }
115
+ return events;
116
+ }
117
+
118
+ /**
119
+ * @param {{ event: string, data: unknown }[]} events
120
+ * @returns {'pending' | { ok: true, result: unknown } | { ok: false, error: Error }}
121
+ */
122
+ function interpretSse(events) {
123
+ for (const event of events) {
124
+ if (event.event === 'error') {
125
+ const code = event.data && typeof event.data === 'object'
126
+ ? /** @type {{ error?: string }} */ (event.data).error
127
+ : '';
128
+ if (code === 'not_found') {
129
+ return {
130
+ ok: false,
131
+ error: Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' }),
132
+ };
133
+ }
134
+ return { ok: false, error: asRemoteError({ code: code || 'bridge_error', message: 'Command failed' }) };
135
+ }
136
+ if (event.event === 'pending') return 'pending';
137
+ if (event.event === 'result') {
138
+ const outcome = resultFromCommandResponse(event.data);
139
+ if (!outcome.ok) return { ok: false, error: outcome.error };
140
+ return { ok: true, result: outcome.result };
141
+ }
142
+ }
143
+ return 'pending';
144
+ }
145
+
146
+ /**
147
+ * @param {string} url
148
+ * @param {string} token
149
+ * @param {typeof fetch} fetchImpl
150
+ * @param {AbortSignal} signal
151
+ */
152
+ async function fetchAuthed(url, token, fetchImpl, signal) {
153
+ return fetchImpl(url, {
154
+ method: 'GET',
155
+ headers: {
156
+ Authorization: `Bearer ${token}`,
157
+ Accept: 'application/json',
158
+ },
159
+ signal,
160
+ });
161
+ }
162
+
163
+ /**
164
+ * @param {{
165
+ * commandsUrl: string,
166
+ * token: string,
167
+ * frame: { v: number, id: string | number, command: string, args: unknown },
168
+ * fetch?: typeof fetch,
169
+ * now?: () => number,
170
+ * }} options
171
+ */
172
+ export async function callOverHttp(options) {
173
+ const fetchImpl = options.fetch || fetch;
174
+ const now = options.now || Date.now;
175
+ const frame = options.frame;
176
+ const post = await fetchImpl(options.commandsUrl, {
177
+ method: 'POST',
178
+ headers: {
179
+ Authorization: `Bearer ${options.token}`,
180
+ 'Content-Type': 'application/json',
181
+ Accept: 'application/json',
182
+ },
183
+ body: JSON.stringify(frame),
184
+ });
185
+ /** @type {any} */
186
+ let posted = null;
187
+ try {
188
+ posted = await post.json();
189
+ } catch {
190
+ posted = null;
191
+ }
192
+ if (post.status === 401) throw tokenRevokedError();
193
+ if (post.status !== 202) throw httpFailure(post.status, posted);
194
+
195
+ const deadline = now() + COMMAND_WAIT_MS;
196
+ let sseFailed = false;
197
+ while (now() < deadline) {
198
+ const signal = AbortSignal.timeout(STEP_TIMEOUT_MS + 5000);
199
+ if (!sseFailed) {
200
+ try {
201
+ const outcome = await waitViaSse(options, fetchImpl, signal);
202
+ if (outcome === 'pending') continue;
203
+ if (!outcome.ok) throw outcome.error;
204
+ return outcome.result;
205
+ } catch (err) {
206
+ if (isTerminal(err)) throw err;
207
+ sseFailed = true;
208
+ }
209
+ }
210
+ const polled = await waitViaPoll(options, fetchImpl, signal);
211
+ if (polled === 'pending') continue;
212
+ if (!polled.ok) throw polled.error;
213
+ return polled.result;
214
+ }
215
+ throw commandWaitTimeout();
216
+ }
217
+
218
+ /**
219
+ * @param {unknown} err
220
+ */
221
+ function isTerminal(err) {
222
+ const code = err && typeof err === 'object' ? /** @type {{ code?: string }} */ (err).code : '';
223
+ return code === 'tab_asleep'
224
+ || code === 'too_many_pending'
225
+ || code === 'token_revoked'
226
+ || code === 'client_update_required'
227
+ || code === 'not_found';
228
+ }
229
+
230
+ /**
231
+ * @param {{ commandsUrl: string, token: string, frame: { id: string | number } }} options
232
+ * @param {typeof fetch} fetchImpl
233
+ * @param {AbortSignal} signal
234
+ */
235
+ async function waitViaSse(options, fetchImpl, signal) {
236
+ const url = `${options.commandsUrl}/${encodeURIComponent(String(options.frame.id))}/events?timeout=${STEP_TIMEOUT_MS}`;
237
+ const res = await fetchImpl(url, {
238
+ method: 'GET',
239
+ headers: {
240
+ Authorization: `Bearer ${options.token}`,
241
+ Accept: 'text/event-stream',
242
+ },
243
+ signal,
244
+ });
245
+ if (res.status === 401) throw tokenRevokedError();
246
+ if (!res.ok) {
247
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
248
+ throw Object.assign(new Error(`Event stream failed (${res.status})`), { code: 'sse_failed' });
249
+ }
250
+ const type = res.headers.get('content-type') || '';
251
+ if (type.includes('application/json')) {
252
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
253
+ throw Object.assign(new Error('Event stream was not available'), { code: 'sse_failed' });
254
+ }
255
+ const events = await readSseEvents(res);
256
+ if (!events.length) {
257
+ throw Object.assign(new Error('Event stream was empty'), { code: 'sse_failed' });
258
+ }
259
+ return interpretSse(events);
260
+ }
261
+
262
+ /**
263
+ * @param {{ commandsUrl: string, token: string, frame: { id: string | number } }} options
264
+ * @param {typeof fetch} fetchImpl
265
+ * @param {AbortSignal} signal
266
+ */
267
+ async function waitViaPoll(options, fetchImpl, signal) {
268
+ const url = `${options.commandsUrl}/${encodeURIComponent(String(options.frame.id))}?timeout=${STEP_TIMEOUT_MS}`;
269
+ const res = await fetchAuthed(url, options.token, fetchImpl, signal);
270
+ /** @type {any} */
271
+ let json = null;
272
+ try {
273
+ json = await res.json();
274
+ } catch {
275
+ json = null;
276
+ }
277
+ if (res.status === 401) throw tokenRevokedError();
278
+ if (res.status === 404) {
279
+ throw Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' });
280
+ }
281
+ if (!res.ok) throw httpFailure(res.status, json);
282
+ if (json?.status === 'pending') return 'pending';
283
+ if (json?.status === 'done') {
284
+ const outcome = resultFromCommandResponse(json.response);
285
+ if (!outcome.ok) return { ok: false, error: outcome.error };
286
+ return { ok: true, result: outcome.result };
287
+ }
288
+ throw Object.assign(new Error('Bad command response'), { code: 'bridge_error' });
289
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Device-code login against the server relay.
3
+ * The device secret and the token are never logged or printed.
4
+ */
5
+
6
+ import { createHash, randomBytes } from 'node:crypto';
7
+ import { hostname } from 'node:os';
8
+ import { agentUrls } from './config.mjs';
9
+ import { saveLogin } from './tokenStore.mjs';
10
+
11
+ /**
12
+ * 32 random bytes. Pairing start sends only the SHA-256. Poll sends the
13
+ * secret itself. Neither value is logged.
14
+ */
15
+ function createDeviceSecret() {
16
+ const bytes = randomBytes(32);
17
+ return {
18
+ deviceSecret: bytes.toString('base64url'),
19
+ deviceSecretHash: createHash('sha256').update(bytes).digest('hex'),
20
+ };
21
+ }
22
+
23
+ /**
24
+ * @param {string} status
25
+ */
26
+ export function loginStatusError(status) {
27
+ if (status === 'denied') return 'SurfCAD denied this login.';
28
+ if (status === 'expired') return 'That login code expired. Run npx surfcad-mcp login again.';
29
+ if (status === 'dead') return 'Too many wrong tries. Run npx surfcad-mcp login again.';
30
+ if (status === 'consumed') return 'That login code was already used. Run npx surfcad-mcp login again.';
31
+ return 'Login ended before approval. Run npx surfcad-mcp login again.';
32
+ }
33
+
34
+ /**
35
+ * @param {string} url
36
+ * @param {object} body
37
+ * @param {typeof fetch} fetchImpl
38
+ */
39
+ async function postJson(url, body, fetchImpl) {
40
+ /** @type {Response} */
41
+ let res;
42
+ try {
43
+ res = await fetchImpl(url, {
44
+ method: 'POST',
45
+ headers: {
46
+ 'Content-Type': 'application/json',
47
+ Accept: 'application/json',
48
+ },
49
+ body: JSON.stringify(body),
50
+ });
51
+ } catch {
52
+ throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
53
+ }
54
+ /** @type {any} */
55
+ let json = null;
56
+ try {
57
+ json = await res.json();
58
+ } catch {
59
+ json = null;
60
+ }
61
+ return { status: res.status, json };
62
+ }
63
+
64
+ /**
65
+ * @param {{
66
+ * serverUrl: string,
67
+ * name?: string,
68
+ * machine?: string,
69
+ * env?: NodeJS.ProcessEnv,
70
+ * fetch?: typeof fetch,
71
+ * sleep?: (ms: number) => Promise<void>,
72
+ * timeoutMs?: number,
73
+ * now?: () => number,
74
+ * onCode?: (info: { userCode: string, approvalUrl: string, interval: number }) => Promise<void> | void,
75
+ * }} options
76
+ * @returns {Promise<{ server: string, name: string, machine: string }>}
77
+ */
78
+ export async function loginDevice(options) {
79
+ const urls = agentUrls(options.serverUrl);
80
+ const fetchImpl = options.fetch || fetch;
81
+ const sleep = options.sleep || ((ms) => new Promise((resolve) => {
82
+ setTimeout(resolve, ms);
83
+ }));
84
+ const now = options.now || Date.now;
85
+ const name = typeof options.name === 'string' ? options.name.trim() : '';
86
+ const machine = (options.machine || hostname() || '').trim() || 'an unknown machine';
87
+ const { deviceSecret, deviceSecretHash } = createDeviceSecret();
88
+ const started = await postJson(urls.pairUrl, {
89
+ ...(name ? { name } : {}),
90
+ machine,
91
+ deviceSecretHash,
92
+ }, fetchImpl);
93
+ if (started.status !== 201 || !started.json?.userCode) {
94
+ const code = started.json?.error === 'rate_limited' ? 'rate_limited' : 'pair_failed';
95
+ const message = code === 'rate_limited'
96
+ ? 'Too many login attempts. Wait and run npx surfcad-mcp login again.'
97
+ : 'Could not start login.';
98
+ throw Object.assign(new Error(message), { code });
99
+ }
100
+ const userCode = String(started.json.userCode);
101
+ const intervalSec = Number(started.json.interval);
102
+ const pollMs = Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec * 1000 : 5000;
103
+ if (options.onCode) {
104
+ await options.onCode({
105
+ userCode,
106
+ approvalUrl: urls.approvalUrl,
107
+ interval: Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec : 5,
108
+ });
109
+ }
110
+ const deadline = now() + (options.timeoutMs ?? 10 * 60 * 1000);
111
+ let first = true;
112
+ while (now() < deadline) {
113
+ if (!first) await sleep(pollMs);
114
+ first = false;
115
+ const polled = await postJson(urls.pollUrl, { deviceSecret, userCode }, fetchImpl);
116
+ if (polled.status !== 200 || !polled.json?.status) {
117
+ throw Object.assign(new Error('Could not check the login code.'), { code: 'poll_failed' });
118
+ }
119
+ const status = String(polled.json.status);
120
+ if (status === 'pending') continue;
121
+ if (status === 'approved') {
122
+ const token = polled.json.token;
123
+ if (typeof token !== 'string' || !token) {
124
+ throw Object.assign(
125
+ new Error('Login was approved but no token came back. Run npx surfcad-mcp login again.'),
126
+ { code: 'bad_login' },
127
+ );
128
+ }
129
+ await saveLogin({
130
+ token,
131
+ server: urls.origin,
132
+ name,
133
+ machine,
134
+ }, options.env);
135
+ return { server: urls.origin, name, machine };
136
+ }
137
+ throw Object.assign(new Error(loginStatusError(status)), { code: status });
138
+ }
139
+ throw Object.assign(
140
+ new Error('Timed out waiting for approval. Run npx surfcad-mcp login again.'),
141
+ { code: 'expired' },
142
+ );
143
+ }
144
+
145
+ /**
146
+ * Redeem a join code shown by SurfCAD. The token is saved and not returned
147
+ * to the caller for printing. A wrong, expired, or used code is one error.
148
+ * @param {{
149
+ * serverUrl: string,
150
+ * code: string,
151
+ * name?: string,
152
+ * machine?: string,
153
+ * env?: NodeJS.ProcessEnv,
154
+ * fetch?: typeof fetch,
155
+ * }} options
156
+ * @returns {Promise<{ server: string, name: string, machine: string }>}
157
+ */
158
+ export async function loginWithCode(options) {
159
+ const urls = agentUrls(options.serverUrl);
160
+ const fetchImpl = options.fetch || fetch;
161
+ const name = typeof options.name === 'string' ? options.name.trim() : '';
162
+ const machine = (options.machine || hostname() || '').trim() || 'an unknown machine';
163
+ const code = typeof options.code === 'string' ? options.code.trim() : '';
164
+ if (!code) {
165
+ throw Object.assign(new Error('--code needs a value.'), { code: 'bad_args' });
166
+ }
167
+ const redeemed = await postJson(urls.joinUrl, {
168
+ code,
169
+ ...(name ? { name } : {}),
170
+ machine,
171
+ }, fetchImpl);
172
+ if (redeemed.status === 429) {
173
+ throw Object.assign(
174
+ new Error('Too many attempts. Wait and run npx surfcad-mcp login --code again.'),
175
+ { code: 'rate_limited' },
176
+ );
177
+ }
178
+ const token = redeemed.json?.token;
179
+ if (redeemed.status !== 200 || typeof token !== 'string' || !token) {
180
+ throw Object.assign(
181
+ new Error('That code is not valid. In SurfCAD, open Connect Agent and copy a new one.'),
182
+ { code: 'invalid_code' },
183
+ );
184
+ }
185
+ await saveLogin({
186
+ token,
187
+ server: urls.origin,
188
+ name,
189
+ machine,
190
+ }, options.env);
191
+ return { server: urls.origin, name, machine };
192
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Revoke the saved bearer token, then delete the local file.
3
+ * The token is never logged or printed. A server that cannot be reached
4
+ * still loses the local file; the caller says the login may stay valid.
5
+ */
6
+
7
+ import { agentUrls } from './config.mjs';
8
+ import { deleteSavedLogin, readSavedLogin } from './tokenStore.mjs';
9
+
10
+ const REVOKE_TIMEOUT_MS = 8000;
11
+
12
+ /**
13
+ * @param {{ token: string, server: string }} saved
14
+ * @param {typeof fetch} fetchImpl
15
+ * @returns {Promise<boolean>}
16
+ */
17
+ async function revokeSelf(saved, fetchImpl) {
18
+ /** @type {string} */
19
+ let origin;
20
+ try {
21
+ origin = agentUrls(saved.server).origin;
22
+ } catch {
23
+ return false;
24
+ }
25
+ try {
26
+ const res = await fetchImpl(`${origin}/agent/tokens/self`, {
27
+ method: 'DELETE',
28
+ headers: {
29
+ Authorization: `Bearer ${saved.token}`,
30
+ Accept: 'application/json',
31
+ },
32
+ signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
33
+ });
34
+ try {
35
+ await res.arrayBuffer();
36
+ } catch {
37
+ /* the status is enough; a body we cannot read is not a reason to keep the file */
38
+ }
39
+ return res.status === 200 || res.status === 401 || res.status === 404;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {{ env?: NodeJS.ProcessEnv, fetch?: typeof fetch }} [options]
47
+ * @returns {Promise<{ hadLogin: boolean, confirmed: boolean }>}
48
+ */
49
+ export async function logoutDevice(options = {}) {
50
+ const env = options.env;
51
+ const fetchImpl = options.fetch || fetch;
52
+ /** @type {{ token: string, server: string } | null} */
53
+ let saved = null;
54
+ try {
55
+ saved = await readSavedLogin(env);
56
+ } catch (err) {
57
+ await deleteSavedLogin(env);
58
+ throw err;
59
+ }
60
+ let confirmed = !saved?.token;
61
+ try {
62
+ if (saved?.token) confirmed = await revokeSelf(saved, fetchImpl);
63
+ } finally {
64
+ await deleteSavedLogin(env);
65
+ }
66
+ return { hadLogin: Boolean(saved?.token), confirmed };
67
+ }