@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.
@@ -26,8 +26,8 @@ import {
26
26
  export const ARTIFACT_MEDIA_TYPE =
27
27
  "application/vnd.firstdraft.compilation-artifact+json";
28
28
  export const ARTIFACT_FORMAT = "firstdraft.compilation-artifact/1";
29
- export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.22";
30
- export const RAILS_TARGET_PROFILE = "rails-sketch/2026-09";
29
+ export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.23";
30
+ export const RAILS_TARGET_PROFILE = "rails-sketch/2026-09-bookmark-assets";
31
31
  export const MAX_ARTIFACT_BYTES = 128 * 1024 * 1024;
32
32
 
33
33
  const ARTIFACT_KEYS = ["format", "provenance", "manifest_sha256", "files"];
@@ -0,0 +1,343 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ rmSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import path from "node:path";
12
+
13
+ import { isFileSystemError } from "./file-system.js";
14
+
15
+ export const CREDENTIALS_FORMAT = "firstdraft.cli-credentials/1";
16
+ const MAX_CREDENTIALS_BYTES = 256 * 1024;
17
+ const LOCK_TIMEOUT_MS = 10_000;
18
+ const LOCK_RETRY_MS = 25;
19
+
20
+ /**
21
+ * @typedef {object} CredentialsFileSystem
22
+ * @property {typeof mkdirSync} mkdirSync
23
+ * @property {typeof readFileSync} readFileSync
24
+ * @property {typeof renameSync} renameSync
25
+ * @property {typeof rmSync} rmSync
26
+ * @property {typeof statSync} statSync
27
+ * @property {typeof writeFileSync} writeFileSync
28
+ */
29
+
30
+ /**
31
+ * Where and how the CLI stores login credentials. Every member is injectable so
32
+ * tests never touch the real configuration directory.
33
+ *
34
+ * @typedef {object} CredentialStore
35
+ * @property {Readonly<Record<string, string | undefined>>} [env]
36
+ * @property {() => string} [homedir]
37
+ * @property {CredentialsFileSystem} [fileSystem]
38
+ * @property {() => string} [createTemporaryId]
39
+ * @property {number} [lockTimeoutMs] how long an update waits for another
40
+ * process's lock before failing
41
+ */
42
+
43
+ /**
44
+ * @typedef {object} CredentialEntry
45
+ * @property {string} access_token
46
+ * @property {string} token_type
47
+ * @property {string} created_at
48
+ */
49
+
50
+ /**
51
+ * @typedef {object} Credentials
52
+ * @property {typeof CREDENTIALS_FORMAT} format
53
+ * @property {Record<string, CredentialEntry>} origins
54
+ */
55
+
56
+ /** @type {CredentialsFileSystem} */
57
+ const DEFAULT_FILE_SYSTEM = {
58
+ mkdirSync,
59
+ readFileSync,
60
+ renameSync,
61
+ rmSync,
62
+ statSync,
63
+ writeFileSync,
64
+ };
65
+
66
+ export class CredentialsInvalidError extends Error {}
67
+
68
+ /**
69
+ * The credentials lock stayed held for the whole wait: another command is
70
+ * updating the file, or one exited while holding the lock. The lock is never
71
+ * removed automatically, because no file-system check can tell an abandoned
72
+ * lock from one another command has just taken. Its `code` lets callers treat
73
+ * it like any other unavailable credentials file.
74
+ */
75
+ export class CredentialsLockedError extends Error {
76
+ code = "ELOCKED";
77
+ }
78
+
79
+ /**
80
+ * `$XDG_CONFIG_HOME/firstdraft/credentials.json`, falling back to
81
+ * `~/.config/firstdraft/credentials.json`. A relative XDG_CONFIG_HOME is
82
+ * ignored, as the XDG Base Directory specification requires.
83
+ *
84
+ * @param {CredentialStore} [store]
85
+ */
86
+ export function credentialsPath(store = {}) {
87
+ const env = store.env ?? process.env;
88
+ const configHome = env.XDG_CONFIG_HOME;
89
+ const base =
90
+ configHome !== undefined && path.isAbsolute(configHome)
91
+ ? configHome
92
+ : path.join((store.homedir ?? homedir)(), ".config");
93
+ return path.join(base, "firstdraft", "credentials.json");
94
+ }
95
+
96
+ /**
97
+ * Reads the credentials file. A missing file is an empty store; an unreadable
98
+ * or malformed file throws.
99
+ *
100
+ * @param {CredentialStore} [store]
101
+ * @returns {Credentials}
102
+ */
103
+ export function readCredentials(store = {}) {
104
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
105
+ let source;
106
+ try {
107
+ source = fileSystem.readFileSync(credentialsPath(store));
108
+ } catch (error) {
109
+ if (isMissingFileError(error)) return emptyCredentials();
110
+ throw error;
111
+ }
112
+
113
+ if (source.byteLength > MAX_CREDENTIALS_BYTES) {
114
+ throw new CredentialsInvalidError("The credentials file is too large.");
115
+ }
116
+
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(
120
+ new TextDecoder("utf-8", { fatal: true }).decode(source),
121
+ );
122
+ } catch (error) {
123
+ if (!(error instanceof SyntaxError) && !(error instanceof TypeError))
124
+ throw error;
125
+ throw new CredentialsInvalidError("The credentials file is invalid.");
126
+ }
127
+
128
+ if (
129
+ !isRecord(parsed) ||
130
+ parsed.format !== CREDENTIALS_FORMAT ||
131
+ !isRecord(parsed.origins)
132
+ ) {
133
+ throw new CredentialsInvalidError("The credentials file is invalid.");
134
+ }
135
+
136
+ const origins = emptyOrigins();
137
+ for (const [origin, entry] of Object.entries(parsed.origins)) {
138
+ if (!isCredentialEntry(entry)) {
139
+ throw new CredentialsInvalidError("The credentials file is invalid.");
140
+ }
141
+ origins[origin] = {
142
+ access_token: entry.access_token,
143
+ token_type: entry.token_type,
144
+ created_at: entry.created_at,
145
+ };
146
+ }
147
+ return { format: CREDENTIALS_FORMAT, origins };
148
+ }
149
+
150
+ /**
151
+ * Stores (or replaces) the credential for one origin, keeping the others.
152
+ *
153
+ * @param {CredentialStore} store
154
+ * @param {string} origin
155
+ * @param {CredentialEntry} entry
156
+ */
157
+ export function writeCredential(store, origin, entry) {
158
+ withStoreLock(store, () => {
159
+ const credentials = readCredentials(store);
160
+ credentials.origins[origin] = entry;
161
+ saveCredentials(store, credentials);
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Removes the credential for one origin. With `accessToken`, removes it only
167
+ * while it still holds that token, so a newer login saved in the meantime is
168
+ * kept.
169
+ *
170
+ * @param {CredentialStore} store
171
+ * @param {string} origin
172
+ * @param {{accessToken?: string}} [options]
173
+ * @returns {boolean} whether an entry was removed
174
+ */
175
+ export function deleteCredential(store, origin, { accessToken } = {}) {
176
+ if (!Object.hasOwn(readCredentials(store).origins, origin)) return false;
177
+
178
+ return withStoreLock(store, () => {
179
+ const credentials = readCredentials(store);
180
+ const entry = credentials.origins[origin];
181
+ if (
182
+ entry === undefined ||
183
+ (accessToken !== undefined && entry.access_token !== accessToken)
184
+ )
185
+ return false;
186
+ delete credentials.origins[origin];
187
+ saveCredentials(store, credentials);
188
+ return true;
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Returns a memoized, never-throwing reader of stored access tokens keyed by
194
+ * origin. An unreadable or malformed file reads as empty.
195
+ *
196
+ * @param {CredentialStore} [store]
197
+ * @returns {() => Readonly<Record<string, string>>}
198
+ */
199
+ export function storedTokenReader(store = {}) {
200
+ /** @type {Record<string, string> | undefined} */
201
+ let tokens;
202
+ return () => {
203
+ if (tokens !== undefined) return tokens;
204
+ /** @type {Record<string, string>} */
205
+ const loaded = Object.create(null);
206
+ try {
207
+ for (const [origin, entry] of Object.entries(
208
+ readCredentials(store).origins,
209
+ )) {
210
+ loaded[origin] = entry.access_token;
211
+ }
212
+ } catch (error) {
213
+ if (
214
+ !(error instanceof CredentialsInvalidError) &&
215
+ !isFileSystemError(error)
216
+ )
217
+ throw error;
218
+ }
219
+ tokens = loaded;
220
+ return tokens;
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Runs `callback` while holding `credentials.json.lock`, so concurrent
226
+ * processes cannot interleave a read-modify-write and lose each other's
227
+ * entries. Reads need no lock because each save is an atomic rename.
228
+ *
229
+ * @template T
230
+ * @param {CredentialStore} store
231
+ * @param {() => T} callback
232
+ * @returns {T}
233
+ */
234
+ function withStoreLock(store, callback) {
235
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
236
+ const directory = path.dirname(credentialsPath(store));
237
+ const lock = path.join(directory, "credentials.json.lock");
238
+ const deadline = Date.now() + (store.lockTimeoutMs ?? LOCK_TIMEOUT_MS);
239
+
240
+ fileSystem.mkdirSync(directory, { recursive: true, mode: 0o700 });
241
+ while (true) {
242
+ try {
243
+ fileSystem.writeFileSync(lock, `${process.pid}\n`, {
244
+ flag: "wx",
245
+ mode: 0o600,
246
+ });
247
+ break;
248
+ } catch (error) {
249
+ if (!isExistingFileError(error)) throw error;
250
+ }
251
+ if (Date.now() >= deadline) {
252
+ throw new CredentialsLockedError(
253
+ "Another process is updating the credentials file.",
254
+ );
255
+ }
256
+ sleep(LOCK_RETRY_MS);
257
+ }
258
+
259
+ try {
260
+ return callback();
261
+ } finally {
262
+ try {
263
+ fileSystem.rmSync(lock, { force: true });
264
+ } catch {
265
+ // The callback's outcome matters more; a leftover lock is reported later.
266
+ }
267
+ }
268
+ }
269
+
270
+ /** @param {number} milliseconds */
271
+ function sleep(milliseconds) {
272
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
273
+ }
274
+
275
+ /** @param {CredentialStore} store @param {Credentials} credentials */
276
+ function saveCredentials(store, credentials) {
277
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
278
+ const target = credentialsPath(store);
279
+ const directory = path.dirname(target);
280
+ const temporaryId =
281
+ store.createTemporaryId?.() ?? randomBytes(8).toString("hex");
282
+ const temporary = path.join(
283
+ directory,
284
+ `.credentials.json.${temporaryId}.tmp`,
285
+ );
286
+
287
+ try {
288
+ fileSystem.writeFileSync(
289
+ temporary,
290
+ `${JSON.stringify(credentials, null, 2)}\n`,
291
+ { flag: "wx", mode: 0o600, flush: true },
292
+ );
293
+ fileSystem.renameSync(temporary, target);
294
+ } catch (error) {
295
+ try {
296
+ fileSystem.rmSync(temporary, { force: true });
297
+ } catch {
298
+ // The original failure is the useful one.
299
+ }
300
+ throw error;
301
+ }
302
+ }
303
+
304
+ /** @returns {Credentials} */
305
+ function emptyCredentials() {
306
+ return { format: CREDENTIALS_FORMAT, origins: emptyOrigins() };
307
+ }
308
+
309
+ /**
310
+ * Origins are keyed by URL origin; a null prototype keeps keys such as
311
+ * `__proto__` inert.
312
+ *
313
+ * @returns {Record<string, CredentialEntry>}
314
+ */
315
+ function emptyOrigins() {
316
+ return Object.create(null);
317
+ }
318
+
319
+ /** @param {unknown} value @returns {value is CredentialEntry} */
320
+ function isCredentialEntry(value) {
321
+ return (
322
+ isRecord(value) &&
323
+ typeof value.access_token === "string" &&
324
+ value.access_token.length > 0 &&
325
+ typeof value.token_type === "string" &&
326
+ typeof value.created_at === "string"
327
+ );
328
+ }
329
+
330
+ /** @param {unknown} error */
331
+ function isExistingFileError(error) {
332
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
333
+ }
334
+
335
+ /** @param {unknown} error */
336
+ function isMissingFileError(error) {
337
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
338
+ }
339
+
340
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
341
+ function isRecord(value) {
342
+ return typeof value === "object" && value !== null && !Array.isArray(value);
343
+ }