@firstdraft.com/cli 0.8.0 → 0.8.2
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 +22 -26
- package/docs/README.md +9 -14
- package/docs/commands.md +237 -43
- package/docs/errors.md +75 -9
- package/package.json +6 -4
- package/src/api-authentication.js +55 -13
- package/src/api-response.js +77 -3
- package/src/cli.js +558 -7
- package/src/commands/compilation.js +121 -9
- package/src/commands/login.js +314 -0
- package/src/commands/logout.js +107 -0
- package/src/commands/plan-publish.js +16 -13
- package/src/commands/plan-push.js +5 -5
- package/src/commands/plan-status.js +5 -5
- package/src/credentials.js +343 -0
- package/src/oauth.js +565 -0
- package/RELEASING.md +0 -118
- package/docs/release-history.md +0 -77
|
@@ -17,11 +17,13 @@ import {
|
|
|
17
17
|
import {
|
|
18
18
|
FirstDraftNetworkError,
|
|
19
19
|
FirstDraftProtocolError,
|
|
20
|
+
SERVICE_ROUTES,
|
|
20
21
|
isProblemBody,
|
|
21
22
|
readResponseBody,
|
|
22
23
|
readResponseBytes,
|
|
23
24
|
responseMediaType,
|
|
24
25
|
sendRequest,
|
|
26
|
+
serviceEndpoint,
|
|
25
27
|
} from "../api-response.js";
|
|
26
28
|
import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
|
|
27
29
|
|
|
@@ -129,6 +131,30 @@ export class CompilationStatusInvalidError extends Error {
|
|
|
129
131
|
}
|
|
130
132
|
}
|
|
131
133
|
|
|
134
|
+
export class CompilationCancelRejectedError extends Error {
|
|
135
|
+
/**
|
|
136
|
+
* @param {number} status
|
|
137
|
+
* @param {Record<string, unknown>} response
|
|
138
|
+
*/
|
|
139
|
+
constructor(status, response) {
|
|
140
|
+
super("First Draft rejected the cancellation.");
|
|
141
|
+
this.status = status;
|
|
142
|
+
this.response = response;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export class CompilationCancelUnavailableError extends Error {
|
|
147
|
+
/**
|
|
148
|
+
* @param {number | undefined} status
|
|
149
|
+
* @param {Record<string, unknown> | null} [response]
|
|
150
|
+
*/
|
|
151
|
+
constructor(status, response = null) {
|
|
152
|
+
super("The cancellation could not be confirmed.");
|
|
153
|
+
this.status = status;
|
|
154
|
+
this.response = response;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
132
158
|
export class CompilationChangedError extends Error {
|
|
133
159
|
/** @param {CompilationResponse} current */
|
|
134
160
|
constructor(current) {
|
|
@@ -332,6 +358,8 @@ export async function downloadCompilation({
|
|
|
332
358
|
);
|
|
333
359
|
const source = await downloadArtifact({
|
|
334
360
|
apiUrl: context.apiUrl,
|
|
361
|
+
projectId: context.projectId,
|
|
362
|
+
compilationId: current.compilation.id,
|
|
335
363
|
metadata,
|
|
336
364
|
fetchFunction,
|
|
337
365
|
createRequestSignal,
|
|
@@ -357,6 +385,82 @@ export async function downloadCompilation({
|
|
|
357
385
|
}
|
|
358
386
|
}
|
|
359
387
|
|
|
388
|
+
/**
|
|
389
|
+
* @typedef {object} CompilationCancelOptions
|
|
390
|
+
* @property {string} cwd
|
|
391
|
+
* @property {string} compilationId
|
|
392
|
+
* @property {typeof globalThis.fetch} [fetchFunction]
|
|
393
|
+
* @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem]
|
|
394
|
+
* @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
|
|
395
|
+
*/
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Cancel one queued or running Compilation of the local Project. The Service
|
|
399
|
+
* answers a repeated cancel with the same cancelled Compilation and refuses a
|
|
400
|
+
* succeeded or failed one without changing it, so an unconfirmed outcome is
|
|
401
|
+
* safe to repeat rather than an ambiguous mutation.
|
|
402
|
+
*
|
|
403
|
+
* @param {CompilationCancelOptions} options
|
|
404
|
+
* @returns {Promise<CompilationResponse>}
|
|
405
|
+
*/
|
|
406
|
+
export async function cancelCompilation({
|
|
407
|
+
cwd,
|
|
408
|
+
compilationId,
|
|
409
|
+
fetchFunction = globalThis.fetch,
|
|
410
|
+
fileSystem,
|
|
411
|
+
createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
|
|
412
|
+
}) {
|
|
413
|
+
const { apiUrl, projectId } = readContext({ cwd, compilationId, fileSystem });
|
|
414
|
+
const endpoint = serviceEndpoint(SERVICE_ROUTES.cancelCompilation, apiUrl, {
|
|
415
|
+
project_id: projectId,
|
|
416
|
+
compilation_id: compilationId,
|
|
417
|
+
});
|
|
418
|
+
let response;
|
|
419
|
+
let body;
|
|
420
|
+
try {
|
|
421
|
+
response = await sendRequest(fetchFunction, endpoint, {
|
|
422
|
+
headers: { Accept: "application/json, application/problem+json" },
|
|
423
|
+
redirect: "error",
|
|
424
|
+
signal: createRequestSignal(REQUEST_TIMEOUT_MS),
|
|
425
|
+
});
|
|
426
|
+
body = await readResponseBody(response);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
if (error instanceof FirstDraftNetworkError) {
|
|
429
|
+
throw new CompilationCancelUnavailableError(error.status);
|
|
430
|
+
}
|
|
431
|
+
// An oversized error body leaves the outcome as unconfirmed as any other
|
|
432
|
+
// failed response; only an oversized success breaks the contract.
|
|
433
|
+
if (error instanceof FirstDraftProtocolError) {
|
|
434
|
+
throw error.status >= 200 && error.status < 300
|
|
435
|
+
? new CompilationStatusInvalidError(error.status)
|
|
436
|
+
: new CompilationCancelUnavailableError(error.status);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
throw error;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (response.status !== 200) {
|
|
443
|
+
if (response.ok) throw new CompilationStatusInvalidError(response.status);
|
|
444
|
+
|
|
445
|
+
const problem = safeProblem(response, body);
|
|
446
|
+
if (problem !== null && response.status !== 408 && response.status < 500) {
|
|
447
|
+
throw new CompilationCancelRejectedError(response.status, problem);
|
|
448
|
+
}
|
|
449
|
+
throw new CompilationCancelUnavailableError(response.status, problem);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const parsed = parseCompilationResponse(body, projectId, compilationId);
|
|
453
|
+
if (
|
|
454
|
+
responseMediaType(response) !== "application/json" ||
|
|
455
|
+
parsed === null ||
|
|
456
|
+
parsed.compilation.status !== "cancelled"
|
|
457
|
+
) {
|
|
458
|
+
throw new CompilationStatusInvalidError(response.status);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return parsed;
|
|
462
|
+
}
|
|
463
|
+
|
|
360
464
|
/**
|
|
361
465
|
* @typedef {object} CurrentCompilationIdentity
|
|
362
466
|
* @property {string} projectId
|
|
@@ -472,6 +576,8 @@ export async function compileAndDownload({
|
|
|
472
576
|
);
|
|
473
577
|
const source = await downloadArtifact({
|
|
474
578
|
apiUrl: context.apiUrl,
|
|
579
|
+
projectId: context.projectId,
|
|
580
|
+
compilationId: current.compilation.id,
|
|
475
581
|
metadata,
|
|
476
582
|
fetchFunction,
|
|
477
583
|
createRequestSignal,
|
|
@@ -600,12 +706,13 @@ async function startCompilation({
|
|
|
600
706
|
fetchFunction,
|
|
601
707
|
createRequestSignal,
|
|
602
708
|
}) {
|
|
603
|
-
const endpoint =
|
|
709
|
+
const endpoint = serviceEndpoint(SERVICE_ROUTES.startCompilation, apiUrl, {
|
|
710
|
+
project_id: projectId,
|
|
711
|
+
});
|
|
604
712
|
let response;
|
|
605
713
|
let body;
|
|
606
714
|
try {
|
|
607
715
|
response = await sendRequest(fetchFunction, endpoint, {
|
|
608
|
-
method: "POST",
|
|
609
716
|
headers: {
|
|
610
717
|
Accept: "application/json, application/problem+json",
|
|
611
718
|
"If-Match": etag,
|
|
@@ -667,15 +774,14 @@ async function readCompilationStatus({
|
|
|
667
774
|
createRequestSignal,
|
|
668
775
|
requestTimeout,
|
|
669
776
|
}) {
|
|
670
|
-
const endpoint =
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
);
|
|
777
|
+
const endpoint = serviceEndpoint(SERVICE_ROUTES.readCompilation, apiUrl, {
|
|
778
|
+
project_id: projectId,
|
|
779
|
+
compilation_id: compilationId,
|
|
780
|
+
});
|
|
674
781
|
let response;
|
|
675
782
|
let body;
|
|
676
783
|
try {
|
|
677
784
|
response = await sendRequest(fetchFunction, endpoint, {
|
|
678
|
-
method: "GET",
|
|
679
785
|
headers: { Accept: "application/json, application/problem+json" },
|
|
680
786
|
redirect: "error",
|
|
681
787
|
signal: createRequestSignal(requestTimeout),
|
|
@@ -749,22 +855,28 @@ function matchesExpectedCompilation(current, expected) {
|
|
|
749
855
|
/**
|
|
750
856
|
* @param {object} options
|
|
751
857
|
* @param {string} options.apiUrl
|
|
858
|
+
* @param {string} options.projectId
|
|
859
|
+
* @param {string} options.compilationId
|
|
752
860
|
* @param {{path: string, sha256: string, media_type: string, byte_size: number}} options.metadata
|
|
753
861
|
* @param {typeof globalThis.fetch} options.fetchFunction
|
|
754
862
|
* @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
|
|
755
863
|
*/
|
|
756
864
|
async function downloadArtifact({
|
|
757
865
|
apiUrl,
|
|
866
|
+
projectId,
|
|
867
|
+
compilationId,
|
|
758
868
|
metadata,
|
|
759
869
|
fetchFunction,
|
|
760
870
|
createRequestSignal,
|
|
761
871
|
}) {
|
|
762
|
-
const endpoint =
|
|
872
|
+
const endpoint = serviceEndpoint(SERVICE_ROUTES.downloadArtifact, apiUrl, {
|
|
873
|
+
project_id: projectId,
|
|
874
|
+
compilation_id: compilationId,
|
|
875
|
+
});
|
|
763
876
|
let response;
|
|
764
877
|
let source;
|
|
765
878
|
try {
|
|
766
879
|
response = await sendRequest(fetchFunction, endpoint, {
|
|
767
|
-
method: "GET",
|
|
768
880
|
headers: {
|
|
769
881
|
Accept: `${ARTIFACT_MEDIA_TYPE}, application/problem+json`,
|
|
770
882
|
},
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { hostname as osHostname } from "node:os";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
STAGING_API_URL,
|
|
6
|
+
assertStagingSelection,
|
|
7
|
+
} from "../api-authentication.js";
|
|
8
|
+
import {
|
|
9
|
+
CredentialsInvalidError,
|
|
10
|
+
CredentialsLockedError,
|
|
11
|
+
credentialsPath,
|
|
12
|
+
readCredentials,
|
|
13
|
+
writeCredential,
|
|
14
|
+
} from "../credentials.js";
|
|
15
|
+
import { isFileSystemError } from "../file-system.js";
|
|
16
|
+
import {
|
|
17
|
+
LOOPBACK_TIMEOUT_MS,
|
|
18
|
+
OAuthError,
|
|
19
|
+
authorizationUrl,
|
|
20
|
+
createPkcePair,
|
|
21
|
+
createState,
|
|
22
|
+
exchangeAuthorizationCode,
|
|
23
|
+
pollDeviceToken,
|
|
24
|
+
requestDeviceAuthorization,
|
|
25
|
+
startLoopbackServer,
|
|
26
|
+
} from "../oauth.js";
|
|
27
|
+
import { normalizeApiUrl } from "../plan-state.js";
|
|
28
|
+
import { DEFAULT_API_URL } from "./plan-push.js";
|
|
29
|
+
|
|
30
|
+
const MAX_DEVICE_NAME_LENGTH = 100;
|
|
31
|
+
|
|
32
|
+
export class LoginDeniedError extends Error {}
|
|
33
|
+
export class LoginExpiredError extends Error {}
|
|
34
|
+
|
|
35
|
+
export class LoginFailedError extends Error {
|
|
36
|
+
/**
|
|
37
|
+
* @param {string} message
|
|
38
|
+
* @param {{reason?: string, status?: number, credentialsPath?: string, phase?: "read" | "write", cause?: unknown}} [options]
|
|
39
|
+
*/
|
|
40
|
+
constructor(message, options = {}) {
|
|
41
|
+
super(message, { cause: options.cause });
|
|
42
|
+
this.reason = options.reason;
|
|
43
|
+
this.status = options.status;
|
|
44
|
+
this.credentialsPath = options.credentialsPath;
|
|
45
|
+
this.phase = options.phase;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Selects the origin exactly as other API commands select their initial
|
|
51
|
+
* origin: `--staging`, else FIRSTDRAFT_API_URL, else production.
|
|
52
|
+
*
|
|
53
|
+
* @param {{apiUrl?: string, staging?: boolean}} options
|
|
54
|
+
*/
|
|
55
|
+
export function resolveLoginOrigin({ apiUrl, staging = false }) {
|
|
56
|
+
assertStagingSelection(apiUrl, staging);
|
|
57
|
+
if (staging) return STAGING_API_URL;
|
|
58
|
+
return apiUrl === undefined ? DEFAULT_API_URL : normalizeApiUrl(apiUrl);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @typedef {object} LoginOptions
|
|
63
|
+
* @property {string} origin
|
|
64
|
+
* @property {boolean} [device] use the device authorization grant
|
|
65
|
+
* @property {(text: string) => void} prompt writes user instructions (stderr)
|
|
66
|
+
* @property {typeof globalThis.fetch} [fetchFunction]
|
|
67
|
+
* @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
|
|
68
|
+
* @property {(delayMs: number, signal?: AbortSignal) => Promise<void>} [sleep]
|
|
69
|
+
* @property {() => number} [now]
|
|
70
|
+
* @property {() => string} [hostname]
|
|
71
|
+
* @property {import("../oauth.js").StartLoopbackServer} [startLoopback]
|
|
72
|
+
* @property {import("../credentials.js").CredentialStore} [credentials]
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Runs the browser (loopback + PKCE) or device flow and stores the resulting
|
|
77
|
+
* token for `origin`. Never returns or prints the token.
|
|
78
|
+
*
|
|
79
|
+
* @param {LoginOptions} options
|
|
80
|
+
*/
|
|
81
|
+
export async function login({
|
|
82
|
+
origin,
|
|
83
|
+
device = false,
|
|
84
|
+
prompt,
|
|
85
|
+
fetchFunction,
|
|
86
|
+
createRequestSignal,
|
|
87
|
+
sleep = defaultSleep,
|
|
88
|
+
now = Date.now,
|
|
89
|
+
hostname = osHostname,
|
|
90
|
+
startLoopback = startLoopbackServer,
|
|
91
|
+
credentials = {},
|
|
92
|
+
}) {
|
|
93
|
+
// Reject an unreadable or invalid store before any network request.
|
|
94
|
+
// A later write can still fail after a token has been issued.
|
|
95
|
+
readStore(credentials);
|
|
96
|
+
const deviceName = safeDeviceName(hostname);
|
|
97
|
+
const request = { origin, fetchFunction, createRequestSignal };
|
|
98
|
+
|
|
99
|
+
/** @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
|
+
};
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
if (device) {
|
|
114
|
+
save(await deviceLogin({ ...request, deviceName, prompt, sleep, now }));
|
|
115
|
+
} else {
|
|
116
|
+
await browserLogin({
|
|
117
|
+
...request,
|
|
118
|
+
deviceName,
|
|
119
|
+
prompt,
|
|
120
|
+
sleep,
|
|
121
|
+
startLoopback,
|
|
122
|
+
save,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
} catch (error) {
|
|
126
|
+
throw loginError(error);
|
|
127
|
+
}
|
|
128
|
+
return { origin };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* @param {import("../oauth.js").RequestOptions & {
|
|
133
|
+
* deviceName: string | undefined,
|
|
134
|
+
* prompt: (text: string) => void,
|
|
135
|
+
* sleep: (delayMs: number, signal?: AbortSignal) => Promise<void>,
|
|
136
|
+
* startLoopback: import("../oauth.js").StartLoopbackServer,
|
|
137
|
+
* save: (token: import("../oauth.js").AccessToken) => void,
|
|
138
|
+
* }} options
|
|
139
|
+
*/
|
|
140
|
+
async function browserLogin({
|
|
141
|
+
deviceName,
|
|
142
|
+
prompt,
|
|
143
|
+
sleep,
|
|
144
|
+
startLoopback,
|
|
145
|
+
save,
|
|
146
|
+
...request
|
|
147
|
+
}) {
|
|
148
|
+
const state = createState();
|
|
149
|
+
const { verifier, challenge } = createPkcePair();
|
|
150
|
+
|
|
151
|
+
let listener;
|
|
152
|
+
try {
|
|
153
|
+
listener = await startLoopback({ state });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (!(error instanceof Error)) throw error;
|
|
156
|
+
throw new LoginFailedError(
|
|
157
|
+
"Could not start the local login callback server.",
|
|
158
|
+
{ reason: "loopback_unavailable", cause: error },
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const timer = new AbortController();
|
|
163
|
+
try {
|
|
164
|
+
const url = authorizationUrl(request.origin, {
|
|
165
|
+
redirectUri: listener.redirectUri,
|
|
166
|
+
state,
|
|
167
|
+
challenge,
|
|
168
|
+
deviceName,
|
|
169
|
+
});
|
|
170
|
+
prompt(
|
|
171
|
+
`To log in to ${request.origin}, open this URL in your browser:\n\n ${url}\n\n` +
|
|
172
|
+
"Waiting up to 5 minutes for approval. On a machine without a browser, " +
|
|
173
|
+
"run 'firstdraft login --interactive' instead.\n",
|
|
174
|
+
);
|
|
175
|
+
/** @type {Promise<"timeout">} */
|
|
176
|
+
const timeout = sleep(LOOPBACK_TIMEOUT_MS, timer.signal).then(
|
|
177
|
+
() => "timeout",
|
|
178
|
+
() => new Promise(() => {}),
|
|
179
|
+
);
|
|
180
|
+
const outcome = await Promise.race([listener.result, timeout]);
|
|
181
|
+
timer.abort();
|
|
182
|
+
|
|
183
|
+
if (outcome === "timeout") {
|
|
184
|
+
throw new LoginExpiredError("No browser callback arrived in time.");
|
|
185
|
+
}
|
|
186
|
+
if ("error" in outcome) {
|
|
187
|
+
listener.respond(outcome.error === "access_denied" ? "denied" : "failed");
|
|
188
|
+
throw new OAuthError("The authorization was not granted.", {
|
|
189
|
+
code: outcome.error,
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// The browser waits on the held callback until the token is exchanged and
|
|
194
|
+
// saved, so its page reports what the terminal will report.
|
|
195
|
+
save(
|
|
196
|
+
await exchangeAuthorizationCode({
|
|
197
|
+
...request,
|
|
198
|
+
code: outcome.code,
|
|
199
|
+
redirectUri: listener.redirectUri,
|
|
200
|
+
verifier,
|
|
201
|
+
}),
|
|
202
|
+
);
|
|
203
|
+
listener.respond("approved");
|
|
204
|
+
} finally {
|
|
205
|
+
timer.abort();
|
|
206
|
+
// Answers any still-held callback as failed.
|
|
207
|
+
await listener.close();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @param {import("../oauth.js").RequestOptions & {
|
|
213
|
+
* deviceName: string | undefined,
|
|
214
|
+
* prompt: (text: string) => void,
|
|
215
|
+
* sleep: (delayMs: number) => Promise<void>,
|
|
216
|
+
* now: () => number,
|
|
217
|
+
* }} options
|
|
218
|
+
*/
|
|
219
|
+
async function deviceLogin({ deviceName, prompt, sleep, now, ...request }) {
|
|
220
|
+
const authorization = await requestDeviceAuthorization({
|
|
221
|
+
...request,
|
|
222
|
+
deviceName,
|
|
223
|
+
});
|
|
224
|
+
prompt(
|
|
225
|
+
`To log in to ${request.origin}, open this URL in a browser on any device:\n\n` +
|
|
226
|
+
` ${authorization.verificationUri}\n\n` +
|
|
227
|
+
`and enter the code: ${authorization.userCode}\n\n` +
|
|
228
|
+
(authorization.verificationUriComplete === undefined
|
|
229
|
+
? ""
|
|
230
|
+
: `Or open this URL, which already includes the code:\n\n ${authorization.verificationUriComplete}\n\n`) +
|
|
231
|
+
"Waiting for approval...\n",
|
|
232
|
+
);
|
|
233
|
+
return pollDeviceToken({
|
|
234
|
+
...request,
|
|
235
|
+
deviceCode: authorization.deviceCode,
|
|
236
|
+
interval: authorization.interval,
|
|
237
|
+
expiresIn: authorization.expiresIn,
|
|
238
|
+
sleep,
|
|
239
|
+
now,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** @param {import("../credentials.js").CredentialStore} credentials */
|
|
244
|
+
function readStore(credentials) {
|
|
245
|
+
try {
|
|
246
|
+
return readCredentials(credentials);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
throw credentialsError(error, credentials, "read");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* @param {unknown} error
|
|
254
|
+
* @param {import("../credentials.js").CredentialStore} credentials
|
|
255
|
+
* @param {"read" | "write"} phase
|
|
256
|
+
*/
|
|
257
|
+
function credentialsError(error, credentials, phase) {
|
|
258
|
+
if (!(error instanceof CredentialsInvalidError) && !isFileSystemError(error))
|
|
259
|
+
throw error;
|
|
260
|
+
return new LoginFailedError("The credentials file could not be used.", {
|
|
261
|
+
reason:
|
|
262
|
+
error instanceof CredentialsLockedError
|
|
263
|
+
? "credentials_locked"
|
|
264
|
+
: error instanceof CredentialsInvalidError
|
|
265
|
+
? "credentials_invalid"
|
|
266
|
+
: "credentials_unavailable",
|
|
267
|
+
credentialsPath: credentialsPath(credentials),
|
|
268
|
+
phase,
|
|
269
|
+
cause: error,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** @param {unknown} error */
|
|
274
|
+
function loginError(error) {
|
|
275
|
+
if (
|
|
276
|
+
error instanceof LoginDeniedError ||
|
|
277
|
+
error instanceof LoginExpiredError ||
|
|
278
|
+
error instanceof LoginFailedError
|
|
279
|
+
)
|
|
280
|
+
return error;
|
|
281
|
+
if (!(error instanceof OAuthError)) throw error;
|
|
282
|
+
|
|
283
|
+
if (error.code === "access_denied") {
|
|
284
|
+
return new LoginDeniedError("The authorization was denied.");
|
|
285
|
+
}
|
|
286
|
+
if (error.code === "expired_token") {
|
|
287
|
+
return new LoginExpiredError("The authorization expired.");
|
|
288
|
+
}
|
|
289
|
+
return new LoginFailedError("The login could not be completed.", {
|
|
290
|
+
reason: error.code,
|
|
291
|
+
status: error.status,
|
|
292
|
+
cause: error,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
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
|
+
/** @param {number} delayMs @param {AbortSignal} [signal] */
|
|
312
|
+
function defaultSleep(delayMs, signal) {
|
|
313
|
+
return delay(delayMs, undefined, { signal });
|
|
314
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CredentialsInvalidError,
|
|
3
|
+
CredentialsLockedError,
|
|
4
|
+
credentialsPath,
|
|
5
|
+
deleteCredential,
|
|
6
|
+
readCredentials,
|
|
7
|
+
} from "../credentials.js";
|
|
8
|
+
import { isFileSystemError } from "../file-system.js";
|
|
9
|
+
import { revokeToken } from "../oauth.js";
|
|
10
|
+
|
|
11
|
+
export class LogoutFailedError extends Error {
|
|
12
|
+
/**
|
|
13
|
+
* @param {string} message
|
|
14
|
+
* @param {{reason: string, credentialsPath: string, phase: "read" | "write", revoked?: boolean, cause?: unknown}} options
|
|
15
|
+
*/
|
|
16
|
+
constructor(message, options) {
|
|
17
|
+
super(message, { cause: options.cause });
|
|
18
|
+
this.reason = options.reason;
|
|
19
|
+
this.credentialsPath = options.credentialsPath;
|
|
20
|
+
this.phase = options.phase;
|
|
21
|
+
this.revoked = options.revoked;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @typedef {object} LogoutOptions
|
|
27
|
+
* @property {string} origin
|
|
28
|
+
* @property {typeof globalThis.fetch} [fetchFunction]
|
|
29
|
+
* @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
|
|
30
|
+
* @property {import("../credentials.js").CredentialStore} [credentials]
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @typedef {object} LogoutResult
|
|
35
|
+
* @property {boolean} stored whether a credential for the origin was stored
|
|
36
|
+
* @property {boolean} revoked whether First Draft confirmed revocation
|
|
37
|
+
* @property {boolean} changed whether the saved token changed during logout, so
|
|
38
|
+
* the current entry was left in place
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Revokes the stored token for `origin` (best effort) and deletes the local
|
|
43
|
+
* entry if it still holds that token. Other origins are untouched.
|
|
44
|
+
*
|
|
45
|
+
* @param {LogoutOptions} options
|
|
46
|
+
* @returns {Promise<LogoutResult>}
|
|
47
|
+
*/
|
|
48
|
+
export async function logout({
|
|
49
|
+
origin,
|
|
50
|
+
fetchFunction,
|
|
51
|
+
createRequestSignal,
|
|
52
|
+
credentials = {},
|
|
53
|
+
}) {
|
|
54
|
+
const entry = withCredentials(
|
|
55
|
+
credentials,
|
|
56
|
+
() => readCredentials(credentials).origins[origin],
|
|
57
|
+
{ phase: "read" },
|
|
58
|
+
);
|
|
59
|
+
if (entry === undefined)
|
|
60
|
+
return { stored: false, revoked: false, changed: false };
|
|
61
|
+
|
|
62
|
+
const revoked = await revokeToken({
|
|
63
|
+
origin,
|
|
64
|
+
token: entry.access_token,
|
|
65
|
+
fetchFunction,
|
|
66
|
+
createRequestSignal,
|
|
67
|
+
});
|
|
68
|
+
const removed = withCredentials(
|
|
69
|
+
credentials,
|
|
70
|
+
() =>
|
|
71
|
+
deleteCredential(credentials, origin, {
|
|
72
|
+
accessToken: entry.access_token,
|
|
73
|
+
}),
|
|
74
|
+
{ phase: "write", revoked },
|
|
75
|
+
);
|
|
76
|
+
return { stored: true, revoked, changed: !removed };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @template T
|
|
81
|
+
* @param {import("../credentials.js").CredentialStore} credentials
|
|
82
|
+
* @param {() => T} callback
|
|
83
|
+
* @param {{phase: "read" | "write", revoked?: boolean}} outcome
|
|
84
|
+
* @returns {T}
|
|
85
|
+
*/
|
|
86
|
+
function withCredentials(credentials, callback, outcome) {
|
|
87
|
+
try {
|
|
88
|
+
return callback();
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (
|
|
91
|
+
!(error instanceof CredentialsInvalidError) &&
|
|
92
|
+
!isFileSystemError(error)
|
|
93
|
+
)
|
|
94
|
+
throw error;
|
|
95
|
+
throw new LogoutFailedError("The credentials file could not be used.", {
|
|
96
|
+
reason:
|
|
97
|
+
error instanceof CredentialsLockedError
|
|
98
|
+
? "credentials_locked"
|
|
99
|
+
: error instanceof CredentialsInvalidError
|
|
100
|
+
? "credentials_invalid"
|
|
101
|
+
: "credentials_unavailable",
|
|
102
|
+
credentialsPath: credentialsPath(credentials),
|
|
103
|
+
...outcome,
|
|
104
|
+
cause: error,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|