surfcad-mcp 0.3.2 → 0.3.4
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 +55 -7
- package/bin/surfcad-mcp.js +36 -3
- package/data/commands.json +4424 -129
- package/data/helpers.json +35 -11
- package/package.json +2 -2
- package/src/bridge/bridgePopup.mjs +28 -1
- package/src/bridge/localAddress.mjs +43 -5
- package/src/bridge/relayHub.mjs +31 -9
- package/src/cli.mjs +230 -0
- package/src/commandProtocol.mjs +126 -0
- package/src/errors.mjs +81 -2
- package/src/helpers.mjs +1 -1
- package/src/pairWait.mjs +34 -0
- package/src/prompt/errorHints.mjs +22 -5
- package/src/prompt/guide.mjs +4 -4
- package/src/prompt/promptSession.mjs +62 -23
- package/src/prompt/promptTools.mjs +2 -2
- package/src/relay.mjs +8 -5
- package/src/remote/config.mjs +178 -0
- package/src/remote/httpFallback.mjs +289 -0
- package/src/remote/login.mjs +258 -0
- package/src/remote/logout.mjs +67 -0
- package/src/remote/session.mjs +534 -0
- package/src/remote/tokenStore.mjs +109 -0
- package/src/server.mjs +52 -23
|
@@ -0,0 +1,258 @@
|
|
|
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
|
+
export const LOGIN_STALE_MESSAGE = 'That login code is stale. Run npx surfcad-mcp login again for a new one.';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {unknown} retryAfterSec
|
|
38
|
+
* @returns {string} empty, or ` try again in N s.`
|
|
39
|
+
*/
|
|
40
|
+
export function formatRetryAfter(retryAfterSec) {
|
|
41
|
+
const sec = Number(retryAfterSec);
|
|
42
|
+
if (!Number.isFinite(sec) || sec <= 0) return '';
|
|
43
|
+
return ` try again in ${Math.ceil(sec)} s.`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} lead sentence ending in a period
|
|
48
|
+
* @param {unknown} retryAfterSec
|
|
49
|
+
* @param {string} again
|
|
50
|
+
*/
|
|
51
|
+
function rateLimitMessage(lead, retryAfterSec, again) {
|
|
52
|
+
return `${lead}${formatRetryAfter(retryAfterSec)} ${again}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {string} url
|
|
57
|
+
* @param {object} body
|
|
58
|
+
* @param {typeof fetch} fetchImpl
|
|
59
|
+
* @param {AbortSignal} [signal]
|
|
60
|
+
*/
|
|
61
|
+
async function postJson(url, body, fetchImpl, signal) {
|
|
62
|
+
/** @type {Response} */
|
|
63
|
+
let res;
|
|
64
|
+
try {
|
|
65
|
+
res = await fetchImpl(url, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: {
|
|
68
|
+
'Content-Type': 'application/json',
|
|
69
|
+
Accept: 'application/json',
|
|
70
|
+
},
|
|
71
|
+
body: JSON.stringify(body),
|
|
72
|
+
signal,
|
|
73
|
+
});
|
|
74
|
+
} catch (err) {
|
|
75
|
+
if (err?.name === 'AbortError') {
|
|
76
|
+
throw Object.assign(new Error('aborted'), { code: 'aborted' });
|
|
77
|
+
}
|
|
78
|
+
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
79
|
+
}
|
|
80
|
+
/** @type {any} */
|
|
81
|
+
let json = null;
|
|
82
|
+
try {
|
|
83
|
+
json = await res.json();
|
|
84
|
+
} catch {
|
|
85
|
+
json = null;
|
|
86
|
+
}
|
|
87
|
+
return { status: res.status, json };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {{
|
|
92
|
+
* serverUrl: string,
|
|
93
|
+
* name?: string,
|
|
94
|
+
* machine?: string,
|
|
95
|
+
* env?: NodeJS.ProcessEnv,
|
|
96
|
+
* fetch?: typeof fetch,
|
|
97
|
+
* sleep?: (ms: number) => Promise<void>,
|
|
98
|
+
* timeoutMs?: number,
|
|
99
|
+
* now?: () => number,
|
|
100
|
+
* onCode?: (info: { userCode: string, approvalUrl: string, interval: number }) => Promise<void> | void,
|
|
101
|
+
* }} options
|
|
102
|
+
* @returns {Promise<{ server: string, name: string, machine: string }>}
|
|
103
|
+
*/
|
|
104
|
+
export async function loginDevice(options) {
|
|
105
|
+
const urls = agentUrls(options.serverUrl);
|
|
106
|
+
const fetchImpl = options.fetch || fetch;
|
|
107
|
+
const sleep = options.sleep || ((ms) => new Promise((resolve) => {
|
|
108
|
+
setTimeout(resolve, ms);
|
|
109
|
+
}));
|
|
110
|
+
const now = options.now || Date.now;
|
|
111
|
+
const name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
112
|
+
const machine = (options.machine || hostname() || '').trim() || 'an unknown machine';
|
|
113
|
+
const { deviceSecret, deviceSecretHash } = createDeviceSecret();
|
|
114
|
+
const started = await postJson(urls.pairUrl, {
|
|
115
|
+
...(name ? { name } : {}),
|
|
116
|
+
machine,
|
|
117
|
+
deviceSecretHash,
|
|
118
|
+
}, fetchImpl);
|
|
119
|
+
if (started.status !== 201 || !started.json?.userCode) {
|
|
120
|
+
const code = started.json?.error === 'rate_limited' ? 'rate_limited' : 'pair_failed';
|
|
121
|
+
const message = code === 'rate_limited'
|
|
122
|
+
? rateLimitMessage(
|
|
123
|
+
'Too many login attempts.',
|
|
124
|
+
started.json?.retryAfterSec,
|
|
125
|
+
'Run npx surfcad-mcp login again.',
|
|
126
|
+
)
|
|
127
|
+
: 'Could not start login.';
|
|
128
|
+
throw Object.assign(new Error(message), { code });
|
|
129
|
+
}
|
|
130
|
+
const userCode = String(started.json.userCode);
|
|
131
|
+
const intervalSec = Number(started.json.interval);
|
|
132
|
+
const pollMs = Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec * 1000 : 5000;
|
|
133
|
+
if (options.onCode) {
|
|
134
|
+
await options.onCode({
|
|
135
|
+
userCode,
|
|
136
|
+
approvalUrl: urls.approvalUrl,
|
|
137
|
+
interval: Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec : 5,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const expiresAtMs = Date.parse(started.json.expiresAt);
|
|
141
|
+
const deadline = Number.isFinite(expiresAtMs)
|
|
142
|
+
? expiresAtMs
|
|
143
|
+
: now() + (options.timeoutMs ?? 10 * 60 * 1000);
|
|
144
|
+
let first = true;
|
|
145
|
+
while (now() < deadline) {
|
|
146
|
+
if (!first) {
|
|
147
|
+
const wait = Math.min(pollMs, deadline - now());
|
|
148
|
+
if (wait > 0) await sleep(wait);
|
|
149
|
+
if (now() >= deadline) break;
|
|
150
|
+
}
|
|
151
|
+
first = false;
|
|
152
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
153
|
+
const remaining = Math.max(0, deadline - now());
|
|
154
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
155
|
+
let timeoutId;
|
|
156
|
+
const timeout = new Promise((resolve) => {
|
|
157
|
+
timeoutId = setTimeout(() => {
|
|
158
|
+
controller?.abort();
|
|
159
|
+
resolve({ timedOut: true });
|
|
160
|
+
}, remaining);
|
|
161
|
+
});
|
|
162
|
+
const pending = postJson(urls.pollUrl, { deviceSecret, userCode }, fetchImpl, controller?.signal)
|
|
163
|
+
.catch((err) => {
|
|
164
|
+
if (err?.code === 'aborted') return { timedOut: true };
|
|
165
|
+
throw err;
|
|
166
|
+
});
|
|
167
|
+
let polled;
|
|
168
|
+
try {
|
|
169
|
+
polled = await Promise.race([pending, timeout]);
|
|
170
|
+
} finally {
|
|
171
|
+
clearTimeout(timeoutId);
|
|
172
|
+
}
|
|
173
|
+
if (polled?.timedOut) break;
|
|
174
|
+
if (polled.status === 429) {
|
|
175
|
+
throw Object.assign(new Error(rateLimitMessage(
|
|
176
|
+
'Too many login attempts.',
|
|
177
|
+
polled.json?.retryAfterSec,
|
|
178
|
+
'Run npx surfcad-mcp login again.',
|
|
179
|
+
)), { code: 'rate_limited' });
|
|
180
|
+
}
|
|
181
|
+
if (polled.status !== 200 || !polled.json?.status) {
|
|
182
|
+
throw Object.assign(new Error('Could not check the login code.'), { code: 'poll_failed' });
|
|
183
|
+
}
|
|
184
|
+
const status = String(polled.json.status);
|
|
185
|
+
if (status === 'pending') continue;
|
|
186
|
+
if (status === 'approved') {
|
|
187
|
+
const token = polled.json.token;
|
|
188
|
+
if (typeof token !== 'string' || !token) {
|
|
189
|
+
throw Object.assign(
|
|
190
|
+
new Error('Login was approved but no token came back. Run npx surfcad-mcp login again.'),
|
|
191
|
+
{ code: 'bad_login' },
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
await saveLogin({
|
|
195
|
+
token,
|
|
196
|
+
server: urls.origin,
|
|
197
|
+
name,
|
|
198
|
+
machine,
|
|
199
|
+
}, options.env);
|
|
200
|
+
return { server: urls.origin, name, machine };
|
|
201
|
+
}
|
|
202
|
+
throw Object.assign(new Error(loginStatusError(status)), { code: status });
|
|
203
|
+
}
|
|
204
|
+
throw Object.assign(new Error(LOGIN_STALE_MESSAGE), { code: 'expired' });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Redeem a join code shown by SurfCAD. The token is saved and not returned
|
|
209
|
+
* to the caller for printing. A wrong, expired, or used code is one error.
|
|
210
|
+
* @param {{
|
|
211
|
+
* serverUrl: string,
|
|
212
|
+
* code: string,
|
|
213
|
+
* name?: string,
|
|
214
|
+
* machine?: string,
|
|
215
|
+
* env?: NodeJS.ProcessEnv,
|
|
216
|
+
* fetch?: typeof fetch,
|
|
217
|
+
* }} options
|
|
218
|
+
* @returns {Promise<{ server: string, name: string, machine: string }>}
|
|
219
|
+
*/
|
|
220
|
+
export async function loginWithCode(options) {
|
|
221
|
+
const urls = agentUrls(options.serverUrl);
|
|
222
|
+
const fetchImpl = options.fetch || fetch;
|
|
223
|
+
const name = typeof options.name === 'string' ? options.name.trim() : '';
|
|
224
|
+
const machine = (options.machine || hostname() || '').trim() || 'an unknown machine';
|
|
225
|
+
const code = typeof options.code === 'string' ? options.code.trim() : '';
|
|
226
|
+
if (!code) {
|
|
227
|
+
throw Object.assign(new Error('--code needs a value.'), { code: 'bad_args' });
|
|
228
|
+
}
|
|
229
|
+
const redeemed = await postJson(urls.joinUrl, {
|
|
230
|
+
code,
|
|
231
|
+
...(name ? { name } : {}),
|
|
232
|
+
machine,
|
|
233
|
+
}, fetchImpl);
|
|
234
|
+
if (redeemed.status === 429) {
|
|
235
|
+
throw Object.assign(
|
|
236
|
+
new Error(rateLimitMessage(
|
|
237
|
+
'Too many attempts.',
|
|
238
|
+
redeemed.json?.retryAfterSec,
|
|
239
|
+
'Run npx surfcad-mcp login --code again.',
|
|
240
|
+
)),
|
|
241
|
+
{ code: 'rate_limited' },
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
const token = redeemed.json?.token;
|
|
245
|
+
if (redeemed.status !== 200 || typeof token !== 'string' || !token) {
|
|
246
|
+
throw Object.assign(
|
|
247
|
+
new Error('That code is not valid. In SurfCAD, open Connect Agent and copy a new one.'),
|
|
248
|
+
{ code: 'invalid_code' },
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
await saveLogin({
|
|
252
|
+
token,
|
|
253
|
+
server: urls.origin,
|
|
254
|
+
name,
|
|
255
|
+
machine,
|
|
256
|
+
}, options.env);
|
|
257
|
+
return { server: urls.origin, name, machine };
|
|
258
|
+
}
|
|
@@ -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
|
+
}
|