@firstdraft.com/cli 0.9.0 → 0.11.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/README.md +10 -8
- package/docs/README.md +1 -1
- package/docs/commands.md +659 -132
- package/docs/errors.md +227 -73
- package/package.json +7 -1
- package/src/agent-sentences.js +210 -0
- package/src/api-authentication.js +25 -6
- package/src/api-response.js +110 -6
- package/src/cli.js +3143 -912
- package/src/commands/account.js +97 -0
- package/src/commands/compilation.js +57 -5
- package/src/commands/login.js +246 -42
- package/src/commands/maintain.js +662 -0
- package/src/commands/note.js +204 -0
- package/src/commands/plan-compile.js +44 -77
- package/src/commands/plan-init.js +14 -1
- package/src/commands/plan-push.js +26 -12
- package/src/commands/plan-status.js +1 -1
- package/src/commands/report.js +469 -0
- package/src/commands/sketches.js +388 -0
- package/src/commands/start.js +52 -0
- package/src/compilation-artifact.js +39 -4
- package/src/credentials.js +145 -7
- package/src/oauth.js +33 -25
- package/src/plan-compile-progress.js +8 -81
- package/src/plan-state.js +325 -5
- package/src/root-output.js +13 -1
- package/src/service-client.js +513 -0
- package/src/sketch-capture.js +449 -0
- package/src/commands/plan-publish.js +0 -1146
|
@@ -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,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { lstatSync, readFileSync } from "node:fs";
|
|
3
|
+
import { reviewedSources, SketchError } from "./sketches.js";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
|
|
5
6
|
import {
|
|
@@ -19,6 +20,7 @@ import {
|
|
|
19
20
|
FirstDraftProtocolError,
|
|
20
21
|
SERVICE_ROUTES,
|
|
21
22
|
isProblemBody,
|
|
23
|
+
reviewConflict,
|
|
22
24
|
readResponseBody,
|
|
23
25
|
readResponseBytes,
|
|
24
26
|
responseMediaType,
|
|
@@ -223,6 +225,7 @@ export class CompilationArtifactResponseInvalidError extends Error {
|
|
|
223
225
|
* analysis_run_id: string,
|
|
224
226
|
* graph_version: number,
|
|
225
227
|
* head_source_sha256: string,
|
|
228
|
+
* sketch_revision_id?:string,
|
|
226
229
|
* status: string,
|
|
227
230
|
* compiler_release: string,
|
|
228
231
|
* target: {id: string, profile: string},
|
|
@@ -373,7 +376,21 @@ export async function downloadCompilation({
|
|
|
373
376
|
compilerRelease: current.compilation.compiler_release,
|
|
374
377
|
target: current.compilation.target,
|
|
375
378
|
});
|
|
376
|
-
const
|
|
379
|
+
const selected = current.compilation.sketch_revision_id
|
|
380
|
+
? reviewedSources(cwd, current.compilation.sketch_revision_id, true)
|
|
381
|
+
: undefined;
|
|
382
|
+
if (
|
|
383
|
+
selected &&
|
|
384
|
+
selected.planSha256 !== current.compilation.head_source_sha256
|
|
385
|
+
)
|
|
386
|
+
throw new SketchError(
|
|
387
|
+
"The retained Compilation and local review identify different Plans.",
|
|
388
|
+
);
|
|
389
|
+
const materialized = materializeCompilationArtifact(
|
|
390
|
+
artifact,
|
|
391
|
+
outputTarget,
|
|
392
|
+
selected?.files,
|
|
393
|
+
);
|
|
377
394
|
|
|
378
395
|
return {
|
|
379
396
|
project: current.project,
|
|
@@ -474,6 +491,8 @@ export async function cancelCompilation({
|
|
|
474
491
|
/**
|
|
475
492
|
* @typedef {object} CompileAndDownloadOptions
|
|
476
493
|
* @property {string} cwd
|
|
494
|
+
* @property {string} [revision]
|
|
495
|
+
* @property {Map<string,Buffer>} [sketchFiles]
|
|
477
496
|
* @property {string} expectedEtag
|
|
478
497
|
* @property {CurrentCompilationIdentity} expected
|
|
479
498
|
* @property {string} output
|
|
@@ -497,6 +516,8 @@ export async function cancelCompilation({
|
|
|
497
516
|
export async function compileAndDownload({
|
|
498
517
|
cwd,
|
|
499
518
|
expectedEtag,
|
|
519
|
+
revision,
|
|
520
|
+
sketchFiles,
|
|
500
521
|
expected,
|
|
501
522
|
output,
|
|
502
523
|
outputTarget: suppliedOutputTarget,
|
|
@@ -528,6 +549,7 @@ export async function compileAndDownload({
|
|
|
528
549
|
onProgress({ phase: "compilation", status: "waiting" });
|
|
529
550
|
const initial = await startCompilation({
|
|
530
551
|
...context,
|
|
552
|
+
revision,
|
|
531
553
|
expected,
|
|
532
554
|
fetchFunction,
|
|
533
555
|
createRequestSignal,
|
|
@@ -591,9 +613,21 @@ export async function compileAndDownload({
|
|
|
591
613
|
compilerRelease: current.compilation.compiler_release,
|
|
592
614
|
target: current.compilation.target,
|
|
593
615
|
});
|
|
616
|
+
if (revision && typeof outputTarget !== "string") {
|
|
617
|
+
try {
|
|
618
|
+
reviewedSources(cwd, revision);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
if (!(error instanceof SketchError)) throw error;
|
|
621
|
+
throw new CompilationMaterializationError(
|
|
622
|
+
"Restore the reviewed sources before adopting this directory.",
|
|
623
|
+
{ cause: error, reason: "reviewed_sources_changed" },
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
594
627
|
const materialized = materializeCompilationArtifact(
|
|
595
628
|
artifact,
|
|
596
629
|
outputTarget,
|
|
630
|
+
sketchFiles,
|
|
597
631
|
);
|
|
598
632
|
|
|
599
633
|
return {
|
|
@@ -676,7 +710,7 @@ function readContext({ cwd, compilationId, fileSystem }) {
|
|
|
676
710
|
}
|
|
677
711
|
|
|
678
712
|
const state = readPlanState({ cwd, fileSystem });
|
|
679
|
-
if (state.api_url === undefined) {
|
|
713
|
+
if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
|
|
680
714
|
throw new CompilationNotPushedError(
|
|
681
715
|
"The local Foundation Plan has not been pushed.",
|
|
682
716
|
);
|
|
@@ -693,6 +727,7 @@ function readContext({ cwd, compilationId, fileSystem }) {
|
|
|
693
727
|
* @param {object} options
|
|
694
728
|
* @param {string} options.apiUrl
|
|
695
729
|
* @param {string} options.projectId
|
|
730
|
+
* @param {string} [options.revision]
|
|
696
731
|
* @param {string} options.etag
|
|
697
732
|
* @param {CurrentCompilationIdentity} options.expected
|
|
698
733
|
* @param {typeof globalThis.fetch} options.fetchFunction
|
|
@@ -702,6 +737,7 @@ async function startCompilation({
|
|
|
702
737
|
apiUrl,
|
|
703
738
|
projectId,
|
|
704
739
|
etag,
|
|
740
|
+
revision,
|
|
705
741
|
expected,
|
|
706
742
|
fetchFunction,
|
|
707
743
|
createRequestSignal,
|
|
@@ -716,6 +752,7 @@ async function startCompilation({
|
|
|
716
752
|
headers: {
|
|
717
753
|
Accept: "application/json, application/problem+json",
|
|
718
754
|
"If-Match": etag,
|
|
755
|
+
...(revision ? { "FirstDraft-Sketch-Revision": revision } : {}),
|
|
719
756
|
},
|
|
720
757
|
redirect: "error",
|
|
721
758
|
signal: createRequestSignal(REQUEST_TIMEOUT_MS),
|
|
@@ -749,6 +786,7 @@ async function startCompilation({
|
|
|
749
786
|
responseMediaType(response) !== "application/json" ||
|
|
750
787
|
parsed === null ||
|
|
751
788
|
response.headers.get("location") !== parsed.compilation.status_path ||
|
|
789
|
+
parsed.compilation.sketch_revision_id !== revision ||
|
|
752
790
|
!matchesExpectedCompilation(parsed, expected)
|
|
753
791
|
) {
|
|
754
792
|
throw new CompilationRequestOutcomeUnknownError(response.status);
|
|
@@ -826,7 +864,7 @@ async function readCompilationStatus({
|
|
|
826
864
|
function parseStartedCompilationResponse(value, projectId) {
|
|
827
865
|
if (
|
|
828
866
|
!hasExactKeySet(value, RESPONSE_KEYS) ||
|
|
829
|
-
!
|
|
867
|
+
!isRecord(value.compilation) ||
|
|
830
868
|
!isUuidV7(value.compilation.id)
|
|
831
869
|
) {
|
|
832
870
|
return null;
|
|
@@ -939,7 +977,13 @@ function parseCompilationResponse(value, projectId, compilationId) {
|
|
|
939
977
|
if (
|
|
940
978
|
!hasExactKeySet(value, RESPONSE_KEYS) ||
|
|
941
979
|
!hasExactKeySet(value.project, PROJECT_KEYS) ||
|
|
942
|
-
!
|
|
980
|
+
!isRecord(value.compilation) ||
|
|
981
|
+
!hasExactKeySet(
|
|
982
|
+
value.compilation,
|
|
983
|
+
Object.hasOwn(value.compilation, "sketch_revision_id")
|
|
984
|
+
? [...COMPILATION_KEYS, "sketch_revision_id"]
|
|
985
|
+
: COMPILATION_KEYS,
|
|
986
|
+
)
|
|
943
987
|
) {
|
|
944
988
|
return null;
|
|
945
989
|
}
|
|
@@ -949,6 +993,8 @@ function parseCompilationResponse(value, projectId, compilationId) {
|
|
|
949
993
|
if (
|
|
950
994
|
project.id !== projectId ||
|
|
951
995
|
!isGraphVersion(project.graph_version) ||
|
|
996
|
+
(compilation.sketch_revision_id !== undefined &&
|
|
997
|
+
!isUuidV7(compilation.sketch_revision_id)) ||
|
|
952
998
|
compilation.id !== compilationId ||
|
|
953
999
|
!isUuidV7(compilation.id) ||
|
|
954
1000
|
!isUuidV7(compilation.analysis_run_id) ||
|
|
@@ -994,6 +1040,9 @@ function parseCompilationResponse(value, projectId, compilationId) {
|
|
|
994
1040
|
project: { id: project.id, graph_version: project.graph_version },
|
|
995
1041
|
compilation: {
|
|
996
1042
|
id: compilation.id,
|
|
1043
|
+
...(isUuidV7(compilation.sketch_revision_id)
|
|
1044
|
+
? { sketch_revision_id: compilation.sketch_revision_id }
|
|
1045
|
+
: {}),
|
|
997
1046
|
analysis_run_id: compilation.analysis_run_id,
|
|
998
1047
|
graph_version: compilation.graph_version,
|
|
999
1048
|
head_source_sha256: /** @type {string} */ (
|
|
@@ -1137,6 +1186,8 @@ function sameCompilation(first, current) {
|
|
|
1137
1186
|
current.project.id === first.project.id &&
|
|
1138
1187
|
current.project.graph_version === first.project.graph_version &&
|
|
1139
1188
|
current.compilation.id === first.compilation.id &&
|
|
1189
|
+
current.compilation.sketch_revision_id ===
|
|
1190
|
+
first.compilation.sketch_revision_id &&
|
|
1140
1191
|
current.compilation.analysis_run_id === first.compilation.analysis_run_id &&
|
|
1141
1192
|
current.compilation.graph_version === first.compilation.graph_version &&
|
|
1142
1193
|
current.compilation.head_source_sha256 ===
|
|
@@ -1195,8 +1246,9 @@ function requiresRetainedRecovery(error) {
|
|
|
1195
1246
|
|
|
1196
1247
|
/** @param {Response} response @param {unknown} body */
|
|
1197
1248
|
function safeProblem(response, body) {
|
|
1249
|
+
const conflict = reviewConflict(response, body);
|
|
1250
|
+
if (conflict) return conflict;
|
|
1198
1251
|
if (!isRecord(body) || !isProblemBody(response, body)) return null;
|
|
1199
|
-
|
|
1200
1252
|
return {
|
|
1201
1253
|
...(body.type === "about:blank" ? { type: body.type } : {}),
|
|
1202
1254
|
title: body.title,
|
package/src/commands/login.js
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
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({
|
|
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 });
|