@firstdraft.com/cli 0.7.0 → 0.8.1
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 -25
- package/docs/README.md +15 -13
- package/docs/commands.md +211 -52
- package/docs/errors.md +42 -6
- package/package.json +6 -4
- package/src/api-authentication.js +55 -13
- package/src/api-response.js +73 -3
- package/src/cli.js +395 -6
- package/src/commands/compilation.js +21 -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/compilation-artifact.js +2 -2
- package/src/credentials.js +343 -0
- package/src/oauth.js +565 -0
- package/RELEASING.md +0 -114
- package/docs/release-history.md +0 -77
package/src/oauth.js
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
SERVICE_ROUTES,
|
|
6
|
+
readResponseBody,
|
|
7
|
+
serviceEndpoint,
|
|
8
|
+
} from "./api-response.js";
|
|
9
|
+
|
|
10
|
+
export const CLIENT_ID = "firstdraft-cli";
|
|
11
|
+
export const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000;
|
|
12
|
+
export const LOOPBACK_HOST = "127.0.0.1";
|
|
13
|
+
export const LOOPBACK_PATH = "/callback";
|
|
14
|
+
export const SLOW_DOWN_INCREMENT_MS = 5000;
|
|
15
|
+
const DEFAULT_DEVICE_INTERVAL_SECONDS = 5;
|
|
16
|
+
const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
17
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
18
|
+
const MAX_OAUTH_RESPONSE_BYTES = 64 * 1024;
|
|
19
|
+
const OAUTH_ERROR_CODE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
20
|
+
const USER_CODE = /^[\x21-\x7e]{1,64}$/;
|
|
21
|
+
|
|
22
|
+
/** @type {Record<LoopbackOutcome, [title: string, message: string]>} */
|
|
23
|
+
const OUTCOME_PAGES = {
|
|
24
|
+
approved: [
|
|
25
|
+
"Login complete",
|
|
26
|
+
"First Draft CLI is logged in. You can close this tab and return to your terminal.",
|
|
27
|
+
],
|
|
28
|
+
denied: [
|
|
29
|
+
"Login cancelled",
|
|
30
|
+
"First Draft CLI was not authorized. You can close this tab and return to your terminal.",
|
|
31
|
+
],
|
|
32
|
+
failed: [
|
|
33
|
+
"Login failed",
|
|
34
|
+
"First Draft CLI could not finish logging in. Return to your terminal for details.",
|
|
35
|
+
],
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// `default-src 'none'` also blocks inline styles, so the one stylesheet is
|
|
39
|
+
// allowed by its hash rather than by loosening the policy.
|
|
40
|
+
const CALLBACK_PAGE_STYLE =
|
|
41
|
+
"body{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem}";
|
|
42
|
+
const CALLBACK_PAGE_CSP = `default-src 'none'; style-src 'sha256-${createHash(
|
|
43
|
+
"sha256",
|
|
44
|
+
)
|
|
45
|
+
.update(CALLBACK_PAGE_STYLE)
|
|
46
|
+
.digest("base64")}'`;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* An OAuth endpoint answered with an RFC 6749 error, or the exchange could not
|
|
50
|
+
* be completed. `code` is the validated OAuth error code when there is one.
|
|
51
|
+
*/
|
|
52
|
+
export class OAuthError extends Error {
|
|
53
|
+
/**
|
|
54
|
+
* @param {string} message
|
|
55
|
+
* @param {{code?: string, status?: number, cause?: unknown}} [options]
|
|
56
|
+
*/
|
|
57
|
+
constructor(message, options = {}) {
|
|
58
|
+
super(message, { cause: options.cause });
|
|
59
|
+
this.code = options.code;
|
|
60
|
+
this.status = options.status;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @typedef {object} AccessToken
|
|
66
|
+
* @property {string} access_token
|
|
67
|
+
* @property {"Bearer"} token_type
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @typedef {object} RequestOptions
|
|
72
|
+
* @property {string} origin
|
|
73
|
+
* @property {typeof globalThis.fetch} [fetchFunction]
|
|
74
|
+
* @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
/** @param {(size: number) => Buffer} [random] */
|
|
78
|
+
export function createPkcePair(random = randomBytes) {
|
|
79
|
+
const verifier = random(32).toString("base64url");
|
|
80
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
81
|
+
return { verifier, challenge };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** @param {(size: number) => Buffer} [random] */
|
|
85
|
+
export function createState(random = randomBytes) {
|
|
86
|
+
return random(32).toString("base64url");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @param {string} origin
|
|
91
|
+
* @param {{redirectUri: string, state: string, challenge: string, deviceName?: string}} options
|
|
92
|
+
*/
|
|
93
|
+
export function authorizationUrl(
|
|
94
|
+
origin,
|
|
95
|
+
{ redirectUri, state, challenge, deviceName },
|
|
96
|
+
) {
|
|
97
|
+
const url = new URL("/oauth/authorize", origin);
|
|
98
|
+
url.search = new URLSearchParams({
|
|
99
|
+
response_type: "code",
|
|
100
|
+
client_id: CLIENT_ID,
|
|
101
|
+
redirect_uri: redirectUri,
|
|
102
|
+
state,
|
|
103
|
+
code_challenge: challenge,
|
|
104
|
+
code_challenge_method: "S256",
|
|
105
|
+
...(deviceName ? { device_name: deviceName } : {}),
|
|
106
|
+
}).toString();
|
|
107
|
+
return url.href;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @typedef {{code: string} | {error: string}} LoopbackResult
|
|
112
|
+
*/
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* @typedef {"approved" | "denied" | "failed"} LoopbackOutcome
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @typedef {object} LoopbackListener
|
|
120
|
+
* @property {string} redirectUri
|
|
121
|
+
* @property {Promise<LoopbackResult>} result
|
|
122
|
+
* Settles once, with the first callback that carries the expected state.
|
|
123
|
+
* @property {(outcome: LoopbackOutcome) => void} respond
|
|
124
|
+
* Answers the accepted callback, which is held open until the login knows
|
|
125
|
+
* its real outcome. Later calls do nothing.
|
|
126
|
+
* @property {() => Promise<void>} close
|
|
127
|
+
* Answers a still-held callback as failed, then stops listening.
|
|
128
|
+
*/
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @typedef {(options: {state: string}) => Promise<LoopbackListener>} StartLoopbackServer
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Listens on 127.0.0.1 at an ephemeral port for exactly one OAuth redirect.
|
|
136
|
+
*
|
|
137
|
+
* Only `GET /callback` with a `Host` of the bound address and a `state` equal
|
|
138
|
+
* to the expected value is accepted. Anything else (a favicon request, a
|
|
139
|
+
* missing or wrong state, a rebinding `Host`) receives an error response and
|
|
140
|
+
* does not end the wait, so a stray or hostile local request can neither
|
|
141
|
+
* inject a code nor cancel the login. The first accepted callback settles the
|
|
142
|
+
* result; later requests receive 404. The accepted request is answered only
|
|
143
|
+
* through `respond`, so the browser never reports success before the code
|
|
144
|
+
* exchange and credential write have finished.
|
|
145
|
+
*
|
|
146
|
+
* @type {StartLoopbackServer}
|
|
147
|
+
*/
|
|
148
|
+
export async function startLoopbackServer({ state }) {
|
|
149
|
+
/** @type {(result: LoopbackResult) => void} */
|
|
150
|
+
let settle = () => {};
|
|
151
|
+
/** @type {Promise<LoopbackResult>} */
|
|
152
|
+
const result = new Promise((resolve) => {
|
|
153
|
+
settle = resolve;
|
|
154
|
+
});
|
|
155
|
+
let settled = false;
|
|
156
|
+
/** @type {Promise<void>} */
|
|
157
|
+
let responded = Promise.resolve();
|
|
158
|
+
/** @type {import("node:http").ServerResponse | undefined} */
|
|
159
|
+
let held;
|
|
160
|
+
let port = 0;
|
|
161
|
+
|
|
162
|
+
const server = createServer((request, response) => {
|
|
163
|
+
/** @param {number} status @param {string} title @param {string} message */
|
|
164
|
+
const reply = (status, title, message) =>
|
|
165
|
+
writeCallbackPage(response, status, title, message);
|
|
166
|
+
|
|
167
|
+
const url = parseRequestUrl(request.url);
|
|
168
|
+
if (
|
|
169
|
+
settled ||
|
|
170
|
+
request.method !== "GET" ||
|
|
171
|
+
url === null ||
|
|
172
|
+
url.pathname !== LOOPBACK_PATH
|
|
173
|
+
) {
|
|
174
|
+
reply(404, "Not found", "This address only accepts the login callback.");
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const params = url.searchParams;
|
|
179
|
+
const states = params.getAll("state");
|
|
180
|
+
if (
|
|
181
|
+
request.headers.host !== `${LOOPBACK_HOST}:${port}` ||
|
|
182
|
+
states.length !== 1 ||
|
|
183
|
+
!equalSecrets(states[0] ?? "", state)
|
|
184
|
+
) {
|
|
185
|
+
reply(
|
|
186
|
+
400,
|
|
187
|
+
"Login not accepted",
|
|
188
|
+
"This callback does not match the login in progress. Return to your terminal.",
|
|
189
|
+
);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
settled = true;
|
|
194
|
+
held = response;
|
|
195
|
+
responded = new Promise((resolve) => {
|
|
196
|
+
response.once("close", resolve);
|
|
197
|
+
});
|
|
198
|
+
const codes = params.getAll("code");
|
|
199
|
+
const errors = params.getAll("error");
|
|
200
|
+
const [code] = codes;
|
|
201
|
+
const [error] = errors;
|
|
202
|
+
if (errors.length === 0 && codes.length === 1 && code) {
|
|
203
|
+
settle({ code });
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
settle({
|
|
208
|
+
error:
|
|
209
|
+
errors.length === 1 &&
|
|
210
|
+
error !== undefined &&
|
|
211
|
+
OAUTH_ERROR_CODE.test(error)
|
|
212
|
+
? error
|
|
213
|
+
: "invalid_request",
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
/** @param {LoopbackOutcome} outcome */
|
|
218
|
+
const respond = (outcome) => {
|
|
219
|
+
const response = held;
|
|
220
|
+
held = undefined;
|
|
221
|
+
if (response === undefined) return;
|
|
222
|
+
const [title, message] = OUTCOME_PAGES[outcome];
|
|
223
|
+
writeCallbackPage(response, 200, title, message);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
await new Promise((resolve, reject) => {
|
|
227
|
+
server.once("error", reject);
|
|
228
|
+
server.listen(0, LOOPBACK_HOST, () => {
|
|
229
|
+
server.off("error", reject);
|
|
230
|
+
resolve(undefined);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
const address = server.address();
|
|
234
|
+
if (address === null || typeof address === "string") {
|
|
235
|
+
server.close();
|
|
236
|
+
throw new Error("The loopback server has no TCP address.");
|
|
237
|
+
}
|
|
238
|
+
port = address.port;
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
redirectUri: `http://${LOOPBACK_HOST}:${port}${LOOPBACK_PATH}`,
|
|
242
|
+
result,
|
|
243
|
+
respond,
|
|
244
|
+
close: async () => {
|
|
245
|
+
respond("failed");
|
|
246
|
+
const closed = new Promise((resolve) => {
|
|
247
|
+
server.close(resolve);
|
|
248
|
+
});
|
|
249
|
+
// Let the final browser page flush, but never wait on a stalled client.
|
|
250
|
+
await Promise.race([
|
|
251
|
+
responded,
|
|
252
|
+
new Promise((resolve) => {
|
|
253
|
+
setTimeout(resolve, 1000).unref();
|
|
254
|
+
}),
|
|
255
|
+
]);
|
|
256
|
+
server.closeAllConnections();
|
|
257
|
+
await closed;
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* @param {RequestOptions & {code: string, redirectUri: string, verifier: string}} options
|
|
264
|
+
* @returns {Promise<AccessToken>}
|
|
265
|
+
*/
|
|
266
|
+
export async function exchangeAuthorizationCode({
|
|
267
|
+
code,
|
|
268
|
+
redirectUri,
|
|
269
|
+
verifier,
|
|
270
|
+
...request
|
|
271
|
+
}) {
|
|
272
|
+
const response = await postForm(request, SERVICE_ROUTES.requestOAuthToken, {
|
|
273
|
+
grant_type: "authorization_code",
|
|
274
|
+
code,
|
|
275
|
+
redirect_uri: redirectUri,
|
|
276
|
+
client_id: CLIENT_ID,
|
|
277
|
+
code_verifier: verifier,
|
|
278
|
+
});
|
|
279
|
+
return accessTokenFrom(response);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* @typedef {object} DeviceAuthorization
|
|
284
|
+
* @property {string} deviceCode
|
|
285
|
+
* @property {string} userCode
|
|
286
|
+
* @property {string} verificationUri
|
|
287
|
+
* @property {string | undefined} verificationUriComplete
|
|
288
|
+
* @property {number} expiresIn seconds
|
|
289
|
+
* @property {number} interval seconds
|
|
290
|
+
*/
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* @param {RequestOptions & {deviceName?: string}} options
|
|
294
|
+
* @returns {Promise<DeviceAuthorization>}
|
|
295
|
+
*/
|
|
296
|
+
export async function requestDeviceAuthorization({ deviceName, ...request }) {
|
|
297
|
+
const { status, body } = await postForm(
|
|
298
|
+
request,
|
|
299
|
+
SERVICE_ROUTES.requestDeviceAuthorization,
|
|
300
|
+
{
|
|
301
|
+
client_id: CLIENT_ID,
|
|
302
|
+
...(deviceName ? { device_name: deviceName } : {}),
|
|
303
|
+
},
|
|
304
|
+
);
|
|
305
|
+
if (status !== 200) throw oauthFailure(status, body);
|
|
306
|
+
|
|
307
|
+
const verificationUri = httpUrl(body?.verification_uri);
|
|
308
|
+
const verificationUriComplete =
|
|
309
|
+
body?.verification_uri_complete === undefined
|
|
310
|
+
? undefined
|
|
311
|
+
: httpUrl(body.verification_uri_complete);
|
|
312
|
+
const interval =
|
|
313
|
+
body?.interval === undefined
|
|
314
|
+
? DEFAULT_DEVICE_INTERVAL_SECONDS
|
|
315
|
+
: body.interval;
|
|
316
|
+
if (
|
|
317
|
+
body === null ||
|
|
318
|
+
typeof body.device_code !== "string" ||
|
|
319
|
+
body.device_code.length === 0 ||
|
|
320
|
+
typeof body.user_code !== "string" ||
|
|
321
|
+
!USER_CODE.test(body.user_code) ||
|
|
322
|
+
verificationUri === null ||
|
|
323
|
+
verificationUriComplete === null ||
|
|
324
|
+
!isPositiveInteger(body.expires_in) ||
|
|
325
|
+
!isPositiveInteger(interval)
|
|
326
|
+
) {
|
|
327
|
+
throw new OAuthError("The device authorization response is invalid.", {
|
|
328
|
+
status,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
deviceCode: body.device_code,
|
|
334
|
+
userCode: body.user_code,
|
|
335
|
+
verificationUri,
|
|
336
|
+
verificationUriComplete,
|
|
337
|
+
expiresIn: body.expires_in,
|
|
338
|
+
interval,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Polls the token endpoint until the device grant is approved, denied, or
|
|
344
|
+
* expired. Waits `interval` seconds before each poll and adds five seconds on
|
|
345
|
+
* every `slow_down` (RFC 8628 §3.5).
|
|
346
|
+
*
|
|
347
|
+
* @param {RequestOptions & {
|
|
348
|
+
* deviceCode: string,
|
|
349
|
+
* interval: number,
|
|
350
|
+
* expiresIn: number,
|
|
351
|
+
* sleep: (delayMs: number) => Promise<void>,
|
|
352
|
+
* now: () => number,
|
|
353
|
+
* }} options
|
|
354
|
+
* @returns {Promise<AccessToken>}
|
|
355
|
+
*/
|
|
356
|
+
export async function pollDeviceToken({
|
|
357
|
+
deviceCode,
|
|
358
|
+
interval,
|
|
359
|
+
expiresIn,
|
|
360
|
+
sleep,
|
|
361
|
+
now,
|
|
362
|
+
...request
|
|
363
|
+
}) {
|
|
364
|
+
const deadline = now() + expiresIn * 1000;
|
|
365
|
+
let intervalMs = interval * 1000;
|
|
366
|
+
|
|
367
|
+
while (true) {
|
|
368
|
+
await sleep(intervalMs);
|
|
369
|
+
if (now() >= deadline) {
|
|
370
|
+
throw new OAuthError("The device code expired.", {
|
|
371
|
+
code: "expired_token",
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const response = await postForm(request, SERVICE_ROUTES.requestOAuthToken, {
|
|
376
|
+
grant_type: DEVICE_CODE_GRANT_TYPE,
|
|
377
|
+
device_code: deviceCode,
|
|
378
|
+
client_id: CLIENT_ID,
|
|
379
|
+
});
|
|
380
|
+
if (response.status === 200) return accessTokenFrom(response);
|
|
381
|
+
|
|
382
|
+
const failure = oauthFailure(response.status, response.body);
|
|
383
|
+
if (failure.code === "authorization_pending") continue;
|
|
384
|
+
if (failure.code === "slow_down") {
|
|
385
|
+
intervalMs += SLOW_DOWN_INCREMENT_MS;
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
throw failure;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Best-effort RFC 7009 revocation. Resolves true only for a 200 response.
|
|
394
|
+
*
|
|
395
|
+
* @param {RequestOptions & {token: string}} options
|
|
396
|
+
*/
|
|
397
|
+
export async function revokeToken({ token, ...request }) {
|
|
398
|
+
try {
|
|
399
|
+
const { status } = await postForm(
|
|
400
|
+
request,
|
|
401
|
+
SERVICE_ROUTES.revokeOAuthToken,
|
|
402
|
+
{
|
|
403
|
+
token,
|
|
404
|
+
client_id: CLIENT_ID,
|
|
405
|
+
},
|
|
406
|
+
);
|
|
407
|
+
return status === 200;
|
|
408
|
+
} catch (error) {
|
|
409
|
+
if (error instanceof OAuthError) return false;
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* @param {RequestOptions} request
|
|
416
|
+
* @param {{method: string, path: string}} route
|
|
417
|
+
* @param {Record<string, string>} params
|
|
418
|
+
* @returns {Promise<{status: number, body: Record<string, unknown> | null}>}
|
|
419
|
+
*/
|
|
420
|
+
async function postForm(
|
|
421
|
+
{
|
|
422
|
+
origin,
|
|
423
|
+
fetchFunction = globalThis.fetch,
|
|
424
|
+
createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
425
|
+
},
|
|
426
|
+
route,
|
|
427
|
+
params,
|
|
428
|
+
) {
|
|
429
|
+
const endpoint = serviceEndpoint(route, origin, {});
|
|
430
|
+
let response;
|
|
431
|
+
try {
|
|
432
|
+
response = await fetchFunction(endpoint.url, {
|
|
433
|
+
method: endpoint.method,
|
|
434
|
+
headers: {
|
|
435
|
+
Accept: "application/json",
|
|
436
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
437
|
+
},
|
|
438
|
+
body: new URLSearchParams(params).toString(),
|
|
439
|
+
redirect: "error",
|
|
440
|
+
signal: createRequestSignal(),
|
|
441
|
+
});
|
|
442
|
+
} catch (error) {
|
|
443
|
+
throw new OAuthError("The First Draft request failed.", { cause: error });
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
let body;
|
|
447
|
+
try {
|
|
448
|
+
body = await readResponseBody(response, MAX_OAUTH_RESPONSE_BYTES);
|
|
449
|
+
} catch (error) {
|
|
450
|
+
throw new OAuthError("The First Draft response failed.", {
|
|
451
|
+
status: response.status,
|
|
452
|
+
cause: error,
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
return { status: response.status, body: isRecord(body) ? body : null };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* @param {{status: number, body: Record<string, unknown> | null}} response
|
|
460
|
+
* @returns {AccessToken}
|
|
461
|
+
*/
|
|
462
|
+
function accessTokenFrom({ status, body }) {
|
|
463
|
+
if (status !== 200) throw oauthFailure(status, body);
|
|
464
|
+
if (
|
|
465
|
+
body === null ||
|
|
466
|
+
typeof body.access_token !== "string" ||
|
|
467
|
+
body.access_token.trim().length === 0 ||
|
|
468
|
+
/\s/.test(body.access_token) ||
|
|
469
|
+
typeof body.token_type !== "string" ||
|
|
470
|
+
body.token_type.toLowerCase() !== "bearer"
|
|
471
|
+
) {
|
|
472
|
+
throw new OAuthError("The token response is invalid.", { status });
|
|
473
|
+
}
|
|
474
|
+
return { access_token: body.access_token, token_type: "Bearer" };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* @param {number} status
|
|
479
|
+
* @param {Record<string, unknown> | null} body
|
|
480
|
+
*/
|
|
481
|
+
function oauthFailure(status, body) {
|
|
482
|
+
const code =
|
|
483
|
+
typeof body?.error === "string" && OAUTH_ERROR_CODE.test(body.error)
|
|
484
|
+
? body.error
|
|
485
|
+
: undefined;
|
|
486
|
+
return new OAuthError("First Draft rejected the OAuth request.", {
|
|
487
|
+
code,
|
|
488
|
+
status,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** @param {unknown} value @returns {string | null} */
|
|
493
|
+
function httpUrl(value) {
|
|
494
|
+
if (typeof value !== "string") return null;
|
|
495
|
+
try {
|
|
496
|
+
const url = new URL(value);
|
|
497
|
+
return url.protocol === "https:" || url.protocol === "http:"
|
|
498
|
+
? url.href
|
|
499
|
+
: null;
|
|
500
|
+
} catch {
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** @param {string | undefined} value */
|
|
506
|
+
function parseRequestUrl(value) {
|
|
507
|
+
if (value === undefined || !value.startsWith("/")) return null;
|
|
508
|
+
try {
|
|
509
|
+
return new URL(value, `http://${LOOPBACK_HOST}`);
|
|
510
|
+
} catch {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** @param {string} actual @param {string} expected */
|
|
516
|
+
function equalSecrets(actual, expected) {
|
|
517
|
+
const actualBytes = Buffer.from(actual);
|
|
518
|
+
const expectedBytes = Buffer.from(expected);
|
|
519
|
+
return (
|
|
520
|
+
actualBytes.length === expectedBytes.length &&
|
|
521
|
+
timingSafeEqual(actualBytes, expectedBytes)
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* @param {import("node:http").ServerResponse} response
|
|
527
|
+
* @param {number} status
|
|
528
|
+
* @param {string} title
|
|
529
|
+
* @param {string} message
|
|
530
|
+
*/
|
|
531
|
+
function writeCallbackPage(response, status, title, message) {
|
|
532
|
+
const body = callbackPage(title, message);
|
|
533
|
+
response.writeHead(status, {
|
|
534
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
535
|
+
"Content-Length": Buffer.byteLength(body),
|
|
536
|
+
"Cache-Control": "no-store",
|
|
537
|
+
"Content-Security-Policy": CALLBACK_PAGE_CSP,
|
|
538
|
+
"Referrer-Policy": "no-referrer",
|
|
539
|
+
Connection: "close",
|
|
540
|
+
});
|
|
541
|
+
response.end(body);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** @param {string} title @param {string} message */
|
|
545
|
+
function callbackPage(title, message) {
|
|
546
|
+
return `<!doctype html>
|
|
547
|
+
<html lang="en">
|
|
548
|
+
<head><meta charset="utf-8"><title>${title} · First Draft CLI</title><style>${CALLBACK_PAGE_STYLE}</style></head>
|
|
549
|
+
<body>
|
|
550
|
+
<h1>${title}</h1>
|
|
551
|
+
<p>${message}</p>
|
|
552
|
+
</body>
|
|
553
|
+
</html>
|
|
554
|
+
`;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** @param {unknown} value @returns {value is number} */
|
|
558
|
+
function isPositiveInteger(value) {
|
|
559
|
+
return Number.isSafeInteger(value) && Number(value) > 0;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
563
|
+
function isRecord(value) {
|
|
564
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
565
|
+
}
|
package/RELEASING.md
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
# Releasing First Draft CLI
|
|
2
|
-
|
|
3
|
-
An approved coordinated release publishes directly to npm's `latest` channel. Tests and review belong before merge;
|
|
4
|
-
publication reuses successful CI for the exact source. It does not repeat the suite or require a second
|
|
5
|
-
`next`-to-`latest` promotion. Dated observations remain in [release history](docs/release-history.md).
|
|
6
|
-
|
|
7
|
-
A merge alone does not authorize publication. Obtain one approval for the intended coordinated release, or use the
|
|
8
|
-
approval already given for that scope. The existing GitHub `npm` environment protection still applies; its approval
|
|
9
|
-
executes the same release decision. Do not ask for another conversational approval between already-approved steps.
|
|
10
|
-
|
|
11
|
-
## Version and compatibility policy
|
|
12
|
-
|
|
13
|
-
Before `1.0.0`, use ordinary `0.MINOR.PATCH` versions: increase `MINOR` for a breaking compatibility-line change and
|
|
14
|
-
`PATCH` for a backward-compatible change within that line. Never reuse a published version or move a protected
|
|
15
|
-
release tag. An unpublished, untagged candidate can retain its proposed version while its source changes.
|
|
16
|
-
The published version may remain in source during documentation and test maintenance; recording its release history
|
|
17
|
-
does not require preparing another version. Choose an unused version when preparing the next publication.
|
|
18
|
-
|
|
19
|
-
CLI `0.7.x` requires API `0.6.x` and Plan `firstdraft.foundation-plan.sketch/0.22`. CLI `0.7.0` adds `--staging`
|
|
20
|
-
and requires `FIRSTDRAFT_STAGING_API_TOKEN` for the staging origin, including existing pinned Projects. This token
|
|
21
|
-
configuration change warrants a new CLI minor version; the API and Plan contracts stay unchanged. Production
|
|
22
|
-
remains the default and uses `FIRSTDRAFT_API_TOKEN`, as do custom origins. No Project is migrated. The target stays
|
|
23
|
-
`rails-sketch/2026-09`.
|
|
24
|
-
|
|
25
|
-
Local output remains the default introduced in CLI `0.4.x`: `firstdraft plan compile` is equivalent to
|
|
26
|
-
`firstdraft plan compile --output .`, with GitHub publication selected by explicit `--github`. The root archive
|
|
27
|
-
remains `.firstdraft/design`. Existing applications and old Plans are not migrated.
|
|
28
|
-
|
|
29
|
-
`release/compatibility.json` declares the package version, accepted API-contract range, and accepted Plan formats.
|
|
30
|
-
It is source-only metadata, validated by the normal test suite and absent from the npm tarball. Coordinate the
|
|
31
|
-
explicit CLI comparator and bundled CLI pin in `firstdraft/skills` when this version changes. The service's
|
|
32
|
-
`script/release_compatibility_check` compares the three exact revisions; compatibility establishes eligibility,
|
|
33
|
-
not authorization or runtime proof. Its closed `firstdraft.release-compatibility/1` format rejects unknown keys.
|
|
34
|
-
|
|
35
|
-
## Prepare before merge
|
|
36
|
-
|
|
37
|
-
1. Update `package.json`, `package-lock.json`, and `release/compatibility.json`, and align the Skills CLI requirement.
|
|
38
|
-
2. Update the command, error, and Skill guidance affected by the change. When onboarding changes, coordinate the
|
|
39
|
-
[local guide](https://gist.github.com/raghubetina/3d424a97a1eaa6de8c406e67f32a237e) publication from the Service's
|
|
40
|
-
`docs/guides/local-app.md` before the new CLI reaches `latest`. Preserve dated release evidence.
|
|
41
|
-
3. Run focused checks while developing and the repository's required CI for the merge candidate. For a fresh
|
|
42
|
-
checkout, the complete local check is `npm ci --ignore-scripts`, `npm audit`, then `npm run check`.
|
|
43
|
-
4. Review and merge the change. Wait for the existing `CI` workflow to pass for the selected `main` SHA; publication
|
|
44
|
-
uses that run instead of starting another one.
|
|
45
|
-
|
|
46
|
-
Use existing smoke evidence when it covers the changed behavior. If changed CLI/Service/Skill behavior warrants a
|
|
47
|
-
live smoke, use a simple Plan, compile locally with `firstdraft plan compile --output .`, and boot the generated app locally
|
|
48
|
-
when runtime behavior changed. A CLI dispatch-only change can be covered by local command and packed-package tests.
|
|
49
|
-
Do not require Codespaces, GitHub Publication, native builds, or Revyl for a routine release. Codespaces is a fallback
|
|
50
|
-
development environment. Additional integration checks belong only to changes affecting those integrations.
|
|
51
|
-
|
|
52
|
-
## Publish the approved source
|
|
53
|
-
|
|
54
|
-
From a clean checkout of the selected `main` revision:
|
|
55
|
-
|
|
56
|
-
1. Confirm the exact package version and `v<package-version>` tag are both unused. If either identity is already
|
|
57
|
-
consumed, prepare the next version required by the pre-1.0 policy rather than moving or reusing it.
|
|
58
|
-
2. Confirm the intended three revisions are compatible and the coordinated release approval covers them.
|
|
59
|
-
3. Create and push `v<package-version>` at that source revision. Push one release tag at a time; the workflow
|
|
60
|
-
serializes publication and GitHub retains at most one pending run in a concurrency group.
|
|
61
|
-
4. Approve the existing `npm` environment deployment for that tag. The workflow publishes with provenance under
|
|
62
|
-
`latest`; no separate dist-tag mutation is needed.
|
|
63
|
-
|
|
64
|
-
The workflow requires a protected `v*` tag in `firstdraft/cli`, the matching `package.json` version, an unchanged
|
|
65
|
-
remote tag, and a commit in the first-parent history of protected `main`. It finds a successful `CI` push run for
|
|
66
|
-
that exact SHA using `gh run list`, checks the package file allowlist, then rechecks mutable refs after environment
|
|
67
|
-
approval. It does not install development dependencies, rerun tests or audit, or request interactive npm login.
|
|
68
|
-
Both source checks invoke `scripts/check-release-source.sh`; the postapproval invocation must remain before publish.
|
|
69
|
-
|
|
70
|
-
If CI is still running, let that run finish and rerun the failed publication verification job. Resolve failing
|
|
71
|
-
checks in CI itself; publication does not start a duplicate suite. A source fix after tagging requires a new version.
|
|
72
|
-
Do not retest unrelated surfaces merely because time has passed since merge.
|
|
73
|
-
|
|
74
|
-
## Verify and recover
|
|
75
|
-
|
|
76
|
-
After publication, inspect the registry before retrying a failed workflow; the immutable version may already exist:
|
|
77
|
-
|
|
78
|
-
```sh
|
|
79
|
-
FD_CLI_RELEASE_VERSION="$(node -p "require('./package.json').version")"
|
|
80
|
-
npm view "@firstdraft.com/cli@$FD_CLI_RELEASE_VERSION" \
|
|
81
|
-
version dist.integrity dist.shasum dist.attestations repository.url engines bin --json
|
|
82
|
-
npm dist-tag ls '@firstdraft.com/cli'
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
Confirm the intended version is `latest` and has integrity/provenance metadata. Install that exact version in a
|
|
86
|
-
temporary prefix, confirm `firstdraft --version`, and run `npm audit signatures` there to verify the published
|
|
87
|
-
artifact. This checks distribution; it does not repeat application qualification. Record the version, source,
|
|
88
|
-
package integrity, and any relevant smoke evidence in the dated release record.
|
|
89
|
-
|
|
90
|
-
If OIDC authentication fails, reconcile the registry version and protected tag before retrying. Correct a broken
|
|
91
|
-
trusted-publisher relationship when necessary, then rerun failed jobs at the existing tag. If the tagged workflow
|
|
92
|
-
identity itself is wrong, prepare a new version; never move the tag or add a persistent-token fallback.
|
|
93
|
-
|
|
94
|
-
For a bad release, move `latest` to a known-good compatible version as an incident rollback, or deprecate the bad
|
|
95
|
-
version and publish a corrected higher version. Unpublishing is exceptional incident response, not routine rollback.
|
|
96
|
-
|
|
97
|
-
## Publisher configuration
|
|
98
|
-
|
|
99
|
-
These are durable repository and npm controls, not a per-release account audit. Verify them when provisioning,
|
|
100
|
-
changing publisher configuration, or diagnosing an actual failure:
|
|
101
|
-
|
|
102
|
-
- `firstdraft/cli` is public; `main` requires pull requests and CI, and a `v*` ruleset restricts tag mutation.
|
|
103
|
-
- The `npm` GitHub environment is limited to release tags, requires its existing reviewer, disables administrator
|
|
104
|
-
bypass, and defines `NPM_RELEASE_ENABLED=true`.
|
|
105
|
-
- npm trusted publishing identifies package `@firstdraft.com/cli`, repository `firstdraft/cli`, workflow
|
|
106
|
-
`publish.yml`, environment `npm`, and permission `createPackage`. The publishing account retains the intended
|
|
107
|
-
organization access and write-protecting 2FA. Configure these with an administrator only when needed.
|
|
108
|
-
- Publication runs on a GitHub-hosted runner with `id-token: write`, pinned Node.js 24.18.0 and npm 11.16.0. npm's
|
|
109
|
-
short-lived OIDC exchange is the only publication credential; no persistent npm token or Actions secret is used.
|
|
110
|
-
The CI lookup uses GitHub's read-only workflow token.
|
|
111
|
-
|
|
112
|
-
Ordinary installation and use require no npm login. Ordinary trusted publication requires no local maintainer
|
|
113
|
-
login or per-release security-key ceremony. Request npm interaction only when npm requires it for a governance
|
|
114
|
-
change or an actual authentication failure. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
|