@firstdraft.com/cli 0.8.2 → 0.10.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.
@@ -0,0 +1,97 @@
1
+ import {
2
+ FirstDraftNetworkError,
3
+ FirstDraftProtocolError,
4
+ SERVICE_ROUTES,
5
+ isProblemBody,
6
+ problemProjection,
7
+ readResponseBody,
8
+ responseMediaType,
9
+ sendRequest,
10
+ serviceEndpoint,
11
+ } from "../api-response.js";
12
+
13
+ const REQUEST_TIMEOUT_MS = 30_000;
14
+
15
+ export class AccountUnavailableError extends Error {
16
+ /**
17
+ * @param {number | undefined} status
18
+ * @param {Record<string, unknown> | null} [response]
19
+ */
20
+ constructor(status, response = null) {
21
+ super("The account could not be read.");
22
+ this.status = status;
23
+ this.response = response;
24
+ }
25
+ }
26
+
27
+ export class AccountResponseInvalidError extends Error {
28
+ /** @param {number} status */
29
+ constructor(status) {
30
+ super("The account response is invalid.");
31
+ this.status = status;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * @typedef {object} ReadAccountOptions
37
+ * @property {string} origin
38
+ * @property {typeof globalThis.fetch} [fetchFunction]
39
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
40
+ */
41
+
42
+ /**
43
+ * Reads whether the signed-in account sends progress and failure reports.
44
+ * Only the person turns reports on, on the login approval page.
45
+ *
46
+ * @param {ReadAccountOptions} options
47
+ * @returns {Promise<{reports: "on" | "off"}>}
48
+ */
49
+ export async function readAccount({
50
+ origin,
51
+ fetchFunction = globalThis.fetch,
52
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
53
+ }) {
54
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.readAccount, origin, {});
55
+ let response;
56
+ let body;
57
+ try {
58
+ response = await sendRequest(fetchFunction, endpoint, {
59
+ headers: { Accept: "application/json, application/problem+json" },
60
+ redirect: "error",
61
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
62
+ });
63
+ body = await readResponseBody(response);
64
+ } catch (error) {
65
+ if (error instanceof FirstDraftNetworkError) {
66
+ throw new AccountUnavailableError(error.status);
67
+ }
68
+ if (error instanceof FirstDraftProtocolError) {
69
+ throw error.status >= 200 && error.status < 300
70
+ ? new AccountResponseInvalidError(error.status)
71
+ : new AccountUnavailableError(error.status);
72
+ }
73
+ throw error;
74
+ }
75
+
76
+ if (response.status !== 200) {
77
+ if (response.ok) throw new AccountResponseInvalidError(response.status);
78
+
79
+ throw new AccountUnavailableError(
80
+ response.status,
81
+ isProblemBody(response, body) ? problemProjection(body) : null,
82
+ );
83
+ }
84
+
85
+ // Other keys are ignored so the Service can add account facts without
86
+ // breaking this command; only the validated value is printed.
87
+ if (
88
+ responseMediaType(response) !== "application/json" ||
89
+ typeof body !== "object" ||
90
+ body === null ||
91
+ (body.reports !== "on" && body.reports !== "off")
92
+ ) {
93
+ throw new AccountResponseInvalidError(response.status);
94
+ }
95
+
96
+ return { reports: body.reports };
97
+ }
@@ -1,4 +1,3 @@
1
- import { hostname as osHostname } from "node:os";
2
1
  import { setTimeout as delay } from "node:timers/promises";
3
2
 
4
3
  import {
@@ -9,29 +8,52 @@ import {
9
8
  CredentialsInvalidError,
10
9
  CredentialsLockedError,
11
10
  credentialsPath,
11
+ deleteDeviceLogin,
12
+ deviceLoginPath,
12
13
  readCredentials,
14
+ readDeviceLogin,
13
15
  writeCredential,
16
+ writeDeviceLogin,
14
17
  } from "../credentials.js";
15
18
  import { isFileSystemError } from "../file-system.js";
16
19
  import {
17
20
  LOOPBACK_TIMEOUT_MS,
18
21
  OAuthError,
22
+ SLOW_DOWN_INCREMENT_MS,
19
23
  authorizationUrl,
20
24
  createPkcePair,
21
25
  createState,
22
26
  exchangeAuthorizationCode,
23
27
  pollDeviceToken,
24
28
  requestDeviceAuthorization,
29
+ requestDeviceToken,
25
30
  startLoopbackServer,
26
31
  } from "../oauth.js";
27
32
  import { normalizeApiUrl } from "../plan-state.js";
28
33
  import { DEFAULT_API_URL } from "./plan-push.js";
29
34
 
30
- const MAX_DEVICE_NAME_LENGTH = 100;
35
+ /** How long `login --finish` keeps asking before it says it is still waiting. */
36
+ export const FINISH_WAIT_MS = 15_000;
37
+
38
+ // The answers after which a device grant can never yield a token, so its
39
+ // saved device login is removed.
40
+ const ENDED_GRANT_CODES = ["access_denied", "expired_token", "invalid_grant"];
31
41
 
32
42
  export class LoginDeniedError extends Error {}
33
43
  export class LoginExpiredError extends Error {}
34
44
 
45
+ /** No device login started with --no-wait is waiting for the origin. */
46
+ export class LoginNotStartedError extends Error {}
47
+
48
+ /** First Draft has not confirmed that the person approved the device login. */
49
+ export class LoginPendingError extends Error {
50
+ /** @param {import("../credentials.js").DeviceLogin} login */
51
+ constructor(login) {
52
+ super("The device login is still waiting for approval.");
53
+ this.login = login;
54
+ }
55
+ }
56
+
35
57
  export class LoginFailedError extends Error {
36
58
  /**
37
59
  * @param {string} message
@@ -67,7 +89,6 @@ export function resolveLoginOrigin({ apiUrl, staging = false }) {
67
89
  * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
68
90
  * @property {(delayMs: number, signal?: AbortSignal) => Promise<void>} [sleep]
69
91
  * @property {() => number} [now]
70
- * @property {() => string} [hostname]
71
92
  * @property {import("../oauth.js").StartLoopbackServer} [startLoopback]
72
93
  * @property {import("../credentials.js").CredentialStore} [credentials]
73
94
  */
@@ -86,36 +107,23 @@ export async function login({
86
107
  createRequestSignal,
87
108
  sleep = defaultSleep,
88
109
  now = Date.now,
89
- hostname = osHostname,
90
110
  startLoopback = startLoopbackServer,
91
111
  credentials = {},
92
112
  }) {
93
113
  // Reject an unreadable or invalid store before any network request.
94
114
  // A later write can still fail after a token has been issued.
95
115
  readStore(credentials);
96
- const deviceName = safeDeviceName(hostname);
97
116
  const request = { origin, fetchFunction, createRequestSignal };
98
117
 
99
118
  /** @param {import("../oauth.js").AccessToken} token */
100
- const save = (token) => {
101
- try {
102
- writeCredential(credentials, origin, {
103
- access_token: token.access_token,
104
- token_type: token.token_type,
105
- created_at: new Date(now()).toISOString(),
106
- });
107
- } catch (error) {
108
- throw credentialsError(error, credentials, "write");
109
- }
110
- };
119
+ const save = (token) => saveToken(credentials, origin, token, now);
111
120
 
112
121
  try {
113
122
  if (device) {
114
- save(await deviceLogin({ ...request, deviceName, prompt, sleep, now }));
123
+ save(await deviceLogin({ ...request, prompt, sleep, now }));
115
124
  } else {
116
125
  await browserLogin({
117
126
  ...request,
118
- deviceName,
119
127
  prompt,
120
128
  sleep,
121
129
  startLoopback,
@@ -130,7 +138,6 @@ export async function login({
130
138
 
131
139
  /**
132
140
  * @param {import("../oauth.js").RequestOptions & {
133
- * deviceName: string | undefined,
134
141
  * prompt: (text: string) => void,
135
142
  * sleep: (delayMs: number, signal?: AbortSignal) => Promise<void>,
136
143
  * startLoopback: import("../oauth.js").StartLoopbackServer,
@@ -138,7 +145,6 @@ export async function login({
138
145
  * }} options
139
146
  */
140
147
  async function browserLogin({
141
- deviceName,
142
148
  prompt,
143
149
  sleep,
144
150
  startLoopback,
@@ -165,7 +171,6 @@ async function browserLogin({
165
171
  redirectUri: listener.redirectUri,
166
172
  state,
167
173
  challenge,
168
- deviceName,
169
174
  });
170
175
  prompt(
171
176
  `To log in to ${request.origin}, open this URL in your browser:\n\n ${url}\n\n` +
@@ -210,17 +215,13 @@ async function browserLogin({
210
215
 
211
216
  /**
212
217
  * @param {import("../oauth.js").RequestOptions & {
213
- * deviceName: string | undefined,
214
218
  * prompt: (text: string) => void,
215
219
  * sleep: (delayMs: number) => Promise<void>,
216
220
  * now: () => number,
217
221
  * }} options
218
222
  */
219
- async function deviceLogin({ deviceName, prompt, sleep, now, ...request }) {
220
- const authorization = await requestDeviceAuthorization({
221
- ...request,
222
- deviceName,
223
- });
223
+ async function deviceLogin({ prompt, sleep, now, ...request }) {
224
+ const authorization = await requestDeviceAuthorization(request);
224
225
  prompt(
225
226
  `To log in to ${request.origin}, open this URL in a browser on any device:\n\n` +
226
227
  ` ${authorization.verificationUri}\n\n` +
@@ -240,6 +241,224 @@ async function deviceLogin({ deviceName, prompt, sleep, now, ...request }) {
240
241
  });
241
242
  }
242
243
 
244
+ /**
245
+ * @typedef {object} DeviceLoginOptions
246
+ * @property {string} origin
247
+ * @property {typeof globalThis.fetch} [fetchFunction]
248
+ * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
249
+ * @property {(delayMs: number, signal?: AbortSignal) => Promise<void>} [sleep]
250
+ * @property {() => number} [now]
251
+ * @property {import("../credentials.js").CredentialStore} [credentials]
252
+ */
253
+
254
+ /**
255
+ * The first step of a device login that an agent can run: asks First Draft
256
+ * for a device grant, saves what `finishDeviceLogin` needs, and returns
257
+ * without waiting for approval. The saved login replaces any other.
258
+ *
259
+ * @param {DeviceLoginOptions} options
260
+ * @returns {Promise<import("../credentials.js").DeviceLogin & {expiresIn: number}>}
261
+ */
262
+ export async function startDeviceLogin({
263
+ origin,
264
+ fetchFunction,
265
+ createRequestSignal,
266
+ now = Date.now,
267
+ credentials = {},
268
+ }) {
269
+ // The token is saved there later, so an unusable file stops the login
270
+ // before the person is asked to approve it.
271
+ readStore(credentials);
272
+
273
+ let authorization;
274
+ try {
275
+ authorization = await requestDeviceAuthorization({
276
+ origin,
277
+ fetchFunction,
278
+ createRequestSignal,
279
+ });
280
+ } catch (error) {
281
+ throw loginError(error);
282
+ }
283
+
284
+ const startedAt = now();
285
+ const login = {
286
+ origin,
287
+ deviceCode: authorization.deviceCode,
288
+ userCode: authorization.userCode,
289
+ verificationUri: authorization.verificationUri,
290
+ verificationUriComplete: authorization.verificationUriComplete,
291
+ interval: authorization.interval,
292
+ expiresAt: startedAt + authorization.expiresIn * 1000,
293
+ // First Draft answers a grant's first poll whenever it comes.
294
+ nextPollAt: startedAt,
295
+ };
296
+ withDeviceLogin(credentials, () => writeDeviceLogin(credentials, login));
297
+ return { ...login, expiresIn: authorization.expiresIn };
298
+ }
299
+
300
+ /**
301
+ * The second step: polls the waiting device login at its interval, for at
302
+ * most FINISH_WAIT_MS from the start of the command with each request
303
+ * included, and saves the token once the person has approved. Removes the
304
+ * saved device login when the grant has ended, and otherwise keeps it with
305
+ * the next time First Draft accepts a poll.
306
+ *
307
+ * @param {DeviceLoginOptions} options
308
+ * @returns {Promise<{origin: string, leftover: string | null}>} `leftover`
309
+ * names the spent device login file when it could not be removed
310
+ */
311
+ export async function finishDeviceLogin({
312
+ origin,
313
+ fetchFunction,
314
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs ?? 0),
315
+ sleep = defaultSleep,
316
+ now = Date.now,
317
+ credentials = {},
318
+ }) {
319
+ const deadline = now() + FINISH_WAIT_MS;
320
+ const waiting = withDeviceLogin(credentials, () =>
321
+ readDeviceLogin(credentials),
322
+ );
323
+ if (waiting === null || waiting.origin !== origin) {
324
+ throw new LoginNotStartedError("No device login is waiting.");
325
+ }
326
+ readStore(credentials);
327
+
328
+ const expired = () => {
329
+ withDeviceLogin(credentials, () => deleteDeviceLogin(credentials));
330
+ return new LoginExpiredError("The device code expired.");
331
+ };
332
+ let { interval } = waiting;
333
+ // Never more than one interval away, even after the clock moved back.
334
+ let nextPollAt = Math.min(waiting.nextPollAt, now() + interval * 1000);
335
+ const keep = () => {
336
+ nextPollAt = now() + interval * 1000;
337
+ withDeviceLogin(credentials, () =>
338
+ writeDeviceLogin(credentials, { ...waiting, interval, nextPollAt }),
339
+ );
340
+ };
341
+
342
+ while (true) {
343
+ if (now() >= waiting.expiresAt) throw expired();
344
+ if (nextPollAt >= deadline || nextPollAt >= waiting.expiresAt) {
345
+ throw new LoginPendingError({ ...waiting, interval, nextPollAt });
346
+ }
347
+ const delayMs = nextPollAt - now();
348
+ if (delayMs > 0) await sleep(delayMs);
349
+ if (now() >= waiting.expiresAt) throw expired();
350
+ // A timer can wake late; no poll starts after the wait has ended.
351
+ const remainingMs = deadline - now();
352
+ if (remainingMs <= 0) {
353
+ throw new LoginPendingError({ ...waiting, interval, nextPollAt });
354
+ }
355
+
356
+ let result;
357
+ try {
358
+ result = await requestDeviceToken({
359
+ origin,
360
+ fetchFunction,
361
+ createRequestSignal: () => createRequestSignal(remainingMs),
362
+ deviceCode: waiting.deviceCode,
363
+ });
364
+ } catch (error) {
365
+ if (
366
+ error instanceof OAuthError &&
367
+ error.code !== undefined &&
368
+ ENDED_GRANT_CODES.includes(error.code)
369
+ ) {
370
+ withDeviceLogin(credentials, () => deleteDeviceLogin(credentials));
371
+ } else {
372
+ // The poll may have reached First Draft, so the next one waits.
373
+ keep();
374
+ }
375
+ throw loginError(error);
376
+ }
377
+
378
+ if (!("pending" in result)) {
379
+ // The grant is spent once it issues a token, so its file goes first,
380
+ // whether or not the token can then be saved.
381
+ const removed = removeSpentDeviceLogin(credentials);
382
+ saveToken(credentials, origin, result, now);
383
+ return {
384
+ origin,
385
+ leftover: removed ? null : deviceLoginPath(credentials),
386
+ };
387
+ }
388
+
389
+ if (result.pending === "slow_down") {
390
+ interval += SLOW_DOWN_INCREMENT_MS / 1000;
391
+ }
392
+ // A pending answer that arrived after the expiry is an expired grant.
393
+ if (now() >= waiting.expiresAt) throw expired();
394
+ keep();
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Removes a device login whose grant has issued its token. A spent device
400
+ * code authenticates nothing, so a file that cannot be removed does not fail
401
+ * the login; the caller says where it is.
402
+ *
403
+ * @param {import("../credentials.js").CredentialStore} credentials
404
+ */
405
+ function removeSpentDeviceLogin(credentials) {
406
+ try {
407
+ deleteDeviceLogin(credentials);
408
+ return true;
409
+ } catch (error) {
410
+ if (!isFileSystemError(error)) throw error;
411
+ return false;
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Runs an operation on the saved device login file, reporting a file-system
417
+ * failure or a malformed file as a failed login.
418
+ *
419
+ * @template T
420
+ * @param {import("../credentials.js").CredentialStore} credentials
421
+ * @param {() => T} callback
422
+ * @returns {T}
423
+ */
424
+ function withDeviceLogin(credentials, callback) {
425
+ try {
426
+ return callback();
427
+ } catch (error) {
428
+ if (
429
+ !(error instanceof CredentialsInvalidError) &&
430
+ !isFileSystemError(error)
431
+ )
432
+ throw error;
433
+ throw new LoginFailedError("The device login file could not be used.", {
434
+ reason:
435
+ error instanceof CredentialsInvalidError
436
+ ? "device_login_invalid"
437
+ : "device_login_unavailable",
438
+ credentialsPath: deviceLoginPath(credentials),
439
+ cause: error,
440
+ });
441
+ }
442
+ }
443
+
444
+ /**
445
+ * @param {import("../credentials.js").CredentialStore} credentials
446
+ * @param {string} origin
447
+ * @param {import("../oauth.js").AccessToken} token
448
+ * @param {() => number} now
449
+ */
450
+ function saveToken(credentials, origin, token, now) {
451
+ try {
452
+ writeCredential(credentials, origin, {
453
+ access_token: token.access_token,
454
+ token_type: token.token_type,
455
+ created_at: new Date(now()).toISOString(),
456
+ });
457
+ } catch (error) {
458
+ throw credentialsError(error, credentials, "write");
459
+ }
460
+ }
461
+
243
462
  /** @param {import("../credentials.js").CredentialStore} credentials */
244
463
  function readStore(credentials) {
245
464
  try {
@@ -293,21 +512,6 @@ function loginError(error) {
293
512
  });
294
513
  }
295
514
 
296
- /** @param {() => string} hostname */
297
- function safeDeviceName(hostname) {
298
- let name;
299
- try {
300
- name = hostname();
301
- } catch {
302
- return undefined;
303
- }
304
- // eslint-disable-next-line no-control-regex
305
- const cleaned = name.replace(/[\u0000-\u001f\u007f]/g, "").trim();
306
- return cleaned.length === 0
307
- ? undefined
308
- : cleaned.slice(0, MAX_DEVICE_NAME_LENGTH);
309
- }
310
-
311
515
  /** @param {number} delayMs @param {AbortSignal} [signal] */
312
516
  function defaultSleep(delayMs, signal) {
313
517
  return delay(delayMs, undefined, { signal });