dsh-devdock 2.5.0 → 3.0.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/src/host/store.js DELETED
@@ -1,1063 +0,0 @@
1
- /**
2
- * dsh-push — durable Host state (accounts + settings + push memory).
3
- *
4
- * Everything the Host half remembers between requests lives in ONE JSON
5
- * document under the DSH home:
6
- *
7
- * $DSH_HOME/push/state.json (or ~/.dsh/push/state.json)
8
- *
9
- * WHY ONE DOCUMENT: accounts and settings change together (activating an
10
- * account, flipping `gitPath`), so splitting them across files would create a
11
- * torn-state window for no benefit. The file also carries the ACCESS TOKENS,
12
- * which is why every read used for the wire goes through {@link publicAccount}
13
- * and every error string goes through {@link redactSecrets}.
14
- *
15
- * WHY ATOMIC WRITE (temp + rename): a profile process that dies mid-write must
16
- * never leave a truncated JSON document behind — the next boot would lose
17
- * every account the user added. `rename` over the existing file is atomic on
18
- * both POSIX and Windows (MoveFileEx with REPLACE_EXISTING).
19
- *
20
- * @module src/host/store.js
21
- */
22
-
23
- import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
24
- import { spawn } from 'node:child_process';
25
- import { randomBytes } from 'node:crypto';
26
- import { homedir } from 'node:os';
27
- import { join } from 'node:path';
28
-
29
- /** Settings the document always carries, in the exact shape of CONTRACT §1. */
30
- export const DEFAULT_SETTINGS = Object.freeze({
31
- oauthClientId: '',
32
- defaultRemote: 'origin',
33
- showPrivate: true,
34
- gitPath: '',
35
- });
36
-
37
- /**
38
- * Current document schema version. Bump only with a migration below.
39
- *
40
- * `pushMemory` (CONTRACT §3b) was added WITHOUT a version bump on purpose: it
41
- * is an additive, self-degrading table (`normalizeState` fills `{}` when it is
42
- * absent), and a bump would force a migration for a document that is already
43
- * valid under both versions.
44
- */
45
- const STATE_VERSION = 1;
46
-
47
- /**
48
- * Resolve the DSH home directory.
49
- *
50
- * Mirrors the documented convention (`$DSH_HOME` when set and non-empty,
51
- * otherwise `~/.dsh`) rather than reading a service, so this module stays
52
- * importable by a bare smoke-test script that never boots cordis.
53
- *
54
- * @returns {string} absolute home directory.
55
- */
56
- export function resolveDshHome() {
57
- const configured = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : '';
58
- return configured !== '' ? configured : join(homedir(), '.dsh');
59
- }
60
-
61
- /**
62
- * Redact secrets from a string before it can reach a log line, a JSON response
63
- * or a git output field.
64
- *
65
- * WHY BOTH LISTS: we know the tokens we hold (exact substring removal), but a
66
- * token can also appear inside a message we did not build — git echoing a
67
- * header, an upstream error body quoting an Authorization value. The pattern
68
- * pass catches GitHub's documented token prefixes, and the last rule masks
69
- * any URL userinfo (`https://x-access-token:TOKEN@github.com`).
70
- *
71
- * @param {unknown} text value to sanitize (coerced with String()).
72
- * @param {Iterable<string>} [secrets] exact secret strings to remove.
73
- * @returns {string} the sanitized text.
74
- */
75
- export function redactSecrets(text, secrets = []) {
76
- let out = String(text ?? '');
77
- for (const secret of secrets) {
78
- if (typeof secret === 'string' && secret.length >= 8) out = out.split(secret).join('***');
79
- }
80
- return out
81
- .replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b/g, '***')
82
- .replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, '***')
83
- .replace(/(https?:\/\/)[^\s/@]+@/g, '$1***@');
84
- }
85
-
86
- /**
87
- * The wire-safe projection of a stored account: the token is REMOVED.
88
- *
89
- * @param {object} account stored account record (carries `token`).
90
- * @returns {object} CONTRACT §1 `Account`.
91
- */
92
- export function publicAccount(account) {
93
- return {
94
- id: String(account.id ?? ''),
95
- login: String(account.login ?? ''),
96
- name: account.name ?? null,
97
- avatarUrl: account.avatarUrl ?? null,
98
- htmlUrl: account.htmlUrl ?? null,
99
- tokenKind: account.tokenKind === 'oauth' ? 'oauth' : 'pat',
100
- scopes: Array.isArray(account.scopes) ? account.scopes.filter((s) => typeof s === 'string') : [],
101
- addedAt: typeof account.addedAt === 'string' ? account.addedAt : new Date(0).toISOString(),
102
- lastUsedAt: typeof account.lastUsedAt === 'string' ? account.lastUsedAt : null,
103
- };
104
- }
105
-
106
- /**
107
- * 归一化一条 npm 账号。
108
- *
109
- * 与 GitHub 账号同样只保留必要字段;`login` 是 npm 用户名,`token` 是
110
- * Granular Access Token。没有令牌或没有用户名的条目直接丢弃,避免留下
111
- * 一条"看起来存在但用不了"的账号。
112
- *
113
- * @param {object} raw
114
- * @returns {object|undefined}
115
- */
116
- /**
117
- * 归一化一条 Cloudflare 账号。
118
- *
119
- * 支持两种凭据形态,`authKind` 区分:
120
- * - 'token' —— API Token(cfut_ / cfat_ 或旧 40 位字母数字),只存 token
121
- * - 'global' —— Global API Key(cfk_ 或旧 37-45 位十六进制),存 email + token(=Key)
122
- *
123
- * 两种都必须填全才算有效;不完整的条目直接丢弃,避免留下「看起来存在但用不了」的账号。
124
- *
125
- * @param {object} raw
126
- * @returns {object|undefined}
127
- */
128
- function normalizeCloudflareAccount(raw) {
129
- if (!raw || typeof raw !== 'object') return undefined;
130
- const authKind = raw.authKind === 'global' ? 'global' : 'token';
131
- const token = typeof raw.token === 'string' ? raw.token.trim() : '';
132
- const email = typeof raw.email === 'string' ? raw.email.trim() : '';
133
- if (token === '') return undefined;
134
- if (authKind === 'global' && email === '') return undefined;
135
- const fallbackLogin = authKind === 'global' ? email : 'Cloudflare 账号';
136
- const login = typeof raw.login === 'string' && raw.login.trim() !== ''
137
- ? raw.login.trim()
138
- : fallbackLogin;
139
- return {
140
- id: typeof raw.id === 'string' && raw.id !== '' ? raw.id : 'cf:' + login.toLowerCase(),
141
- authKind,
142
- login,
143
- email,
144
- token,
145
- accountId: typeof raw.accountId === 'string' ? raw.accountId : '',
146
- accountName: typeof raw.accountName === 'string' ? raw.accountName : '',
147
- addedAt: typeof raw.addedAt === 'string' ? raw.addedAt : new Date(0).toISOString(),
148
- lastUsedAt: typeof raw.lastUsedAt === 'string' ? raw.lastUsedAt : null,
149
- };
150
- }
151
-
152
- function normalizeNpmAccount(raw) {
153
- if (!raw || typeof raw !== 'object') return undefined;
154
- const login = typeof raw.login === 'string' ? raw.login.trim() : '';
155
- const token = typeof raw.token === 'string' ? raw.token : '';
156
- if (login === '' || token === '') return undefined;
157
- return {
158
- id: typeof raw.id === 'string' && raw.id !== '' ? raw.id : 'npm:' + login.toLowerCase(),
159
- login,
160
- token,
161
- tokenKind: raw.tokenKind === 'classic' ? 'classic' : 'granular',
162
- addedAt: typeof raw.addedAt === 'string' ? raw.addedAt : new Date(0).toISOString(),
163
- lastUsedAt: typeof raw.lastUsedAt === 'string' ? raw.lastUsedAt : null,
164
- };
165
- }
166
-
167
- /** A fresh, empty document. */
168
- function emptyState() {
169
- return {
170
- version: STATE_VERSION,
171
- accounts: [],
172
- activeAccountId: null,
173
- settings: { ...DEFAULT_SETTINGS },
174
- // CONTRACT §3b: (仓库根, 分支) → 上次成功推送的目标. Always present so a
175
- // caller never has to distinguish "absent" from "empty".
176
- pushMemory: {},
177
- // CONTRACT §3d: the user's SAVED review prompts. Built-ins live in code,
178
- // so this table only ever holds presets the user created.
179
- reviewPresets: [],
180
- // DevDock 的 npm 模块:与 GitHub 账号分开存。两者的令牌形态、校验
181
- // 端点和可用动作都不同,混在一张表里会让每个消费者都要判断 provider。
182
- npmAccounts: [],
183
- activeNpmAccountId: null,
184
- // Cloudflare 模块:令牌是 Cloudflare API Token 或 Global API Key,
185
- // 校验端点是 api.cloudflare.com,动作是 Pages/Workers/Zones 管理。
186
- cloudflareAccounts: [],
187
- activeCloudflareAccountId: null,
188
- };
189
- }
190
-
191
- /**
192
- * Normalize a repository root into the key prefix used by `pushMemory`.
193
- *
194
- * THE PROBLEM THIS SOLVES: the same repository reaches the Host as any of
195
- * `D:\x\y`, `D:/x/y`, `d:\x\y\` — the client sends the session cwd, the user may
196
- * type a path, and git itself prints forward slashes on Windows. Remembering
197
- * "which target did I push this branch to" must not depend on which spelling
198
- * arrived, so every variant collapses to ONE string:
199
- *
200
- * absolute → forward slashes → lowercase Windows drive letter → no trailing
201
- * slash.
202
- *
203
- * The rest of the path keeps its case: Windows is case-insensitive but POSIX is
204
- * not, and a Linux user's `/home/A` and `/home/a` are different repositories.
205
- * Lowercasing the whole path would silently merge them.
206
- *
207
- * @param {string} root absolute repository root as reported by git.
208
- * @returns {string} the normalized form (`''` for a non-string/empty input).
209
- */
210
- export function normalizeRepoRoot(root) {
211
- const raw = typeof root === 'string' ? root.trim() : '';
212
- if (raw === '') return '';
213
- // Windows accepts both separators; forward-slash everything first so the
214
- // drive-letter rule below does not need two forms.
215
- let out = raw.replace(/\\/g, '/');
216
- // `D:` and `d:` are the same drive on Windows; only the drive letter is
217
- // case-folded (see above), never the rest of the path.
218
- out = out.replace(/^([A-Za-z]):\//, (_match, letter) => `${String(letter).toLowerCase()}:/`);
219
- // `D:/x/y/`, `D:/x/y//` → `D:/x/y`. The root `/` stays `/`.
220
- if (out.length > 1) out = out.replace(/\/+$/, '');
221
- return out;
222
- }
223
-
224
- /**
225
- * The `pushMemory` table key for (repository, branch).
226
- *
227
- * `|` is the separator because it cannot appear in a Windows path and is
228
- * extremely unusual in a POSIX one, so the key round-trips without escaping.
229
- *
230
- * @param {string} root repository root (normalized here).
231
- * @param {string} branch branch name.
232
- * @returns {string} `<normalizedRepoRoot>|<branch>`.
233
- */
234
- export function pushMemoryKey(root, branch) {
235
- return `${normalizeRepoRoot(root)}|${String(branch ?? '').trim()}`;
236
- }
237
-
238
- /**
239
- * Coerce the saved review-preset list (CONTRACT §3d).
240
- *
241
- * A preset needs an id, a title and a prompt to be usable; anything missing one
242
- * is dropped. Duplicate ids keep the first occurrence, so a hand-edited
243
- * document cannot make the panel render two cards with the same key.
244
- *
245
- * @param {unknown} raw
246
- * @returns {object[]}
247
- */
248
- function normalizeReviewPresets(raw) {
249
- if (!Array.isArray(raw)) return [];
250
- const out = [];
251
- const seen = new Set();
252
- for (const candidate of raw) {
253
- if (!candidate || typeof candidate !== 'object') continue;
254
- const id = typeof candidate.id === 'string' ? candidate.id.trim() : '';
255
- const title = typeof candidate.title === 'string' ? candidate.title.trim() : '';
256
- const prompt = typeof candidate.prompt === 'string' ? candidate.prompt : '';
257
- if (id === '' || title === '' || prompt.trim() === '') continue;
258
- if (seen.has(id)) continue;
259
- seen.add(id);
260
- out.push({
261
- id,
262
- title,
263
- prompt,
264
- description: typeof candidate.description === 'string' ? candidate.description : '',
265
- category: typeof candidate.category === 'string' && candidate.category !== ''
266
- ? candidate.category
267
- : 'custom',
268
- builtin: false,
269
- createdAt: typeof candidate.createdAt === 'string' ? candidate.createdAt : new Date(0).toISOString(),
270
- updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : undefined,
271
- });
272
- }
273
- return out;
274
- }
275
-
276
- /**
277
- * Coerce one persisted memory entry, dropping anything unusable.
278
- * @param {unknown} raw
279
- * @returns {object|undefined}
280
- */
281
- function normalizePushMemoryEntry(raw) {
282
- if (!raw || typeof raw !== 'object') return undefined;
283
- const remote = typeof raw.remote === 'string' ? raw.remote.trim() : '';
284
- const owner = typeof raw.owner === 'string' ? raw.owner.trim() : '';
285
- const repo = typeof raw.repo === 'string' ? raw.repo.trim() : '';
286
- const ref = typeof raw.ref === 'string' ? raw.ref.trim() : '';
287
- if (owner === '' || repo === '') return undefined;
288
- return {
289
- // A URL-pushed target has no remote name; the contract allows that, so an
290
- // empty `remote` is preserved verbatim instead of rejecting the entry.
291
- remote,
292
- owner,
293
- repo,
294
- ref,
295
- at: typeof raw.at === 'string' && raw.at !== '' ? raw.at : new Date(0).toISOString(),
296
- };
297
- }
298
-
299
- /**
300
- * Coerce the persisted `pushMemory` table.
301
- *
302
- * A corrupt table (an array, a string, `null`, a file hand-edited into
303
- * nonsense) degrades to `{}` — exactly like a malformed account is dropped, so
304
- * one bad key can never take /state down.
305
- *
306
- * @param {unknown} raw
307
- * @returns {Record<string, object>}
308
- */
309
- function normalizePushMemory(raw) {
310
- const out = {};
311
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
312
- for (const [key, value] of Object.entries(raw)) {
313
- const entry = normalizePushMemoryEntry(value);
314
- if (!entry) continue;
315
- const at = key.lastIndexOf('|');
316
- if (at <= 0 || at === key.length - 1) continue;
317
- const root = normalizeRepoRoot(key.slice(0, at));
318
- const branch = key.slice(at + 1).trim();
319
- if (root === '' || branch === '') continue;
320
- // Re-key through the normalizer so a hand-written `D:\x\y|main` collides
321
- // with the canonical entry instead of becoming a second one.
322
- out[`${root}|${branch}`] = entry;
323
- }
324
- return out;
325
- }
326
-
327
- /** Coerce one persisted account record, dropping anything unusable. */
328
- function normalizeAccount(raw) {
329
- if (!raw || typeof raw !== 'object') return undefined;
330
- const login = typeof raw.login === 'string' ? raw.login.trim() : '';
331
- const token = typeof raw.token === 'string' ? raw.token : '';
332
- if (login === '' || token === '') return undefined;
333
- return {
334
- id: typeof raw.id === 'string' && raw.id !== '' ? raw.id : login.toLowerCase(),
335
- login,
336
- name: typeof raw.name === 'string' ? raw.name : null,
337
- avatarUrl: typeof raw.avatarUrl === 'string' ? raw.avatarUrl : null,
338
- htmlUrl: typeof raw.htmlUrl === 'string' ? raw.htmlUrl : null,
339
- token,
340
- tokenKind: raw.tokenKind === 'oauth' ? 'oauth' : 'pat',
341
- scopes: Array.isArray(raw.scopes) ? raw.scopes.filter((s) => typeof s === 'string') : [],
342
- addedAt: typeof raw.addedAt === 'string' ? raw.addedAt : new Date().toISOString(),
343
- lastUsedAt: typeof raw.lastUsedAt === 'string' ? raw.lastUsedAt : null,
344
- };
345
- }
346
-
347
- /** Coerce the persisted settings object into the contract shape. */
348
- function normalizeSettings(raw) {
349
- const out = { ...DEFAULT_SETTINGS };
350
- if (!raw || typeof raw !== 'object') return out;
351
- if (typeof raw.oauthClientId === 'string') out.oauthClientId = raw.oauthClientId.trim();
352
- if (typeof raw.defaultRemote === 'string' && raw.defaultRemote.trim() !== '') out.defaultRemote = raw.defaultRemote.trim();
353
- if (typeof raw.showPrivate === 'boolean') out.showPrivate = raw.showPrivate;
354
- if (typeof raw.gitPath === 'string') out.gitPath = raw.gitPath.trim();
355
- return out;
356
- }
357
-
358
- /**
359
- * Drop a leading UTF-8 byte-order mark.
360
- *
361
- * `JSON.parse` treats U+FEFF as an unexpected token, so a document saved with
362
- * a BOM (Windows PowerShell 5.1's `-Encoding utf8`, many editors) parses as
363
- * "corrupt" and its accounts silently vanish. Trimming one leading BOM is
364
- * always correct for JSON, whose grammar allows no leading character.
365
- *
366
- * @param {string} text raw document text.
367
- * @returns {string} the same text without a leading BOM.
368
- */
369
- function stripBom(text) {
370
- return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
371
- }
372
-
373
- /**
374
- * Normalize a whole persisted document.
375
- *
376
- * A malformed sibling (an account without a token, an activeAccountId that
377
- * points at a removed login) is DROPPED rather than throwing: a hand-edited or
378
- * half-migrated state file must degrade to "fewer accounts", never to a plugin
379
- * that cannot answer /state at all.
380
- *
381
- * @param {unknown} raw parsed JSON.
382
- * @returns {object} a valid state document.
383
- */
384
- function normalizeState(raw) {
385
- const state = emptyState();
386
- if (!raw || typeof raw !== 'object') return state;
387
- if (Array.isArray(raw.accounts)) {
388
- const seen = new Set();
389
- for (const candidate of raw.accounts) {
390
- const account = normalizeAccount(candidate);
391
- if (!account || seen.has(account.id)) continue;
392
- seen.add(account.id);
393
- state.accounts.push(account);
394
- }
395
- }
396
- state.settings = normalizeSettings(raw.settings);
397
- // CONTRACT §3b: an absent or corrupt table is `{}`, never an exception.
398
- state.pushMemory = normalizePushMemory(raw.pushMemory);
399
- // CONTRACT §3d: same rule for the saved review prompts. A malformed entry is
400
- // dropped rather than failing the whole document — a hand-edited preset list
401
- // must degrade to "fewer presets", never to a plugin that cannot answer.
402
- state.reviewPresets = normalizeReviewPresets(raw.reviewPresets);
403
- // npm 账号与 GitHub 账号是两张独立的表,各自归一化、各自记 active。
404
- const npmSeen = new Set();
405
- for (const entry of Array.isArray(raw.npmAccounts) ? raw.npmAccounts : []) {
406
- const account = normalizeNpmAccount(entry);
407
- if (!account || npmSeen.has(account.id)) continue;
408
- npmSeen.add(account.id);
409
- state.npmAccounts.push(account);
410
- }
411
- const activeNpm = typeof raw.activeNpmAccountId === 'string' ? raw.activeNpmAccountId : null;
412
- state.activeNpmAccountId = activeNpm !== null && state.npmAccounts.some((a) => a.id === activeNpm)
413
- ? activeNpm
414
- : (state.npmAccounts[0]?.id ?? null);
415
-
416
- // Cloudflare 账号表,与 npm 表同样:各自归一化、各自记 active。
417
- const cfSeen = new Set();
418
- for (const entry of Array.isArray(raw.cloudflareAccounts) ? raw.cloudflareAccounts : []) {
419
- const account = normalizeCloudflareAccount(entry);
420
- if (!account || cfSeen.has(account.id)) continue;
421
- cfSeen.add(account.id);
422
- state.cloudflareAccounts.push(account);
423
- }
424
- const activeCf = typeof raw.activeCloudflareAccountId === 'string' ? raw.activeCloudflareAccountId : null;
425
- state.activeCloudflareAccountId = activeCf !== null && state.cloudflareAccounts.some((a) => a.id === activeCf)
426
- ? activeCf
427
- : (state.cloudflareAccounts[0]?.id ?? null);
428
-
429
- const active = typeof raw.activeAccountId === 'string' ? raw.activeAccountId : null;
430
- state.activeAccountId = active !== null && state.accounts.some((a) => a.id === active)
431
- ? active
432
- : (state.accounts[0]?.id ?? null);
433
- return state;
434
- }
435
-
436
- /**
437
- * Durable store for the plugin's accounts + settings.
438
- *
439
- * Reads are cached in memory and invalidated on every write (the file is
440
- * tiny; the cache exists so a burst of /state calls from the panel does not
441
- * hammer the disk). Writes are serialized through one promise chain so two
442
- * concurrent mutations can never interleave their read-modify-write.
443
- */
444
- /**
445
- * Restrict a secret-bearing file to the current user.
446
- *
447
- * POSIX honours `mode: 0o600` directly. Windows does not: NTFS uses ACLs and
448
- * Node's mode is mostly ignored, so the file would only be as private as the
449
- * ACL it inherits. Inheriting from %USERPROFILE% is fine; inheriting from a
450
- * shared directory is not. `icacls` is therefore applied explicitly, and any
451
- * failure is ignored — the write itself already succeeded.
452
- *
453
- * @param {string} target absolute path of the written file.
454
- * @returns {Promise<void>}
455
- */
456
- async function hardenPermissions(target) {
457
- if (process.platform !== 'win32') return;
458
- const user = process.env.USERNAME;
459
- if (typeof user !== 'string' || user === '') return;
460
- try {
461
- const child = spawn(
462
- 'icacls',
463
- // Remove inherited entries, then grant only the current user full control.
464
- [target, '/inheritance:r', '/grant:r', `${user}:F`],
465
- { windowsHide: true, stdio: 'ignore' },
466
- );
467
- await new Promise((resolve) => {
468
- child.on('error', resolve);
469
- child.on('exit', resolve);
470
- });
471
- } catch {
472
- // best effort: a hardened file is a bonus, not a requirement for the write
473
- }
474
- }
475
-
476
- export class GithubLinkStore {
477
- /** @type {string} absolute directory holding the state document. */
478
- #dir;
479
- /** @type {string} absolute path of the state document. */
480
- #file;
481
- /** @type {string} pre-rename document, adopted only while `#file` is absent. */
482
- #legacyFile;
483
- /** @type {object|undefined} last successfully read/written document. */
484
- #cache;
485
- /** @type {Promise<unknown>} mutation queue tail. */
486
- #queue = Promise.resolve();
487
-
488
- /**
489
- * @param {{home?: string}} [options] `home` overrides the DSH home (tests).
490
- */
491
- constructor(options = {}) {
492
- const home = options.home ?? resolveDshHome();
493
- this.#dir = join(home, 'push');
494
- this.#file = join(this.#dir, 'state.json');
495
- // The bundle was published as `dsh-github-link` before it was renamed, and
496
- // at least one build stored its accounts under that old directory. Nobody
497
- // should have to sign in again because a package changed its name, so an
498
- // existing old document is adopted on first read when the new one is
499
- // absent. Reading it is enough: the first write lands in the new location.
500
- this.#legacyFile = join(home, 'github-link', 'state.json');
501
- }
502
-
503
- /**
504
- * The document to read: the current one, else a pre-rename one.
505
- * @returns {Promise<{file: string, raw: string}|undefined>}
506
- */
507
- async #readSource() {
508
- for (const file of [this.#file, this.#legacyFile]) {
509
- if (!file) continue;
510
- try {
511
- return { file, raw: await readFile(file, 'utf8') };
512
- } catch (error) {
513
- if (error?.code === 'ENOENT') continue;
514
- // Unreadable-but-present (ACL, EACCES) must not be reported as "no
515
- // accounts", and must not silently fall through to the legacy path.
516
- throw error;
517
- }
518
- }
519
- return undefined;
520
- }
521
-
522
- /** Absolute path of the state document (diagnostics only — never sent). */
523
- get statePath() {
524
- return this.#file;
525
- }
526
-
527
- /** Read the document from disk (cached), falling back to an empty one. */
528
- async read() {
529
- if (this.#cache) return this.#cache;
530
- let source;
531
- try {
532
- source = await this.#readSource();
533
- } catch (error) {
534
- // Unreadable-but-present (ACL, EACCES) must not be reported as "no
535
- // accounts": surface it so the caller can show a real diagnosis.
536
- throw error;
537
- }
538
- if (source === undefined) {
539
- this.#cache = emptyState();
540
- return this.#cache;
541
- }
542
- let parsed;
543
- try {
544
- // Strip a UTF-8 BOM before parsing. A user (or an editor, or a
545
- // PowerShell `Set-Content -Encoding utf8` on Windows PowerShell 5.1)
546
- // writing this file by hand produces `EF BB BF` + `{...}`, and
547
- // `JSON.parse` rejects the BOM as an unexpected token — which would
548
- // quietly drop every saved account and token into the empty-state path.
549
- // Accepting the BOM costs one comparison and makes hand-recovery safe.
550
- parsed = JSON.parse(stripBom(source.raw));
551
- } catch {
552
- // A corrupt document is preserved on disk (we do not overwrite until the
553
- // next write) but the in-memory view starts empty.
554
- parsed = undefined;
555
- }
556
- this.#cache = normalizeState(parsed);
557
- return this.#cache;
558
- }
559
-
560
- /**
561
- * Atomically replace the document.
562
- *
563
- * Writes a sibling temp file (mode 0600) and renames it over the target, so
564
- * a crash leaves either the old or the new document — never a partial one.
565
- *
566
- * @param {object} state document to persist (already normalized).
567
- * @returns {Promise<object>} the persisted document.
568
- */
569
- async write(state) {
570
- const normalized = normalizeState(state);
571
- await mkdir(this.#dir, { recursive: true, mode: 0o700 });
572
- const temp = `${this.#file}.${randomBytes(6).toString('hex')}.tmp`;
573
- const body = `${JSON.stringify(normalized, null, 2)}\n`;
574
- await writeFile(temp, body, { encoding: 'utf8', mode: 0o600 });
575
- if (process.platform !== 'win32') {
576
- // `mode` on writeFile is masked by umask; an explicit chmod is what makes
577
- // the 0600 guarantee real for the file that now holds the tokens.
578
- await chmod(temp, 0o600).catch(() => {});
579
- }
580
- await rename(temp, this.#file);
581
- // Windows ignores the mode above; make the ACL explicit instead.
582
- await hardenPermissions(this.#file);
583
- this.#cache = normalized;
584
- return normalized;
585
- }
586
-
587
- /**
588
- * Run one read-modify-write mutation, serialized against every other one.
589
- *
590
- * @template T
591
- * @param {(state: object) => (T|Promise<T>)} mutator receives a deep-enough
592
- * copy to mutate freely; returning a value resolves the call with it.
593
- * @returns {Promise<T>} the mutator's return value.
594
- */
595
- mutate(mutator) {
596
- const run = async () => {
597
- const current = await this.read();
598
- // Clone so a throwing mutator cannot leave a half-applied cache behind.
599
- const draft = {
600
- version: STATE_VERSION,
601
- accounts: current.accounts.map((a) => ({ ...a })),
602
- activeAccountId: current.activeAccountId,
603
- settings: { ...current.settings },
604
- // The push-memory table is cloned too: a mutator that rewrites one
605
- // branch's entry must not alias the cached object.
606
- pushMemory: Object.fromEntries(
607
- Object.entries(current.pushMemory ?? {}).map(([key, entry]) => [key, { ...entry }]),
608
- ),
609
- // Saved review prompts are cloned for the same reason. Omitting this
610
- // table made every write silently DROP the presets a user had just
611
- // saved: the mutation landed, the save reported success, and the next
612
- // read found an empty list.
613
- reviewPresets: (current.reviewPresets ?? []).map((preset) => ({ ...preset })),
614
- // The npm account table is cloned for exactly the reason above: a
615
- // field missing from this list is silently DROPPED on every write.
616
- npmAccounts: (current.npmAccounts ?? []).map((account) => ({ ...account })),
617
- activeNpmAccountId: current.activeNpmAccountId,
618
- // Cloudflare 账号表同理克隆:漏掉就会在每次写入时静默丢弃。
619
- cloudflareAccounts: (current.cloudflareAccounts ?? []).map((account) => ({ ...account })),
620
- activeCloudflareAccountId: current.activeCloudflareAccountId,
621
- };
622
- const result = await mutator(draft);
623
- await this.write(draft);
624
- return result;
625
- };
626
- // Chain on the tail, and keep the chain alive after a rejection so one
627
- // failed write does not deadlock every later mutation.
628
- const queued = this.#queue.then(run, run);
629
- this.#queue = queued.then(() => {}, () => {});
630
- return queued;
631
- }
632
-
633
- /**
634
- * Find one stored account (WITH its token) by local id.
635
- * @param {string} accountId
636
- * @returns {Promise<object|undefined>}
637
- */
638
- async accountById(accountId) {
639
- const state = await this.read();
640
- return state.accounts.find((account) => account.id === accountId);
641
- }
642
-
643
- /**
644
- * The active account WITH its token, or undefined when nobody is signed in.
645
- * @returns {Promise<object|undefined>}
646
- */
647
- async activeAccount() {
648
- const state = await this.read();
649
- if (state.activeAccountId === null) return undefined;
650
- return state.accounts.find((account) => account.id === state.activeAccountId);
651
- }
652
-
653
- /**
654
- * Token strings currently held — the redaction list for git/API output.
655
- * @returns {Promise<string[]>}
656
- */
657
- async secrets() {
658
- const state = await this.read();
659
- // npm 令牌同样要参与脱敏:它出现在错误文本里就是一次泄漏。
660
- return [
661
- ...state.accounts.map((account) => account.token),
662
- ...(state.npmAccounts ?? []).map((account) => account.token),
663
- ...(state.cloudflareAccounts ?? []).map((account) => account.token),
664
- ].filter((token) => typeof token === 'string' && token !== '');
665
- }
666
-
667
- /**
668
- * npm 账号列表(不带令牌)。
669
- * @returns {Promise<{accounts: object[], activeId: string|null}>}
670
- */
671
- async npmAccounts() {
672
- const state = await this.read();
673
- return {
674
- activeId: state.activeNpmAccountId,
675
- accounts: state.npmAccounts.map((account) => ({
676
- id: account.id,
677
- login: account.login,
678
- tokenKind: account.tokenKind,
679
- addedAt: account.addedAt,
680
- lastUsedAt: account.lastUsedAt,
681
- })),
682
- };
683
- }
684
-
685
- /**
686
- * 当前 npm 账号(带令牌),没有则 undefined。
687
- * @returns {Promise<object|undefined>}
688
- */
689
- async activeNpmAccount() {
690
- const state = await this.read();
691
- if (state.activeNpmAccountId === null) return undefined;
692
- return state.npmAccounts.find((account) => account.id === state.activeNpmAccountId);
693
- }
694
-
695
- /**
696
- * 保存(或更新)一条 npm 账号,并把它设为当前。
697
- * @param {{login: string, token: string, tokenKind?: string}} input
698
- * @returns {Promise<object>} 不含令牌的账号
699
- */
700
- async saveNpmAccount(input) {
701
- const account = normalizeNpmAccount({
702
- ...input,
703
- addedAt: new Date().toISOString(),
704
- });
705
- if (!account) throw new Error('npm 账号缺少用户名或令牌');
706
- await this.mutate((state) => {
707
- const index = state.npmAccounts.findIndex((row) => row.id === account.id);
708
- if (index >= 0) {
709
- state.npmAccounts[index] = { ...state.npmAccounts[index], ...account };
710
- } else {
711
- state.npmAccounts = [...state.npmAccounts, account];
712
- }
713
- state.activeNpmAccountId = account.id;
714
- return state;
715
- });
716
- return { id: account.id, login: account.login, tokenKind: account.tokenKind };
717
- }
718
-
719
- /**
720
- * 删除一条 npm 账号;删掉当前账号时自动切到剩下的第一条。
721
- * @param {string} id
722
- * @returns {Promise<boolean>}
723
- */
724
- async deleteNpmAccount(id) {
725
- return this.mutate((state) => {
726
- const before = state.npmAccounts.length;
727
- state.npmAccounts = state.npmAccounts.filter((account) => account.id !== id);
728
- if (state.npmAccounts.length === before) return false;
729
- if (state.activeNpmAccountId === id) {
730
- state.activeNpmAccountId = state.npmAccounts[0]?.id ?? null;
731
- }
732
- return true;
733
- });
734
- }
735
-
736
- /**
737
- * 切换当前 npm 账号。
738
- * @param {string} id
739
- * @returns {Promise<boolean>}
740
- */
741
- async setActiveNpmAccount(id) {
742
- return this.mutate((state) => {
743
- if (!state.npmAccounts.some((account) => account.id === id)) return false;
744
- state.activeNpmAccountId = id;
745
- return true;
746
- });
747
- }
748
-
749
- /**
750
- * 记录一次成功使用。
751
- * @param {string} id
752
- * @returns {Promise<void>}
753
- */
754
- async touchNpmAccount(id) {
755
- await this.mutate((state) => {
756
- const index = state.npmAccounts.findIndex((account) => account.id === id);
757
- if (index >= 0) state.npmAccounts[index].lastUsedAt = new Date().toISOString();
758
- return state;
759
- });
760
- }
761
-
762
- /* ---------------- Cloudflare 账号(第三张独立表) ---------------- */
763
-
764
- /**
765
- * Cloudflare 账号列表(不带令牌)。
766
- * @returns {Promise<{accounts: object[], activeId: string|null}>}
767
- */
768
- async cloudflareAccounts() {
769
- const state = await this.read();
770
- return {
771
- activeId: state.activeCloudflareAccountId,
772
- accounts: state.cloudflareAccounts.map((account) => ({
773
- id: account.id,
774
- authKind: account.authKind,
775
- login: account.login,
776
- email: account.email,
777
- accountId: account.accountId,
778
- accountName: account.accountName,
779
- addedAt: account.addedAt,
780
- lastUsedAt: account.lastUsedAt,
781
- })),
782
- };
783
- }
784
-
785
- /**
786
- * 当前 Cloudflare 账号(带令牌),没有则 undefined。
787
- * @returns {Promise<object|undefined>}
788
- */
789
- async activeCloudflareAccount() {
790
- const state = await this.read();
791
- if (state.activeCloudflareAccountId === null) return undefined;
792
- return state.cloudflareAccounts.find((account) => account.id === state.activeCloudflareAccountId);
793
- }
794
-
795
- /**
796
- * 保存(或更新)一条 Cloudflare 账号,并把它设为当前。
797
- * @param {{authKind?: string, login?: string, email?: string, token: string,
798
- * accountId?: string, accountName?: string}} input
799
- * @returns {Promise<object>} 不含令牌的账号
800
- */
801
- async saveCloudflareAccount(input) {
802
- const account = normalizeCloudflareAccount({
803
- ...input,
804
- addedAt: new Date().toISOString(),
805
- });
806
- if (!account) throw new Error('Cloudflare 账号缺少令牌');
807
- await this.mutate((state) => {
808
- const index = state.cloudflareAccounts.findIndex((row) => row.id === account.id);
809
- if (index >= 0) {
810
- state.cloudflareAccounts[index] = { ...state.cloudflareAccounts[index], ...account };
811
- } else {
812
- state.cloudflareAccounts = [...state.cloudflareAccounts, account];
813
- }
814
- state.activeCloudflareAccountId = account.id;
815
- return state;
816
- });
817
- return {
818
- id: account.id,
819
- authKind: account.authKind,
820
- login: account.login,
821
- email: account.email,
822
- accountId: account.accountId,
823
- accountName: account.accountName,
824
- };
825
- }
826
-
827
- /**
828
- * 删除一条 Cloudflare 账号;删掉当前账号时自动切到剩下的第一条。
829
- * @param {string} id
830
- * @returns {Promise<boolean>}
831
- */
832
- async deleteCloudflareAccount(id) {
833
- return this.mutate((state) => {
834
- const before = state.cloudflareAccounts.length;
835
- state.cloudflareAccounts = state.cloudflareAccounts.filter((account) => account.id !== id);
836
- if (state.cloudflareAccounts.length === before) return false;
837
- if (state.activeCloudflareAccountId === id) {
838
- state.activeCloudflareAccountId = state.cloudflareAccounts[0]?.id ?? null;
839
- }
840
- return true;
841
- });
842
- }
843
-
844
- /**
845
- * 切换当前 Cloudflare 账号。
846
- * @param {string} id
847
- * @returns {Promise<boolean>}
848
- */
849
- async setActiveCloudflareAccount(id) {
850
- return this.mutate((state) => {
851
- if (!state.cloudflareAccounts.some((account) => account.id === id)) return false;
852
- state.activeCloudflareAccountId = id;
853
- return true;
854
- });
855
- }
856
-
857
- /**
858
- * 更新一条 Cloudflare 账号的 accountId/accountName(登录后选了账户)。
859
- * @param {string} id
860
- * @param {{accountId?: string, accountName?: string}} patch
861
- * @returns {Promise<object>} 不含令牌的账号
862
- */
863
- async updateCloudflareAccount(id, patch) {
864
- return this.mutate((state) => {
865
- const index = state.cloudflareAccounts.findIndex((account) => account.id === id);
866
- if (index < 0) throw new Error('找不到这个 Cloudflare 账号');
867
- if (typeof patch.accountId === 'string') state.cloudflareAccounts[index].accountId = patch.accountId;
868
- if (typeof patch.accountName === 'string') state.cloudflareAccounts[index].accountName = patch.accountName;
869
- const account = state.cloudflareAccounts[index];
870
- return {
871
- id: account.id,
872
- authKind: account.authKind,
873
- login: account.login,
874
- email: account.email,
875
- accountId: account.accountId,
876
- accountName: account.accountName,
877
- };
878
- });
879
- }
880
-
881
- /**
882
- * 记录一次成功使用。
883
- * @param {string} id
884
- * @returns {Promise<void>}
885
- */
886
- async touchCloudflareAccount(id) {
887
- await this.mutate((state) => {
888
- const index = state.cloudflareAccounts.findIndex((account) => account.id === id);
889
- if (index >= 0) state.cloudflareAccounts[index].lastUsedAt = new Date().toISOString();
890
- return state;
891
- });
892
- }
893
-
894
- /** Current settings (a copy — callers may not mutate the cache). */
895
- async settings() {
896
- const state = await this.read();
897
- return { ...state.settings };
898
- }
899
-
900
- /**
901
- * Merge a validated settings patch and persist it.
902
- * @param {Partial<{oauthClientId: string, defaultRemote: string, showPrivate: boolean, gitPath: string}>} patch
903
- * @returns {Promise<object>} the full settings object.
904
- */
905
- async updateSettings(patch) {
906
- return this.mutate((state) => {
907
- state.settings = normalizeSettings({ ...state.settings, ...patch });
908
- return { ...state.settings };
909
- });
910
- }
911
-
912
- /* ---------------- CONTRACT §3b: push target memory ---------------- */
913
-
914
- /**
915
- * The remembered push target for ONE (repository, branch).
916
- *
917
- * A read, so it must never go through `mutate` (which would rewrite the
918
- * document — and take the write queue — for a pure lookup on every panel
919
- * render).
920
- *
921
- * @param {string} root repository root, in any spelling.
922
- * @param {string} branch branch name.
923
- * @returns {Promise<{remote: string, owner: string, repo: string, ref: string, at: string}|null>}
924
- */
925
- async pushMemoryFor(root, branch) {
926
- const normalizedBranch = String(branch ?? '').trim();
927
- if (normalizedBranch === '') return null;
928
- const state = await this.read();
929
- const entry = state.pushMemory?.[pushMemoryKey(root, normalizedBranch)];
930
- return entry ? { ...entry } : null;
931
- }
932
-
933
- /**
934
- * Every remembered target for one repository (all branches).
935
- *
936
- * @param {string} root repository root, in any spelling.
937
- * @returns {Promise<{branch: string, remote: string, owner: string, repo: string, ref: string, at: string}[]>}
938
- * sorted by branch name, so the debug view is stable between calls.
939
- */
940
- async pushMemoryEntries(root) {
941
- const prefix = `${normalizeRepoRoot(root)}|`;
942
- if (prefix === '|') return [];
943
- const state = await this.read();
944
- const out = [];
945
- for (const [key, entry] of Object.entries(state.pushMemory ?? {})) {
946
- if (!key.startsWith(prefix)) continue;
947
- out.push({ branch: key.slice(prefix.length), ...entry });
948
- }
949
- out.sort((left, right) => (left.branch < right.branch ? -1 : left.branch > right.branch ? 1 : 0));
950
- return out;
951
- }
952
-
953
- /**
954
- * Record the target of one SUCCESSFUL push.
955
- *
956
- * Goes through {@link mutate} so it serializes against every other write and
957
- * lands atomically.
958
- *
959
- * @param {string} root repository root, in any spelling.
960
- * @param {string} branch branch name.
961
- * @param {{remote: string, owner: string, repo: string, ref: string, at: string}} entry
962
- * @returns {Promise<object|null>} the stored entry, or null for a key that
963
- * cannot be formed (no root / no branch).
964
- */
965
- async rememberPushTarget(root, branch, entry) {
966
- const normalizedBranch = String(branch ?? '').trim();
967
- if (normalizeRepoRoot(root) === '' || normalizedBranch === '') return null;
968
- const key = pushMemoryKey(root, normalizedBranch);
969
- const record = normalizePushMemoryEntry(entry);
970
- if (!record) return null;
971
- return this.mutate((state) => {
972
- if (!state.pushMemory || typeof state.pushMemory !== 'object' || Array.isArray(state.pushMemory)) {
973
- state.pushMemory = {};
974
- }
975
- state.pushMemory[key] = record;
976
- return { ...record };
977
- });
978
- }
979
-
980
- /**
981
- * Forget one branch's remembered target.
982
- * @param {string} root
983
- * @param {string} branch
984
- * @returns {Promise<boolean>} whether an entry existed.
985
- */
986
- async forgetPushTarget(root, branch) {
987
- const normalizedBranch = String(branch ?? '').trim();
988
- if (normalizeRepoRoot(root) === '' || normalizedBranch === '') return false;
989
- const key = pushMemoryKey(root, normalizedBranch);
990
- return this.mutate((state) => {
991
- if (!state.pushMemory || typeof state.pushMemory !== 'object') return false;
992
- if (!(key in state.pushMemory)) return false;
993
- delete state.pushMemory[key];
994
- return true;
995
- });
996
- }
997
-
998
- /* ---------------- CONTRACT §3d: saved review prompts ---------------- */
999
-
1000
- /**
1001
- * Every preset the user saved.
1002
- * @returns {Promise<object[]>} a detached copy.
1003
- */
1004
- async reviewPresets() {
1005
- const state = await this.read();
1006
- return state.reviewPresets.map((preset) => ({ ...preset }));
1007
- }
1008
-
1009
- /**
1010
- * Save one preset, replacing any preset with the same id.
1011
- *
1012
- * Replacing rather than appending is what makes "edit a saved prompt" a
1013
- * single verb; the panel never has to distinguish create from update.
1014
- *
1015
- * @param {{id?: string, title: string, prompt: string, description?: string, category?: string}} input
1016
- * @returns {Promise<object>} the stored preset.
1017
- */
1018
- async saveReviewPreset(input) {
1019
- const now = new Date().toISOString();
1020
- return this.mutate((state) => {
1021
- const list = Array.isArray(state.reviewPresets) ? state.reviewPresets : [];
1022
- const id = typeof input.id === 'string' && input.id.trim() !== ''
1023
- ? input.id.trim()
1024
- : `custom_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1025
- const preset = {
1026
- id,
1027
- title: String(input.title ?? '').trim(),
1028
- prompt: String(input.prompt ?? ''),
1029
- description: String(input.description ?? ''),
1030
- category: String(input.category ?? 'custom') || 'custom',
1031
- builtin: false,
1032
- createdAt: now,
1033
- updatedAt: now,
1034
- };
1035
- const index = list.findIndex((row) => row.id === id);
1036
- if (index >= 0) {
1037
- // Preserve the original creation time across an update.
1038
- preset.createdAt = list[index].createdAt ?? now;
1039
- state.reviewPresets = list.map((row, i) => (i === index ? preset : row));
1040
- } else {
1041
- state.reviewPresets = [...list, preset];
1042
- }
1043
- return { ...preset };
1044
- });
1045
- }
1046
-
1047
- /**
1048
- * Remove one saved preset.
1049
- * @param {string} id
1050
- * @returns {Promise<boolean>} whether a preset was removed.
1051
- */
1052
- async deleteReviewPreset(id) {
1053
- const wanted = String(id ?? '').trim();
1054
- if (wanted === '') return false;
1055
- return this.mutate((state) => {
1056
- const list = Array.isArray(state.reviewPresets) ? state.reviewPresets : [];
1057
- const next = list.filter((row) => row.id !== wanted);
1058
- if (next.length === list.length) return false;
1059
- state.reviewPresets = next;
1060
- return true;
1061
- });
1062
- }
1063
- }