@mnemom/mnemom 0.14.6 → 0.15.1-next.0
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/commands/activity.d.ts +2 -0
- package/dist/commands/{integrity.js → activity.js} +4 -1
- package/dist/commands/agents.js +18 -1
- package/dist/commands/api-key.js +20 -4
- package/dist/commands/auth.js +39 -32
- package/dist/commands/card.js +17 -2
- package/dist/commands/org.js +15 -2
- package/dist/commands/protection.d.ts +2 -1
- package/dist/commands/protection.js +163 -3
- package/dist/commands/status.js +4 -1
- package/dist/commands/try-me.d.ts +52 -0
- package/dist/commands/try-me.js +374 -0
- package/dist/index.js +63 -3
- package/dist/lib/api.js +5 -6
- package/dist/lib/auth.d.ts +33 -10
- package/dist/lib/auth.js +71 -201
- package/dist/lib/oauth.d.ts +132 -0
- package/dist/lib/oauth.js +490 -0
- package/dist/lib/prompt.js +19 -7
- package/dist/lib/try-me.d.ts +181 -0
- package/dist/lib/try-me.js +245 -0
- package/package.json +3 -2
- package/dist/commands/integrity.d.ts +0 -1
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth 2.1 client for the Mnemom Authorization Server.
|
|
3
|
+
*
|
|
4
|
+
* `mnemom login` authenticates against the Mnemom OAuth AS (the same AS that
|
|
5
|
+
* fronts the MCP control plane) instead of doing a raw Supabase session login.
|
|
6
|
+
* This yields SCOPED access tokens (`mcp:read` / `mcp:write`) — not the full
|
|
7
|
+
* Supabase god-token — so a leaked CLI credential can only do what the CLI was
|
|
8
|
+
* granted, and grants are independently revocable server-side (MNE-805/806).
|
|
9
|
+
*
|
|
10
|
+
* Two interactive flows, both standards-based:
|
|
11
|
+
* - Authorization Code + PKCE with a loopback redirect (the `wrangler login`
|
|
12
|
+
* pattern): open the browser to /authorize, catch the redirect on a
|
|
13
|
+
* localhost listener, exchange code+verifier at /token.
|
|
14
|
+
* - RFC 8628 Device Authorization Grant (`--no-browser` / headless): POST
|
|
15
|
+
* /device_authorization, print the user_code + verification_uri, poll
|
|
16
|
+
* /token honoring `authorization_pending` and `slow_down`.
|
|
17
|
+
*
|
|
18
|
+
* Everything is driven off RFC 8414 discovery
|
|
19
|
+
* (/.well-known/oauth-authorization-server) — endpoint paths are NOT hardcoded.
|
|
20
|
+
* The public client_id is obtained via RFC 7591 Dynamic Client Registration and
|
|
21
|
+
* cached, so there is no client secret to embed (the AS advertises
|
|
22
|
+
* token_endpoint_auth_method "none" — public clients only).
|
|
23
|
+
*/
|
|
24
|
+
import * as http from "node:http";
|
|
25
|
+
import * as crypto from "node:crypto";
|
|
26
|
+
import { execFile } from "node:child_process";
|
|
27
|
+
import { getApiUrl } from "./config.js";
|
|
28
|
+
// The scopes the CLI requests. The AS currently advertises mcp:read + mcp:write
|
|
29
|
+
// (scopes_supported in discovery); we request both so a single login covers the
|
|
30
|
+
// full command surface. If discovery ever narrows what's available we intersect
|
|
31
|
+
// against scopes_supported before asking, so we never request an unknown scope.
|
|
32
|
+
const REQUESTED_SCOPES = ["mcp:read", "mcp:write"];
|
|
33
|
+
const CLIENT_NAME = "Mnemom CLI";
|
|
34
|
+
const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
35
|
+
// Loopback login waits at most this long for the browser round-trip before
|
|
36
|
+
// giving up and freeing the port.
|
|
37
|
+
const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000;
|
|
38
|
+
// Cadence for the "…still waiting for you to finish signing in" heartbeat that
|
|
39
|
+
// both interactive login poll loops emit, so a multi-minute browser sign-in
|
|
40
|
+
// doesn't read as a hung CLI (matches the card-write retry tick in try-me).
|
|
41
|
+
const LOGIN_HEARTBEAT_MS = 15 * 1000;
|
|
42
|
+
let cachedMetadata = null;
|
|
43
|
+
/**
|
|
44
|
+
* Fetch (and process-cache) the AS metadata document. We resolve it relative to
|
|
45
|
+
* the active API base URL so staging/local point at their own AS.
|
|
46
|
+
*/
|
|
47
|
+
export async function discover() {
|
|
48
|
+
if (cachedMetadata)
|
|
49
|
+
return cachedMetadata;
|
|
50
|
+
const url = `${getApiUrl()}/.well-known/oauth-authorization-server`;
|
|
51
|
+
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
|
52
|
+
if (!res.ok) {
|
|
53
|
+
throw new Error(`Could not load OAuth metadata from ${url} (HTTP ${res.status}). ` + `Is the API reachable?`);
|
|
54
|
+
}
|
|
55
|
+
const meta = (await res.json());
|
|
56
|
+
if (!meta.authorization_endpoint || !meta.token_endpoint) {
|
|
57
|
+
throw new Error("OAuth metadata is missing authorization_endpoint/token_endpoint.");
|
|
58
|
+
}
|
|
59
|
+
cachedMetadata = meta;
|
|
60
|
+
return meta;
|
|
61
|
+
}
|
|
62
|
+
/** Reset the process-level discovery cache (used by tests). */
|
|
63
|
+
export function _resetDiscoveryCache() {
|
|
64
|
+
cachedMetadata = null;
|
|
65
|
+
}
|
|
66
|
+
/** Intersect our requested scopes with what the AS advertises. */
|
|
67
|
+
function negotiateScopes(meta) {
|
|
68
|
+
const supported = meta.scopes_supported;
|
|
69
|
+
const scopes = supported && supported.length > 0
|
|
70
|
+
? REQUESTED_SCOPES.filter((s) => supported.includes(s))
|
|
71
|
+
: REQUESTED_SCOPES;
|
|
72
|
+
// If nothing intersects (misconfigured AS), fall back to asking for what the
|
|
73
|
+
// AS says it supports rather than sending an empty scope.
|
|
74
|
+
return (scopes.length > 0 ? scopes : (supported ?? REQUESTED_SCOPES)).join(" ");
|
|
75
|
+
}
|
|
76
|
+
// ============================================================================
|
|
77
|
+
// Dynamic Client Registration (RFC 7591)
|
|
78
|
+
// ============================================================================
|
|
79
|
+
/**
|
|
80
|
+
* Register a public client for the CLI and return its client_id. The AS issues
|
|
81
|
+
* public clients (token_endpoint_auth_method "none"), so there is no secret to
|
|
82
|
+
* persist. The caller is responsible for caching the returned id.
|
|
83
|
+
*/
|
|
84
|
+
export async function registerClient(redirectUris) {
|
|
85
|
+
const meta = await discover();
|
|
86
|
+
if (!meta.registration_endpoint) {
|
|
87
|
+
throw new Error("This Authorization Server does not support dynamic client registration; " +
|
|
88
|
+
"no public CLI client_id is available.");
|
|
89
|
+
}
|
|
90
|
+
const res = await fetch(meta.registration_endpoint, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
93
|
+
body: JSON.stringify({
|
|
94
|
+
client_name: CLIENT_NAME,
|
|
95
|
+
redirect_uris: redirectUris,
|
|
96
|
+
grant_types: ["authorization_code", "refresh_token", DEVICE_CODE_GRANT],
|
|
97
|
+
response_types: ["code"],
|
|
98
|
+
token_endpoint_auth_method: "none",
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
if (!res.ok) {
|
|
102
|
+
throw new Error(`Client registration failed (HTTP ${res.status}): ${await safeBody(res)}`);
|
|
103
|
+
}
|
|
104
|
+
const data = (await res.json());
|
|
105
|
+
if (!data.client_id) {
|
|
106
|
+
throw new Error("Client registration response did not include a client_id.");
|
|
107
|
+
}
|
|
108
|
+
return data.client_id;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Generate a PKCE verifier/challenge pair. The verifier is a high-entropy
|
|
112
|
+
* URL-safe string (RFC 7636 §4.1: 43–128 chars from the unreserved set); the
|
|
113
|
+
* challenge is BASE64URL(SHA256(verifier)) for the S256 method (the only method
|
|
114
|
+
* the AS advertises, and the only one allowed under OAuth 2.1).
|
|
115
|
+
*/
|
|
116
|
+
export function generatePkce() {
|
|
117
|
+
const verifier = base64url(crypto.randomBytes(32));
|
|
118
|
+
const challenge = base64url(crypto.createHash("sha256").update(verifier).digest());
|
|
119
|
+
return { verifier, challenge, method: "S256" };
|
|
120
|
+
}
|
|
121
|
+
function base64url(buf) {
|
|
122
|
+
return buf.toString("base64url");
|
|
123
|
+
}
|
|
124
|
+
function tokensFromResponse(data) {
|
|
125
|
+
const now = Math.floor(Date.now() / 1000);
|
|
126
|
+
const expiresIn = typeof data.expires_in === "number" ? data.expires_in : 3600;
|
|
127
|
+
return {
|
|
128
|
+
accessToken: data.access_token,
|
|
129
|
+
tokenType: data.token_type ?? "Bearer",
|
|
130
|
+
refreshToken: data.refresh_token,
|
|
131
|
+
scope: data.scope,
|
|
132
|
+
expiresAt: now + expiresIn,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Run the interactive authorization-code + PKCE login. Returns the issued
|
|
137
|
+
* scoped tokens plus the client_id that was used (so the caller can persist it
|
|
138
|
+
* for refresh). `openUrl` is injectable so tests can drive the flow without
|
|
139
|
+
* spawning a real browser.
|
|
140
|
+
*/
|
|
141
|
+
export async function loginWithLoopback(openUrl = openBrowser) {
|
|
142
|
+
const meta = await discover();
|
|
143
|
+
const pkce = generatePkce();
|
|
144
|
+
const state = crypto.randomBytes(16).toString("hex");
|
|
145
|
+
const { port, codePromise, close } = await startLoopbackServer(state);
|
|
146
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
147
|
+
// Register a client bound to the exact loopback redirect URI. OAuth 2.1
|
|
148
|
+
// requires exact redirect_uri matching, and the loopback port is ephemeral,
|
|
149
|
+
// so we register per-login (cheap, public client, no secret).
|
|
150
|
+
const clientId = await registerClient([redirectUri]);
|
|
151
|
+
const authUrl = new URL(meta.authorization_endpoint);
|
|
152
|
+
authUrl.searchParams.set("response_type", "code");
|
|
153
|
+
authUrl.searchParams.set("client_id", clientId);
|
|
154
|
+
authUrl.searchParams.set("redirect_uri", redirectUri);
|
|
155
|
+
authUrl.searchParams.set("scope", negotiateScopes(meta));
|
|
156
|
+
authUrl.searchParams.set("state", state);
|
|
157
|
+
authUrl.searchParams.set("code_challenge", pkce.challenge);
|
|
158
|
+
authUrl.searchParams.set("code_challenge_method", pkce.method);
|
|
159
|
+
console.log("Opening browser to authenticate...");
|
|
160
|
+
console.log(`If the browser doesn't open, visit:\n ${authUrl.toString()}\n`);
|
|
161
|
+
openUrl(authUrl.toString());
|
|
162
|
+
console.log("Waiting for authentication...");
|
|
163
|
+
try {
|
|
164
|
+
// Heartbeat while we await the loopback redirect — otherwise the sign-in
|
|
165
|
+
// round-trip is dead silent and reads as a hung CLI.
|
|
166
|
+
const code = await withHeartbeat(codePromise, LOGIN_HEARTBEAT_MS, (s) => console.log(`…still waiting for you to finish signing in (${s}s)`));
|
|
167
|
+
const tokens = await exchangeCode(meta, clientId, code, pkce.verifier, redirectUri);
|
|
168
|
+
return { tokens, clientId };
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
close();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Start a loopback HTTP listener that captures the OAuth redirect
|
|
176
|
+
* (GET /callback?code=...&state=...). Resolves with the authorization code once
|
|
177
|
+
* a redirect with a matching state arrives; rejects on error/mismatch/timeout.
|
|
178
|
+
*/
|
|
179
|
+
function startLoopbackServer(expectedState) {
|
|
180
|
+
let resolveCode;
|
|
181
|
+
let rejectCode;
|
|
182
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
183
|
+
resolveCode = resolve;
|
|
184
|
+
rejectCode = reject;
|
|
185
|
+
});
|
|
186
|
+
const server = http.createServer((req, res) => {
|
|
187
|
+
const reqUrl = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
188
|
+
if (req.method !== "GET" || reqUrl.pathname !== "/callback") {
|
|
189
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
190
|
+
res.end("Not found");
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const error = reqUrl.searchParams.get("error");
|
|
194
|
+
const code = reqUrl.searchParams.get("code");
|
|
195
|
+
const state = reqUrl.searchParams.get("state");
|
|
196
|
+
if (error) {
|
|
197
|
+
const desc = reqUrl.searchParams.get("error_description") ?? error;
|
|
198
|
+
respondHtml(res, 400, "Authentication failed", desc);
|
|
199
|
+
rejectCode(new Error(`Authorization denied: ${desc}`));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
// Constant-time state comparison to avoid leaking timing on the CSRF token.
|
|
203
|
+
if (!state || !timingSafeEqual(state, expectedState)) {
|
|
204
|
+
respondHtml(res, 403, "Authentication failed", "State mismatch — possible CSRF.");
|
|
205
|
+
rejectCode(new Error("State mismatch — possible CSRF attack"));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (!code) {
|
|
209
|
+
respondHtml(res, 400, "Authentication failed", "No authorization code in callback.");
|
|
210
|
+
rejectCode(new Error("No authorization code in callback"));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
respondHtml(res, 200, "Authenticated!", "You can close this tab and return to the terminal.");
|
|
214
|
+
resolveCode(code);
|
|
215
|
+
});
|
|
216
|
+
return new Promise((resolve) => {
|
|
217
|
+
server.listen(0, "127.0.0.1", () => {
|
|
218
|
+
const port = server.address().port;
|
|
219
|
+
const timeout = setTimeout(() => {
|
|
220
|
+
rejectCode(new Error("Login timed out. Please try again."));
|
|
221
|
+
server.close();
|
|
222
|
+
}, LOOPBACK_TIMEOUT_MS);
|
|
223
|
+
resolve({
|
|
224
|
+
port,
|
|
225
|
+
codePromise,
|
|
226
|
+
close: () => {
|
|
227
|
+
clearTimeout(timeout);
|
|
228
|
+
server.close();
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
async function exchangeCode(meta, clientId, code, verifier, redirectUri) {
|
|
235
|
+
const res = await fetch(meta.token_endpoint, {
|
|
236
|
+
method: "POST",
|
|
237
|
+
headers: {
|
|
238
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
239
|
+
Accept: "application/json",
|
|
240
|
+
},
|
|
241
|
+
body: new URLSearchParams({
|
|
242
|
+
grant_type: "authorization_code",
|
|
243
|
+
code,
|
|
244
|
+
redirect_uri: redirectUri,
|
|
245
|
+
client_id: clientId,
|
|
246
|
+
code_verifier: verifier,
|
|
247
|
+
}),
|
|
248
|
+
});
|
|
249
|
+
if (!res.ok) {
|
|
250
|
+
throw new Error(`Token exchange failed: ${await oauthError(res)}`);
|
|
251
|
+
}
|
|
252
|
+
return tokensFromResponse((await res.json()));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Run the RFC 8628 device authorization grant. Registers a client (the device
|
|
256
|
+
* flow needs no redirect, but the AS's DCR validation requires a valid
|
|
257
|
+
* redirect_uri — HTTPS or a loopback — so we register a loopback placeholder it
|
|
258
|
+
* will never redirect to), requests a device code, prints the user_code +
|
|
259
|
+
* verification_uri for the user to approve in any browser, then polls the token
|
|
260
|
+
* endpoint until approval — honoring `authorization_pending` and `slow_down`
|
|
261
|
+
* per the spec.
|
|
262
|
+
*
|
|
263
|
+
* `display` and `sleep` are injectable so tests can drive the poll loop
|
|
264
|
+
* deterministically without real timers or stdout.
|
|
265
|
+
*/
|
|
266
|
+
export async function loginWithDevice(opts) {
|
|
267
|
+
const display = opts?.display ?? ((line) => console.log(line));
|
|
268
|
+
const sleep = opts?.sleep ?? defaultSleep;
|
|
269
|
+
const meta = await discover();
|
|
270
|
+
if (!meta.device_authorization_endpoint) {
|
|
271
|
+
throw new Error("This Authorization Server does not support the device flow.");
|
|
272
|
+
}
|
|
273
|
+
// Device flow has no redirect, but the AS's DCR validation rejects the OAuth
|
|
274
|
+
// OOB sentinel ("redirect_uri must be HTTPS or a loopback for native
|
|
275
|
+
// clients"). Register a loopback placeholder — it satisfies validation and is
|
|
276
|
+
// never used, since the device grant never redirects.
|
|
277
|
+
const clientId = await registerClient(["http://127.0.0.1/callback"]);
|
|
278
|
+
const authzRes = await fetch(meta.device_authorization_endpoint, {
|
|
279
|
+
method: "POST",
|
|
280
|
+
headers: {
|
|
281
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
282
|
+
Accept: "application/json",
|
|
283
|
+
},
|
|
284
|
+
body: new URLSearchParams({ client_id: clientId, scope: negotiateScopes(meta) }),
|
|
285
|
+
});
|
|
286
|
+
if (!authzRes.ok) {
|
|
287
|
+
throw new Error(`Device authorization failed: ${await oauthError(authzRes)}`);
|
|
288
|
+
}
|
|
289
|
+
const authz = (await authzRes.json());
|
|
290
|
+
display("");
|
|
291
|
+
display("To authenticate, visit:");
|
|
292
|
+
display(` ${authz.verification_uri}`);
|
|
293
|
+
display("");
|
|
294
|
+
display(`And enter the code: ${authz.user_code}`);
|
|
295
|
+
if (authz.verification_uri_complete) {
|
|
296
|
+
display("");
|
|
297
|
+
display(`Or open this URL directly:`);
|
|
298
|
+
display(` ${authz.verification_uri_complete}`);
|
|
299
|
+
}
|
|
300
|
+
display("");
|
|
301
|
+
display("Waiting for authorization...");
|
|
302
|
+
const tokens = await pollDeviceToken(meta, clientId, authz, sleep, display);
|
|
303
|
+
return { tokens, clientId };
|
|
304
|
+
}
|
|
305
|
+
async function pollDeviceToken(meta, clientId, authz, sleep, display) {
|
|
306
|
+
// RFC 8628 §3.5: default interval is 5s if the server omits it; on slow_down
|
|
307
|
+
// we increase the interval by 5s and keep that as the new minimum.
|
|
308
|
+
let intervalMs = (authz.interval ?? 5) * 1000;
|
|
309
|
+
const deadline = Date.now() + authz.expires_in * 1000;
|
|
310
|
+
// Heartbeat off accumulated poll time (not wall-clock) so it stays correct
|
|
311
|
+
// even when sleep is stubbed in tests; ticks every LOGIN_HEARTBEAT_MS.
|
|
312
|
+
let waitedMs = 0;
|
|
313
|
+
let nextHeartbeatMs = LOGIN_HEARTBEAT_MS;
|
|
314
|
+
for (;;) {
|
|
315
|
+
if (Date.now() >= deadline) {
|
|
316
|
+
throw new Error("Device authorization expired before approval. Please try again.");
|
|
317
|
+
}
|
|
318
|
+
await sleep(intervalMs);
|
|
319
|
+
waitedMs += intervalMs;
|
|
320
|
+
const res = await fetch(meta.token_endpoint, {
|
|
321
|
+
method: "POST",
|
|
322
|
+
headers: {
|
|
323
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
324
|
+
Accept: "application/json",
|
|
325
|
+
},
|
|
326
|
+
body: new URLSearchParams({
|
|
327
|
+
grant_type: DEVICE_CODE_GRANT,
|
|
328
|
+
device_code: authz.device_code,
|
|
329
|
+
client_id: clientId,
|
|
330
|
+
}),
|
|
331
|
+
});
|
|
332
|
+
if (res.ok) {
|
|
333
|
+
return tokensFromResponse((await res.json()));
|
|
334
|
+
}
|
|
335
|
+
const body = (await res.json().catch(() => ({})));
|
|
336
|
+
switch (body.error) {
|
|
337
|
+
case "authorization_pending":
|
|
338
|
+
break; // keep polling at the current interval
|
|
339
|
+
case "slow_down":
|
|
340
|
+
intervalMs += 5000; // RFC 8628 §3.5
|
|
341
|
+
break;
|
|
342
|
+
case "expired_token":
|
|
343
|
+
throw new Error("Device authorization expired before approval. Please try again.");
|
|
344
|
+
case "access_denied":
|
|
345
|
+
throw new Error("Authorization was denied.");
|
|
346
|
+
default:
|
|
347
|
+
throw new Error(`Device authorization failed: ${body.error ?? `HTTP ${res.status}`}` +
|
|
348
|
+
(body.error_description ? ` — ${body.error_description}` : ""));
|
|
349
|
+
}
|
|
350
|
+
// Still pending (authorization_pending / slow_down) — emit a heartbeat
|
|
351
|
+
// every ~15s so a multi-minute approval doesn't look hung.
|
|
352
|
+
if (waitedMs >= nextHeartbeatMs) {
|
|
353
|
+
display(`…still waiting for you to finish signing in (${Math.round(waitedMs / 1000)}s)`);
|
|
354
|
+
nextHeartbeatMs += LOGIN_HEARTBEAT_MS;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// ============================================================================
|
|
359
|
+
// Refresh (RFC 6749 §6)
|
|
360
|
+
// ============================================================================
|
|
361
|
+
/**
|
|
362
|
+
* Exchange a refresh token for a fresh access token. Returns null if refresh is
|
|
363
|
+
* not possible (no refresh token, or the AS rejects it — e.g. revoked/expired),
|
|
364
|
+
* so callers can fall back to prompting for re-login rather than crashing.
|
|
365
|
+
*/
|
|
366
|
+
export async function refreshTokens(refreshToken, clientId) {
|
|
367
|
+
if (!refreshToken || !clientId)
|
|
368
|
+
return null;
|
|
369
|
+
try {
|
|
370
|
+
const meta = await discover();
|
|
371
|
+
const res = await fetch(meta.token_endpoint, {
|
|
372
|
+
method: "POST",
|
|
373
|
+
headers: {
|
|
374
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
375
|
+
Accept: "application/json",
|
|
376
|
+
},
|
|
377
|
+
body: new URLSearchParams({
|
|
378
|
+
grant_type: "refresh_token",
|
|
379
|
+
refresh_token: refreshToken,
|
|
380
|
+
client_id: clientId,
|
|
381
|
+
}),
|
|
382
|
+
});
|
|
383
|
+
if (!res.ok)
|
|
384
|
+
return null;
|
|
385
|
+
const data = (await res.json());
|
|
386
|
+
const tokens = tokensFromResponse(data);
|
|
387
|
+
// Per RFC 6749 §6, a refresh response MAY omit a new refresh token, in which
|
|
388
|
+
// case the old one remains valid — preserve it so the next refresh works.
|
|
389
|
+
if (!tokens.refreshToken)
|
|
390
|
+
tokens.refreshToken = refreshToken;
|
|
391
|
+
return tokens;
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
// ============================================================================
|
|
398
|
+
// Helpers
|
|
399
|
+
// ============================================================================
|
|
400
|
+
/**
|
|
401
|
+
* Open `url` in the user's default browser WITHOUT a shell. The URL is always
|
|
402
|
+
* passed as a separate argv element (never concatenated into a command string),
|
|
403
|
+
* so shell metacharacters — `$(...)`, backticks, `\` — in the URL can never be
|
|
404
|
+
* interpreted as a command. Fire-and-forget: any failure (no opener installed,
|
|
405
|
+
* headless host) is swallowed because callers already print a manual-URL
|
|
406
|
+
* fallback, so a missing browser must not crash login.
|
|
407
|
+
*/
|
|
408
|
+
export function openBrowser(url) {
|
|
409
|
+
// On Windows, `start` is a cmd builtin and its FIRST quoted arg is the window
|
|
410
|
+
// title; the empty "" makes the URL the target rather than the title.
|
|
411
|
+
const [command, args] = process.platform === "darwin"
|
|
412
|
+
? ["open", [url]]
|
|
413
|
+
: process.platform === "win32"
|
|
414
|
+
? ["cmd", ["/c", "start", "", url]]
|
|
415
|
+
: ["xdg-open", [url]];
|
|
416
|
+
try {
|
|
417
|
+
const child = execFile(command, args, () => {
|
|
418
|
+
/* swallow opener errors — the manual URL fallback is already printed */
|
|
419
|
+
});
|
|
420
|
+
// Don't keep the event loop alive on the opener; login flow waits on the
|
|
421
|
+
// loopback/device promise, not on the browser process.
|
|
422
|
+
child.unref?.();
|
|
423
|
+
}
|
|
424
|
+
catch {
|
|
425
|
+
/* execFile threw synchronously (e.g. command not found) — ignore */
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
function defaultSleep(ms) {
|
|
429
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Await `promise` while emitting a heartbeat tick every `intervalMs`, so a long
|
|
433
|
+
* silent wait (a browser sign-in round-trip) doesn't look hung. `onTick` is
|
|
434
|
+
* called with the elapsed whole-seconds count. The timer is always cleared when
|
|
435
|
+
* the promise settles, and is unref'd so it never keeps the event loop alive on
|
|
436
|
+
* its own. `timers` is injectable so tests drive the ticks without real clocks.
|
|
437
|
+
*/
|
|
438
|
+
export async function withHeartbeat(promise, intervalMs, onTick, timers = {}) {
|
|
439
|
+
const set = timers.set ?? ((cb, ms) => setInterval(cb, ms));
|
|
440
|
+
const clear = timers.clear ?? ((h) => clearInterval(h));
|
|
441
|
+
let elapsedMs = 0;
|
|
442
|
+
const handle = set(() => {
|
|
443
|
+
elapsedMs += intervalMs;
|
|
444
|
+
onTick(Math.round(elapsedMs / 1000));
|
|
445
|
+
}, intervalMs);
|
|
446
|
+
handle?.unref?.();
|
|
447
|
+
try {
|
|
448
|
+
return await promise;
|
|
449
|
+
}
|
|
450
|
+
finally {
|
|
451
|
+
clear(handle);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
/** Constant-time string compare that tolerates length differences. */
|
|
455
|
+
function timingSafeEqual(a, b) {
|
|
456
|
+
const ab = Buffer.from(a);
|
|
457
|
+
const bb = Buffer.from(b);
|
|
458
|
+
if (ab.length !== bb.length)
|
|
459
|
+
return false;
|
|
460
|
+
return crypto.timingSafeEqual(ab, bb);
|
|
461
|
+
}
|
|
462
|
+
/** Escape a string for safe interpolation into HTML text content. */
|
|
463
|
+
function escapeHtml(s) {
|
|
464
|
+
return s
|
|
465
|
+
.replace(/&/g, "&")
|
|
466
|
+
.replace(/</g, "<")
|
|
467
|
+
.replace(/>/g, ">")
|
|
468
|
+
.replace(/"/g, """)
|
|
469
|
+
.replace(/'/g, "'");
|
|
470
|
+
}
|
|
471
|
+
function respondHtml(res, status, title, body) {
|
|
472
|
+
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
|
|
473
|
+
// title/body are escaped: on the error path `body` carries the OAuth
|
|
474
|
+
// error_description straight from the callback query string (attacker-
|
|
475
|
+
// controllable on the loopback URL), so interpolating it raw is reflected XSS
|
|
476
|
+
// (CodeQL js/reflected-xss). Escaping closes it; the page is plain text anyway.
|
|
477
|
+
res.end(`<html><body style="font-family:system-ui;text-align:center;padding:60px">` +
|
|
478
|
+
`<h2>${escapeHtml(title)}</h2><p>${escapeHtml(body)}</p></body></html>`);
|
|
479
|
+
}
|
|
480
|
+
/** Format a standard OAuth error response ({error, error_description}). */
|
|
481
|
+
async function oauthError(res) {
|
|
482
|
+
const body = (await res.json().catch(() => ({})));
|
|
483
|
+
if (body.error) {
|
|
484
|
+
return body.error + (body.error_description ? ` — ${body.error_description}` : "");
|
|
485
|
+
}
|
|
486
|
+
return `HTTP ${res.status}`;
|
|
487
|
+
}
|
|
488
|
+
async function safeBody(res) {
|
|
489
|
+
return (await res.text().catch(() => "")) || `HTTP ${res.status}`;
|
|
490
|
+
}
|
package/dist/lib/prompt.js
CHANGED
|
@@ -162,6 +162,11 @@ export async function askMultiSelect(question, options) {
|
|
|
162
162
|
});
|
|
163
163
|
});
|
|
164
164
|
}
|
|
165
|
+
/** Map a typed answer ("1".."n") to its option label, or null if out of range. */
|
|
166
|
+
function resolveSelection(answer, options) {
|
|
167
|
+
const idx = parseInt(answer.trim(), 10) - 1;
|
|
168
|
+
return idx >= 0 && idx < options.length ? options[idx] : null;
|
|
169
|
+
}
|
|
165
170
|
/**
|
|
166
171
|
* Single-select prompt. Displays numbered options, user enters a number.
|
|
167
172
|
* Returns selected label or null if invalid.
|
|
@@ -171,6 +176,19 @@ export async function askSelect(question, options) {
|
|
|
171
176
|
for (let i = 0; i < options.length; i++) {
|
|
172
177
|
console.log(` ${i + 1}) ${options[i]}`);
|
|
173
178
|
}
|
|
179
|
+
// Non-interactive stdin (pipe / CI / agent-driven): serve the next buffered
|
|
180
|
+
// line from the SAME shared reader askInput uses. A fresh per-prompt readline
|
|
181
|
+
// interface drops buffered lines on a pipe (MNE-269), and `rl.question` never
|
|
182
|
+
// resolves on EOF — so a non-TTY run would silently hang here. Read the
|
|
183
|
+
// shared buffer instead; on EOF there's nothing to pick, so return null and
|
|
184
|
+
// let the caller fall back.
|
|
185
|
+
if (!process.stdin.isTTY) {
|
|
186
|
+
process.stdout.write("Select: ");
|
|
187
|
+
const lines = await readPipedStdinLines();
|
|
188
|
+
const next = lines.shift();
|
|
189
|
+
process.stdout.write("\n");
|
|
190
|
+
return resolveSelection(next ?? "", options);
|
|
191
|
+
}
|
|
174
192
|
const rl = readline.createInterface({
|
|
175
193
|
input: process.stdin,
|
|
176
194
|
output: process.stdout,
|
|
@@ -178,13 +196,7 @@ export async function askSelect(question, options) {
|
|
|
178
196
|
return new Promise((resolve) => {
|
|
179
197
|
rl.question("Select: ", (answer) => {
|
|
180
198
|
rl.close();
|
|
181
|
-
|
|
182
|
-
if (idx >= 0 && idx < options.length) {
|
|
183
|
-
resolve(options[idx]);
|
|
184
|
-
}
|
|
185
|
-
else {
|
|
186
|
-
resolve(null);
|
|
187
|
-
}
|
|
199
|
+
resolve(resolveSelection(answer, options));
|
|
188
200
|
});
|
|
189
201
|
});
|
|
190
202
|
}
|