dsh-multi-device-config-sync 0.0.0-stage → 1.6.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/lib/routes.js ADDED
@@ -0,0 +1,507 @@
1
+ /**
2
+ * The Host half's HTTP surface.
3
+ *
4
+ * Every route lives under one `prefix` registration on the bare web server,
5
+ * so admission and disposal happen in one place.
6
+ *
7
+ * Admission: the request must pass the host's own gate when the host publishes
8
+ * one (`connection.requestRejection` covers its Host/Origin fence and its
9
+ * browser login), and its Host — when the transport preserves one — must be
10
+ * loopback or an authority the deployment declared. That is the same rule the
11
+ * shipped API fence applies; these routes are exact matches on the bare web
12
+ * server, so they never pass through that fence themselves.
13
+ */
14
+ import {
15
+ BACKUP_FILENAME, GIST_MAX_BYTES, MAX_BACKUP_BYTES, WORK_DIR,
16
+ applyRestore, backupBytes, collectProfileFiles, exportBackupWithReport, planRestore,
17
+ profileName, profileRoot, profileSource, readBackupFile, undoLastRestore, undoStatus, validateBackup,
18
+ } from './backup.js'
19
+ import { createGist, parseGistId, readGist, resolveTokenSource, tokenSourceNames, updateGist, verifyToken } from './gist.js'
20
+ import { ConfigSyncError, describeError, statusOf } from './errors.js'
21
+ import { installMissingPlugins, pluginInventory, validPackageName } from './plugins.js'
22
+ import { readSettings, settingsPath, writeSettings } from './store.js'
23
+ import { createRestoreSession, restoreGistConfiguration } from './sync-install.js'
24
+ import { readFileSync } from 'node:fs'
25
+ import { join } from 'node:path'
26
+
27
+ // Read the plugin's own shipped manifest, not the working directory or profile.
28
+ const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
29
+
30
+ /** The one route prefix this plugin owns. */
31
+ export const BASE_PATH = '/dsh-profile-gist-sync-plus'
32
+ /** Largest request body accepted for an import (a backup plus JSON framing). */
33
+ const MAX_BODY_BYTES = 4 * 1024 * 1024
34
+
35
+ /** Register this plugin's routes; the returned disposer removes them. */
36
+ export function registerRoutes(ctx) {
37
+ const webServer = ctx.get('webServer')
38
+ if (webServer === undefined || webServer === null) return () => {}
39
+ const session = createRestoreSession(ctx)
40
+ const unregister = webServer.register({
41
+ kind: 'prefix',
42
+ path: BASE_PATH,
43
+ handler: (request, response) => { void handleRequest(ctx, session, request, response) },
44
+ })
45
+ return () => { session.dispose(); return unregister() }
46
+ }
47
+
48
+ /** Write a JSON payload with no-store caching. */
49
+ function sendJson(response, status, payload) {
50
+ const body = JSON.stringify(payload)
51
+ response.writeHead(status, {
52
+ 'cache-control': 'no-store',
53
+ 'content-type': 'application/json; charset=utf-8',
54
+ 'content-length': Buffer.byteLength(body),
55
+ })
56
+ response.end(body)
57
+ }
58
+
59
+ const NDJSON = 'application/x-ndjson'
60
+ const count = n => Number.isSafeInteger(n) && n >= 0
61
+
62
+ // An ordinary browser/old Client asking for */* still receives its original JSON.
63
+ function acceptsProgress(accept) {
64
+ return typeof accept === 'string' && accept.split(',').some(range => {
65
+ const [media, ...params] = range.toLowerCase().split(';').map(s => s.trim())
66
+ const q = params.find(p => /^q\s*=/.test(p))
67
+ return media === NDJSON && (q === undefined || Number(q.slice(q.indexOf('=') + 1)) > 0)
68
+ })
69
+ }
70
+
71
+ // Do not serialize arbitrary internal objects onto the progress channel. In
72
+ // particular a source URL, path, plan ID or installation log is not a progress field.
73
+ function progressFrame(p) {
74
+ if (p?.stage === 'check' || p?.stage === 'write') return { type: 'progress', stage: p.stage }
75
+ if (!count(p?.files)) return null
76
+ if (p.stage === 'verify') {
77
+ const meter = count(p.processed) && count(p.total) && p.total > 0 && p.processed <= p.total
78
+ ? { processed: p.processed, total: p.total } : {}
79
+ return { type: 'progress', stage: 'verify', files: p.files, ...meter }
80
+ }
81
+ if (p.stage !== 'install' || !count(p.processed) || !count(p.total) || p.total === 0 || p.processed > p.total
82
+ || !(p.current === null || validPackageName(p.current))) return null
83
+ return { type: 'progress', stage: 'install', files: p.files, processed: p.processed, total: p.total, current: p.current }
84
+ }
85
+
86
+ /** Same one-use operation for both protocols. Never start a second write to obtain progress or to recover a receipt. */
87
+ async function confirmReviewed(request, response, body, apply) {
88
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(k => k !== 'planId' && k !== 'confirm')) {
89
+ throw new ConfigSyncError('A reviewed restore accepts only the plan ID and confirmation.', 'invalid')
90
+ }
91
+ if (!acceptsProgress(request.headers.accept)) {
92
+ sendJson(response, 200, await apply(body.planId, body.confirm))
93
+ return
94
+ }
95
+ // The route's independent writer lock belongs to the operation, not the
96
+ // socket. A closed tab discards feedback; it does not cancel or repeat work.
97
+ let disconnected = false
98
+ const detach = () => { disconnected = true }
99
+ response.once('error', detach)
100
+ response.once('close', detach)
101
+ const send = (frame, final = false) => {
102
+ if (disconnected || response.destroyed || response.writableEnded || (!final && response.writableNeedDrain)) return
103
+ if (!response.headersSent) response.writeHead(200, {
104
+ 'content-type': `${NDJSON}; charset=utf-8`, 'cache-control': 'no-store, no-transform',
105
+ 'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff', vary: 'Accept',
106
+ })
107
+ const line = `${JSON.stringify(frame)}\n`
108
+ if (final) response.end(line)
109
+ else {
110
+ // Flush each small stage as one HTTP chunk now, rather than leaving the
111
+ // default next-tick cork closed during a synchronous configuration write.
112
+ response.cork()
113
+ try { response.write(line) } finally { response.uncork() }
114
+ }
115
+ }
116
+ try {
117
+ const result = await apply(body.planId, body.confirm, event => {
118
+ const frame = progressFrame(event)
119
+ if (frame) send(frame)
120
+ })
121
+ send({ type: 'result', result }, true)
122
+ } catch (error) {
123
+ // Preserve HTTP errors before the stream starts; after that the final
124
+ // error record, not the 200 handshake, carries the terminal outcome.
125
+ if (disconnected || response.destroyed || response.writableEnded) return
126
+ if (!response.headersSent) throw error
127
+ send({ type: 'error', ...describeError(error) }, true)
128
+ }
129
+ }
130
+
131
+ /** Read and parse a JSON request body. */
132
+ async function readJsonBody(request) {
133
+ const chunks = []
134
+ let size = 0
135
+ for await (const chunk of request) {
136
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
137
+ size += buffer.length
138
+ if (size > MAX_BODY_BYTES) throw new ConfigSyncError('the request body is too large', 'too-large')
139
+ chunks.push(buffer)
140
+ }
141
+ if (size === 0) return {}
142
+ try {
143
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
144
+ } catch {
145
+ throw new ConfigSyncError('the request body is not valid JSON', 'invalid')
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Authorities this deployment serves besides loopback, as the host declared
151
+ * them (`dsh web --trusted-host <name>`, plus the LAN literals it derives).
152
+ */
153
+ function trustedHosts(ctx) {
154
+ const connection = ctx.get('connection')
155
+ const hosts = connection?.trustedHosts
156
+ return Array.isArray(hosts) ? hosts.filter(host => typeof host === 'string') : []
157
+ }
158
+
159
+ /**
160
+ * The Host/Origin rule for these routes: the request's Host must be loopback or
161
+ * a declared authority, the fetch metadata must not say `cross-site`, and an
162
+ * Origin, when present, must match that Host.
163
+ */
164
+ function sameOrigin(ctx, request) {
165
+ const host = typeof request.headers.host === 'string' ? request.headers.host : undefined
166
+ const origin = typeof request.headers.origin === 'string' ? request.headers.origin : undefined
167
+ const site = typeof request.headers['sec-fetch-site'] === 'string' ? request.headers['sec-fetch-site'] : undefined
168
+ if (site === 'cross-site') return false
169
+ // A non-browser client can set any Origin it likes, so an absent Origin is not
170
+ // itself a refusal; the Host check is what a rebinding attacker cannot forge.
171
+ if (origin !== undefined) {
172
+ try {
173
+ if (new URL(origin).host !== host) return false
174
+ } catch {
175
+ return false
176
+ }
177
+ }
178
+ if (host === undefined) return true
179
+ let hostname
180
+ try {
181
+ hostname = new URL(`http://${host}`).hostname
182
+ } catch {
183
+ return false
184
+ }
185
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
186
+ if (bare === 'localhost' || bare === '127.0.0.1' || bare === '::1' || bare.endsWith('.localhost')) return true
187
+ return trustedHosts(ctx).includes(hostname) || trustedHosts(ctx).includes(bare)
188
+ }
189
+
190
+ /**
191
+ * Answer the request with the host's rejection if it has one.
192
+ * @returns true when the request was refused and answered here.
193
+ */
194
+ function refuseUnadmitted(ctx, request, response) {
195
+ const connection = ctx.get('connection')
196
+ const gate = connection?.requestRejection
197
+ if (typeof gate === 'function') {
198
+ let status
199
+ try {
200
+ status = gate.call(connection, request)
201
+ } catch {
202
+ // A gate that throws has not admitted anything.
203
+ status = 403
204
+ }
205
+ if (typeof status === 'number') {
206
+ sendJson(response, status, {
207
+ error: 'DSH refused this request: not signed in, or an untrusted origin',
208
+ code: 'auth',
209
+ })
210
+ return true
211
+ }
212
+ }
213
+ if (!sameOrigin(ctx, request)) {
214
+ sendJson(response, 403, {
215
+ error: 'refused: the Host or Origin of this request is not one this deployment serves',
216
+ code: 'auth',
217
+ })
218
+ return true
219
+ }
220
+ return false
221
+ }
222
+
223
+ /** Profile summary for the settings page. */
224
+ function statusPayload() {
225
+ const root = profileRoot()
226
+ const { included, excluded } = collectProfileFiles(root)
227
+ let bytes = 0
228
+ for (const file of included) bytes += file.bytes
229
+ const settings = readSettings()
230
+ return {
231
+ profile: profileName(),
232
+ root,
233
+ profileSource: profileSource(),
234
+ workDir: join(root, WORK_DIR),
235
+ version: PACKAGE_VERSION,
236
+ files: included,
237
+ excluded,
238
+ counts: {
239
+ files: included.length,
240
+ bytes,
241
+ excluded: excluded.length,
242
+ machineFiles: excluded.filter(entry => entry.code === 'machine-state').length,
243
+ },
244
+ limits: { maxBackupBytes: MAX_BACKUP_BYTES, gistMaxBytes: GIST_MAX_BYTES },
245
+ gistFile: BACKUP_FILENAME,
246
+ envTokens: tokenSourceNames(),
247
+ undo: undoStatus(),
248
+ // What this plugin remembers, so the page can show one plain sentence about
249
+ // the cloud copy without asking the reader for anything.
250
+ cloud: {
251
+ gistId: settings.gistId,
252
+ includeMachine: settings.includeMachine,
253
+ lastUpload: settings.lastUpload,
254
+ lastSync: settings.lastSync,
255
+ settingsFile: settingsPath(),
256
+ },
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Which Gist this request is about: the one it names, else the remembered one,
262
+ * else nothing (which means "create a new one" on upload and is a refusal on
263
+ * read).
264
+ * @param {unknown} named - the value from the request body.
265
+ */
266
+ function targetId(named) {
267
+ const raw = typeof named === 'string' ? named.trim() : ''
268
+ if (raw !== '') return parseGistId(raw)
269
+ return readSettings().gistId
270
+ }
271
+
272
+ /** Now, in the timestamp shape every record here uses. */
273
+ function now() {
274
+ return new Date().toISOString()
275
+ }
276
+
277
+ /**
278
+ * Serve a fresh backup as a download.
279
+ *
280
+ * A file download has nowhere to put the export report, so it is discarded here.
281
+ * The export itself still drops machine-local dependency specs — the alternative
282
+ * would be a file that breaks `pnpm install` wherever it is restored — and the
283
+ * same report is surfaced by the upload response and by the page.
284
+ */
285
+ function exportDownload(response, url) {
286
+ const { backup } = exportBackupWithReport({ includeMachine: url.searchParams.get('include') === 'machine' })
287
+ const body = `${JSON.stringify(backup, null, 2)}\n`
288
+ const stamp = new Date().toISOString().replaceAll(':', '-').replace(/\.\d+Z$/, 'Z')
289
+ response.writeHead(200, {
290
+ 'cache-control': 'no-store',
291
+ 'content-type': 'application/json; charset=utf-8',
292
+ 'content-disposition': `attachment; filename="dsh-profile-backup-${stamp}.json"`,
293
+ 'content-length': Buffer.byteLength(body),
294
+ })
295
+ response.end(body)
296
+ }
297
+
298
+ /** Client pairs are a constraint on the live inventory, never a list of install targets. */
299
+ async function installLocalGaps(ctx, expected) {
300
+ if (expected === undefined) return installMissingPlugins(ctx) // legacy caller
301
+ const invalid = () => new ConfigSyncError('expectedPackages must list unique package names with exact install specs.', 'invalid')
302
+ if (!Array.isArray(expected)) throw invalid()
303
+ const names = new Set()
304
+ for (const row of expected) {
305
+ if (!validPackageName(row?.name) || typeof row.installSpec !== 'string' || !row.installSpec.trim() || names.has(row.name)) throw invalid()
306
+ names.add(row.name)
307
+ }
308
+ const inventory = await pluginInventory(ctx)
309
+ const installable = inventory.available ? inventory.missing.filter(row => row.resolvable) : null
310
+ if (!installable || installable.length !== expected.length || installable.some((row, i) =>
311
+ row.name !== expected[i].name || row.installSpec !== expected[i].installSpec)) {
312
+ throw new ConfigSyncError('The local plugin list changed or is unavailable. Check the missing packages again.', 'stale-plan')
313
+ }
314
+ // The installer reads local state again. Even a change after the comparison
315
+ // cannot expand this allowlist or substitute another spec for a reviewed one.
316
+ const approved = new Map(installable.map(row => [row.name, row.installSpec]))
317
+ return installMissingPlugins(ctx, { approved })
318
+ }
319
+
320
+ /** Route one request. Unknown subpaths answer 404 with the same JSON shape. */
321
+ const PROFILE_WRITES = new Set(['/api/sync/install', '/api/config/restore', '/api/sync', '/api/restore', '/api/undo', '/api/plugins/install'])
322
+
323
+ async function handleRequest(ctx, session, request, response) {
324
+ let release
325
+ try {
326
+ const url = new URL(request.url ?? '/', 'http://localhost')
327
+ if (!url.pathname.startsWith(`${BASE_PATH}/`)) {
328
+ sendJson(response, 404, { error: 'not found', code: 'notfound' })
329
+ return
330
+ }
331
+ if (refuseUnadmitted(ctx, request, response)) return
332
+ const route = url.pathname.slice(BASE_PATH.length)
333
+ const method = request.method ?? 'GET'
334
+ if (method === 'POST' && PROFILE_WRITES.has(route)) release = session.lock()
335
+
336
+ if (method === 'POST' && (route === '/api/sync/preview' || route === '/api/config/preview')) {
337
+ const body = await readJsonBody(request)
338
+ const id = targetId(body?.id)
339
+ if (!id) throw new ConfigSyncError('Set the Gist ID or link on this machine first.', 'no-cloud')
340
+ const { token } = await resolveTokenSource(body?.token)
341
+ const { ref, backup } = await readGist(token, id)
342
+ const plan = route === '/api/config/preview' ? session.previewConfig(ref, backup) : await session.preview(ref, backup)
343
+ sendJson(response, 200, plan)
344
+ return
345
+ }
346
+ if (method === 'POST' && (route === '/api/sync/install' || route === '/api/config/restore')) {
347
+ const body = await readJsonBody(request)
348
+ await confirmReviewed(request, response, body, route === '/api/config/restore' ? session.confirmConfig : session.confirm)
349
+ return
350
+ }
351
+
352
+ if (route === '/api/status' && method === 'GET') {
353
+ sendJson(response, 200, statusPayload())
354
+ return
355
+ }
356
+ if (route === '/api/export' && method === 'GET') {
357
+ exportDownload(response, url)
358
+ return
359
+ }
360
+ if (route === '/api/plugins' && method === 'GET') {
361
+ // Read-only, and deliberately a route of its own: it consults the host's
362
+ // plugin manager, which a status refresh has no business doing.
363
+ sendJson(response, 200, await pluginInventory(ctx))
364
+ return
365
+ }
366
+ if (route === '/api/plugins/install' && method === 'POST') {
367
+ const body = await readJsonBody(request)
368
+ sendJson(response, 200, await installLocalGaps(ctx, body?.expectedPackages))
369
+ return
370
+ }
371
+ if (route === '/api/preview' && method === 'POST') {
372
+ const body = await readJsonBody(request)
373
+ const backup = validateBackup(body?.backup)
374
+ sendJson(response, 200, body?.reviewed === true ? session.previewLocal(backup) : { preview: planRestore(backup) })
375
+ return
376
+ }
377
+ if (route === '/api/restore' && method === 'POST') {
378
+ const body = await readJsonBody(request)
379
+ if (body?.planId !== undefined) {
380
+ if (body.backup !== undefined) throw new ConfigSyncError('A reviewed import accepts a plan ID, not a replacement backup.', 'invalid')
381
+ await confirmReviewed(request, response, body, session.confirmLocal)
382
+ return
383
+ }
384
+ if (body?.confirm !== true) {
385
+ throw new ConfigSyncError('restoring requires an explicit confirmation', 'invalid')
386
+ }
387
+ const { report } = applyRestore(body?.backup)
388
+ sendJson(response, 200, { report })
389
+ return
390
+ }
391
+ if (route === '/api/undo' && method === 'POST') {
392
+ const body = await readJsonBody(request)
393
+ if (body?.expectedStamp !== undefined) {
394
+ if (typeof body.expectedStamp !== 'string' || !body.expectedStamp.trim()) throw new ConfigSyncError('expectedStamp must name the reviewed undo snapshot.', 'invalid')
395
+ if (undoStatus()?.stamp !== body.expectedStamp) throw new ConfigSyncError('The undo snapshot changed. Review the latest restore before undoing it.', 'stale-plan')
396
+ }
397
+ sendJson(response, 200, { report: undoLastRestore() })
398
+ return
399
+ }
400
+ if (route === '/api/file/read' && method === 'POST') {
401
+ const body = await readJsonBody(request)
402
+ const backup = readBackupFile(String(body?.path ?? ''))
403
+ sendJson(response, 200, { backup, preview: planRestore(backup) })
404
+ return
405
+ }
406
+ if (route === '/api/settings' && method === 'POST') {
407
+ const body = await readJsonBody(request)
408
+ const patch = {}
409
+ if (body?.gistId !== undefined) {
410
+ // An empty value clears the remembered cloud copy, which is how the page
411
+ // starts over with a different Gist.
412
+ const raw = typeof body.gistId === 'string' ? body.gistId.trim() : ''
413
+ patch.gistId = raw === '' ? null : parseGistId(raw)
414
+ }
415
+ if (body?.includeMachine !== undefined) patch.includeMachine = body.includeMachine === true
416
+ const stored = writeSettings(patch)
417
+ sendJson(response, 200, {
418
+ cloud: {
419
+ gistId: stored.gistId,
420
+ includeMachine: stored.includeMachine,
421
+ lastUpload: stored.lastUpload,
422
+ lastSync: stored.lastSync,
423
+ settingsFile: settingsPath(),
424
+ },
425
+ })
426
+ return
427
+ }
428
+ if (route === '/api/gist/token' && method === 'POST') {
429
+ const body = await readJsonBody(request)
430
+ const resolved = await resolveTokenSource(body?.token)
431
+ const login = await verifyToken(resolved.token)
432
+ if (!login) throw new ConfigSyncError('GitHub did not identify an account for this token.', 'auth')
433
+ sendJson(response, 200, { source: resolved.source, login })
434
+ return
435
+ }
436
+ if (route === '/api/gist/upload' && method === 'POST') {
437
+ const body = await readJsonBody(request)
438
+ const resolved = await resolveTokenSource(body?.token)
439
+ const { backup, dropped, droppedEntries } = exportBackupWithReport({ includeMachine: body?.includeMachine === true })
440
+ const content = `${JSON.stringify(backup, null, 2)}\n`
441
+ const id = targetId(body?.id)
442
+ // The upload preview names either a particular Gist or a new one (null).
443
+ // Compare at the point of selecting the destination, before either write.
444
+ if (body?.expectedTarget !== undefined && body.expectedTarget !== id) {
445
+ throw new ConfigSyncError('The upload target changed. Review the destination before uploading again.', 'stale-plan')
446
+ }
447
+ const ref = id === null
448
+ ? await createGist(resolved.token, content)
449
+ : await updateGist(resolved.token, id, content)
450
+ // Remember where the cloud copy lives and when it was written, so the next
451
+ // upload, the sync button, and the status line need no typing.
452
+ writeSettings({
453
+ gistId: ref.id,
454
+ lastUpload: {
455
+ gistId: ref.id,
456
+ at: now(),
457
+ files: backup.files.length,
458
+ bytes: Buffer.byteLength(content),
459
+ created: id === null,
460
+ tokenSource: resolved.source,
461
+ },
462
+ })
463
+ sendJson(response, 200, {
464
+ ref,
465
+ created: id === null,
466
+ tokenSource: resolved.source,
467
+ bytes: Buffer.byteLength(content),
468
+ files: backup.files.length,
469
+ createdAt: backup.createdAt,
470
+ backupBytes: backupBytes(backup),
471
+ // Machine-local dependency specs left out of what was uploaded, so the
472
+ // page can say so instead of the user finding out on the other machine.
473
+ dropped,
474
+ droppedEntries,
475
+ })
476
+ return
477
+ }
478
+ if (route === '/api/gist/read' && method === 'POST') {
479
+ const body = await readJsonBody(request)
480
+ const resolved = await resolveTokenSource(body?.token)
481
+ const id = targetId(body?.id)
482
+ if (id === null) throw new ConfigSyncError('no cloud backup is set up yet', 'no-cloud')
483
+ const { ref, backup } = await readGist(resolved.token, id)
484
+ sendJson(response, 200, { ref, backup, preview: planRestore(backup), tokenSource: resolved.source })
485
+ return
486
+ }
487
+ if (route === '/api/sync' && method === 'POST') {
488
+ // One call for the whole job: read the cloud copy, then write it here with
489
+ // an undo snapshot taken first.
490
+ const body = await readJsonBody(request)
491
+ const resolved = await resolveTokenSource(body?.token)
492
+ const id = targetId(body?.id)
493
+ if (id === null) {
494
+ throw new ConfigSyncError('there is no cloud backup yet: upload this machine first', 'no-cloud')
495
+ }
496
+ const { ref, backup } = await readGist(resolved.token, id)
497
+ const { report, warnings } = restoreGistConfiguration(ref, backup, { bindUploadTarget: true })
498
+ sendJson(response, 200, { ref, report, tokenSource: resolved.source, undoDir: report.undoDir, ...(warnings.length ? { warnings } : {}) })
499
+ return
500
+ }
501
+ sendJson(response, 404, { error: `no such route: ${route}`, code: 'notfound' })
502
+ } catch (error) {
503
+ sendJson(response, statusOf(error), describeError(error))
504
+ } finally {
505
+ release?.()
506
+ }
507
+ }
package/lib/store.js ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * What this plugin remembers between visits: which Gist holds the cloud copy,
3
+ * which options were last used, and when the last upload or sync happened.
4
+ *
5
+ * One small file inside the profile's work directory — a hidden directory the
6
+ * exporter never carries, so remembering never feeds back into a backup. Reads
7
+ * are tolerant (a missing or damaged file is simply "nothing remembered yet")
8
+ * and writes are atomic, so a crash mid-write cannot leave a half document that
9
+ * would later be read as settings.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
12
+ import { dirname, join } from 'node:path'
13
+ import { WORK_DIR, profileRoot } from './backup.js'
14
+
15
+ const FILE = 'settings.json'
16
+
17
+ /** The shape a reader can rely on, whatever the file happens to hold. */
18
+ function normalize(value) {
19
+ const source = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
20
+ const gistId = typeof source.gistId === 'string' && source.gistId.trim() !== '' ? source.gistId.trim() : null
21
+ return {
22
+ gistId,
23
+ includeMachine: source.includeMachine === true,
24
+ lastUpload: objectOrNull(source.lastUpload),
25
+ lastSync: objectOrNull(source.lastSync),
26
+ }
27
+ }
28
+
29
+ /** A record this plugin wrote, or null. */
30
+ function objectOrNull(value) {
31
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null
32
+ }
33
+
34
+ /** Path of the settings file inside this profile. */
35
+ export function settingsPath() {
36
+ return join(profileRoot(), WORK_DIR, FILE)
37
+ }
38
+
39
+ /** Everything remembered here, defaulted. */
40
+ export function readSettings() {
41
+ const path = settingsPath()
42
+ if (!existsSync(path)) return normalize(null)
43
+ try {
44
+ return normalize(JSON.parse(readFileSync(path, 'utf8')))
45
+ } catch {
46
+ // A damaged file must not take the page down; it just means nothing is known.
47
+ return normalize(null)
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Merge a patch into the remembered settings and write them.
53
+ * @param {object} patch - any of `gistId`, `includeMachine`, `lastUpload`, `lastSync`.
54
+ * @returns {object} the settings as stored.
55
+ */
56
+ export function writeSettings(patch) {
57
+ const next = normalize({ ...readSettings(), ...patch })
58
+ const path = settingsPath()
59
+ mkdirSync(dirname(path), { recursive: true })
60
+ const temporary = `${path}.tmp-${String(process.pid)}`
61
+ try {
62
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
63
+ renameSync(temporary, path)
64
+ } catch (error) {
65
+ try {
66
+ unlinkSync(temporary)
67
+ } catch {
68
+ // The temporary file is best-effort cleanup around the real failure.
69
+ }
70
+ throw error
71
+ }
72
+ return next
73
+ }