dsh-multi-device-config-sync 0.0.0-stage → 1.5.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,438 @@
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
+ /** Read and parse a JSON request body. */
60
+ async function readJsonBody(request) {
61
+ const chunks = []
62
+ let size = 0
63
+ for await (const chunk of request) {
64
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
65
+ size += buffer.length
66
+ if (size > MAX_BODY_BYTES) throw new ConfigSyncError('the request body is too large', 'too-large')
67
+ chunks.push(buffer)
68
+ }
69
+ if (size === 0) return {}
70
+ try {
71
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
72
+ } catch {
73
+ throw new ConfigSyncError('the request body is not valid JSON', 'invalid')
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Authorities this deployment serves besides loopback, as the host declared
79
+ * them (`dsh web --trusted-host <name>`, plus the LAN literals it derives).
80
+ */
81
+ function trustedHosts(ctx) {
82
+ const connection = ctx.get('connection')
83
+ const hosts = connection?.trustedHosts
84
+ return Array.isArray(hosts) ? hosts.filter(host => typeof host === 'string') : []
85
+ }
86
+
87
+ /**
88
+ * The Host/Origin rule for these routes: the request's Host must be loopback or
89
+ * a declared authority, the fetch metadata must not say `cross-site`, and an
90
+ * Origin, when present, must match that Host.
91
+ */
92
+ function sameOrigin(ctx, request) {
93
+ const host = typeof request.headers.host === 'string' ? request.headers.host : undefined
94
+ const origin = typeof request.headers.origin === 'string' ? request.headers.origin : undefined
95
+ const site = typeof request.headers['sec-fetch-site'] === 'string' ? request.headers['sec-fetch-site'] : undefined
96
+ if (site === 'cross-site') return false
97
+ // A non-browser client can set any Origin it likes, so an absent Origin is not
98
+ // itself a refusal; the Host check is what a rebinding attacker cannot forge.
99
+ if (origin !== undefined) {
100
+ try {
101
+ if (new URL(origin).host !== host) return false
102
+ } catch {
103
+ return false
104
+ }
105
+ }
106
+ if (host === undefined) return true
107
+ let hostname
108
+ try {
109
+ hostname = new URL(`http://${host}`).hostname
110
+ } catch {
111
+ return false
112
+ }
113
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
114
+ if (bare === 'localhost' || bare === '127.0.0.1' || bare === '::1' || bare.endsWith('.localhost')) return true
115
+ return trustedHosts(ctx).includes(hostname) || trustedHosts(ctx).includes(bare)
116
+ }
117
+
118
+ /**
119
+ * Answer the request with the host's rejection if it has one.
120
+ * @returns true when the request was refused and answered here.
121
+ */
122
+ function refuseUnadmitted(ctx, request, response) {
123
+ const connection = ctx.get('connection')
124
+ const gate = connection?.requestRejection
125
+ if (typeof gate === 'function') {
126
+ let status
127
+ try {
128
+ status = gate.call(connection, request)
129
+ } catch {
130
+ // A gate that throws has not admitted anything.
131
+ status = 403
132
+ }
133
+ if (typeof status === 'number') {
134
+ sendJson(response, status, {
135
+ error: 'DSH refused this request: not signed in, or an untrusted origin',
136
+ code: 'auth',
137
+ })
138
+ return true
139
+ }
140
+ }
141
+ if (!sameOrigin(ctx, request)) {
142
+ sendJson(response, 403, {
143
+ error: 'refused: the Host or Origin of this request is not one this deployment serves',
144
+ code: 'auth',
145
+ })
146
+ return true
147
+ }
148
+ return false
149
+ }
150
+
151
+ /** Profile summary for the settings page. */
152
+ function statusPayload() {
153
+ const root = profileRoot()
154
+ const { included, excluded } = collectProfileFiles(root)
155
+ let bytes = 0
156
+ for (const file of included) bytes += file.bytes
157
+ const settings = readSettings()
158
+ return {
159
+ profile: profileName(),
160
+ root,
161
+ profileSource: profileSource(),
162
+ workDir: join(root, WORK_DIR),
163
+ version: PACKAGE_VERSION,
164
+ files: included,
165
+ excluded,
166
+ counts: {
167
+ files: included.length,
168
+ bytes,
169
+ excluded: excluded.length,
170
+ machineFiles: excluded.filter(entry => entry.code === 'machine-state').length,
171
+ },
172
+ limits: { maxBackupBytes: MAX_BACKUP_BYTES, gistMaxBytes: GIST_MAX_BYTES },
173
+ gistFile: BACKUP_FILENAME,
174
+ envTokens: tokenSourceNames(),
175
+ undo: undoStatus(),
176
+ // What this plugin remembers, so the page can show one plain sentence about
177
+ // the cloud copy without asking the reader for anything.
178
+ cloud: {
179
+ gistId: settings.gistId,
180
+ includeMachine: settings.includeMachine,
181
+ lastUpload: settings.lastUpload,
182
+ lastSync: settings.lastSync,
183
+ settingsFile: settingsPath(),
184
+ },
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Which Gist this request is about: the one it names, else the remembered one,
190
+ * else nothing (which means "create a new one" on upload and is a refusal on
191
+ * read).
192
+ * @param {unknown} named - the value from the request body.
193
+ */
194
+ function targetId(named) {
195
+ const raw = typeof named === 'string' ? named.trim() : ''
196
+ if (raw !== '') return parseGistId(raw)
197
+ return readSettings().gistId
198
+ }
199
+
200
+ /** Now, in the timestamp shape every record here uses. */
201
+ function now() {
202
+ return new Date().toISOString()
203
+ }
204
+
205
+ /**
206
+ * Serve a fresh backup as a download.
207
+ *
208
+ * A file download has nowhere to put the export report, so it is discarded here.
209
+ * The export itself still drops machine-local dependency specs — the alternative
210
+ * would be a file that breaks `pnpm install` wherever it is restored — and the
211
+ * same report is surfaced by the upload response and by the page.
212
+ */
213
+ function exportDownload(response, url) {
214
+ const { backup } = exportBackupWithReport({ includeMachine: url.searchParams.get('include') === 'machine' })
215
+ const body = `${JSON.stringify(backup, null, 2)}\n`
216
+ const stamp = new Date().toISOString().replaceAll(':', '-').replace(/\.\d+Z$/, 'Z')
217
+ response.writeHead(200, {
218
+ 'cache-control': 'no-store',
219
+ 'content-type': 'application/json; charset=utf-8',
220
+ 'content-disposition': `attachment; filename="dsh-profile-backup-${stamp}.json"`,
221
+ 'content-length': Buffer.byteLength(body),
222
+ })
223
+ response.end(body)
224
+ }
225
+
226
+ /** Client pairs are a constraint on the live inventory, never a list of install targets. */
227
+ async function installLocalGaps(ctx, expected) {
228
+ if (expected === undefined) return installMissingPlugins(ctx) // legacy caller
229
+ const invalid = () => new ConfigSyncError('expectedPackages must list unique package names with exact install specs.', 'invalid')
230
+ if (!Array.isArray(expected)) throw invalid()
231
+ const names = new Set()
232
+ for (const row of expected) {
233
+ if (!validPackageName(row?.name) || typeof row.installSpec !== 'string' || !row.installSpec.trim() || names.has(row.name)) throw invalid()
234
+ names.add(row.name)
235
+ }
236
+ const inventory = await pluginInventory(ctx)
237
+ const installable = inventory.available ? inventory.missing.filter(row => row.resolvable) : null
238
+ if (!installable || installable.length !== expected.length || installable.some((row, i) =>
239
+ row.name !== expected[i].name || row.installSpec !== expected[i].installSpec)) {
240
+ throw new ConfigSyncError('The local plugin list changed or is unavailable. Check the missing packages again.', 'stale-plan')
241
+ }
242
+ // The installer reads local state again. Even a change after the comparison
243
+ // cannot expand this allowlist or substitute another spec for a reviewed one.
244
+ const approved = new Map(installable.map(row => [row.name, row.installSpec]))
245
+ return installMissingPlugins(ctx, { approved })
246
+ }
247
+
248
+ /** Route one request. Unknown subpaths answer 404 with the same JSON shape. */
249
+ const PROFILE_WRITES = new Set(['/api/sync/install', '/api/config/restore', '/api/sync', '/api/restore', '/api/undo', '/api/plugins/install'])
250
+
251
+ async function handleRequest(ctx, session, request, response) {
252
+ let release
253
+ try {
254
+ const url = new URL(request.url ?? '/', 'http://localhost')
255
+ if (!url.pathname.startsWith(`${BASE_PATH}/`)) {
256
+ sendJson(response, 404, { error: 'not found', code: 'notfound' })
257
+ return
258
+ }
259
+ if (refuseUnadmitted(ctx, request, response)) return
260
+ const route = url.pathname.slice(BASE_PATH.length)
261
+ const method = request.method ?? 'GET'
262
+ if (method === 'POST' && PROFILE_WRITES.has(route)) release = session.lock()
263
+
264
+ if (method === 'POST' && (route === '/api/sync/preview' || route === '/api/config/preview')) {
265
+ const body = await readJsonBody(request)
266
+ const id = targetId(body?.id)
267
+ if (!id) throw new ConfigSyncError('Set the Gist ID or link on this machine first.', 'no-cloud')
268
+ const { token } = await resolveTokenSource(body?.token)
269
+ const { ref, backup } = await readGist(token, id)
270
+ const plan = route === '/api/config/preview' ? session.previewConfig(ref, backup) : await session.preview(ref, backup)
271
+ sendJson(response, 200, plan)
272
+ return
273
+ }
274
+ if (method === 'POST' && (route === '/api/sync/install' || route === '/api/config/restore')) {
275
+ const body = await readJsonBody(request)
276
+ const result = route === '/api/config/restore'
277
+ ? session.confirmConfig(body?.planId, body?.confirm)
278
+ : await session.confirm(body?.planId, body?.confirm)
279
+ sendJson(response, 200, result)
280
+ return
281
+ }
282
+
283
+ if (route === '/api/status' && method === 'GET') {
284
+ sendJson(response, 200, statusPayload())
285
+ return
286
+ }
287
+ if (route === '/api/export' && method === 'GET') {
288
+ exportDownload(response, url)
289
+ return
290
+ }
291
+ if (route === '/api/plugins' && method === 'GET') {
292
+ // Read-only, and deliberately a route of its own: it consults the host's
293
+ // plugin manager, which a status refresh has no business doing.
294
+ sendJson(response, 200, await pluginInventory(ctx))
295
+ return
296
+ }
297
+ if (route === '/api/plugins/install' && method === 'POST') {
298
+ const body = await readJsonBody(request)
299
+ sendJson(response, 200, await installLocalGaps(ctx, body?.expectedPackages))
300
+ return
301
+ }
302
+ if (route === '/api/preview' && method === 'POST') {
303
+ const body = await readJsonBody(request)
304
+ const backup = validateBackup(body?.backup)
305
+ sendJson(response, 200, body?.reviewed === true ? session.previewLocal(backup) : { preview: planRestore(backup) })
306
+ return
307
+ }
308
+ if (route === '/api/restore' && method === 'POST') {
309
+ const body = await readJsonBody(request)
310
+ if (body?.planId !== undefined) {
311
+ if (body.backup !== undefined) throw new ConfigSyncError('A reviewed import accepts a plan ID, not a replacement backup.', 'invalid')
312
+ sendJson(response, 200, session.confirmLocal(body.planId, body.confirm))
313
+ return
314
+ }
315
+ if (body?.confirm !== true) {
316
+ throw new ConfigSyncError('restoring requires an explicit confirmation', 'invalid')
317
+ }
318
+ const { report } = applyRestore(body?.backup)
319
+ sendJson(response, 200, { report })
320
+ return
321
+ }
322
+ if (route === '/api/undo' && method === 'POST') {
323
+ const body = await readJsonBody(request)
324
+ if (body?.expectedStamp !== undefined) {
325
+ if (typeof body.expectedStamp !== 'string' || !body.expectedStamp.trim()) throw new ConfigSyncError('expectedStamp must name the reviewed undo snapshot.', 'invalid')
326
+ if (undoStatus()?.stamp !== body.expectedStamp) throw new ConfigSyncError('The undo snapshot changed. Review the latest restore before undoing it.', 'stale-plan')
327
+ }
328
+ sendJson(response, 200, { report: undoLastRestore() })
329
+ return
330
+ }
331
+ if (route === '/api/file/read' && method === 'POST') {
332
+ const body = await readJsonBody(request)
333
+ const backup = readBackupFile(String(body?.path ?? ''))
334
+ sendJson(response, 200, { backup, preview: planRestore(backup) })
335
+ return
336
+ }
337
+ if (route === '/api/settings' && method === 'POST') {
338
+ const body = await readJsonBody(request)
339
+ const patch = {}
340
+ if (body?.gistId !== undefined) {
341
+ // An empty value clears the remembered cloud copy, which is how the page
342
+ // starts over with a different Gist.
343
+ const raw = typeof body.gistId === 'string' ? body.gistId.trim() : ''
344
+ patch.gistId = raw === '' ? null : parseGistId(raw)
345
+ }
346
+ if (body?.includeMachine !== undefined) patch.includeMachine = body.includeMachine === true
347
+ const stored = writeSettings(patch)
348
+ sendJson(response, 200, {
349
+ cloud: {
350
+ gistId: stored.gistId,
351
+ includeMachine: stored.includeMachine,
352
+ lastUpload: stored.lastUpload,
353
+ lastSync: stored.lastSync,
354
+ settingsFile: settingsPath(),
355
+ },
356
+ })
357
+ return
358
+ }
359
+ if (route === '/api/gist/token' && method === 'POST') {
360
+ const body = await readJsonBody(request)
361
+ const resolved = await resolveTokenSource(body?.token)
362
+ const login = await verifyToken(resolved.token)
363
+ if (!login) throw new ConfigSyncError('GitHub did not identify an account for this token.', 'auth')
364
+ sendJson(response, 200, { source: resolved.source, login })
365
+ return
366
+ }
367
+ if (route === '/api/gist/upload' && method === 'POST') {
368
+ const body = await readJsonBody(request)
369
+ const resolved = await resolveTokenSource(body?.token)
370
+ const { backup, dropped, droppedEntries } = exportBackupWithReport({ includeMachine: body?.includeMachine === true })
371
+ const content = `${JSON.stringify(backup, null, 2)}\n`
372
+ const id = targetId(body?.id)
373
+ // The upload preview names either a particular Gist or a new one (null).
374
+ // Compare at the point of selecting the destination, before either write.
375
+ if (body?.expectedTarget !== undefined && body.expectedTarget !== id) {
376
+ throw new ConfigSyncError('The upload target changed. Review the destination before uploading again.', 'stale-plan')
377
+ }
378
+ const ref = id === null
379
+ ? await createGist(resolved.token, content)
380
+ : await updateGist(resolved.token, id, content)
381
+ // Remember where the cloud copy lives and when it was written, so the next
382
+ // upload, the sync button, and the status line need no typing.
383
+ writeSettings({
384
+ gistId: ref.id,
385
+ lastUpload: {
386
+ gistId: ref.id,
387
+ at: now(),
388
+ files: backup.files.length,
389
+ bytes: Buffer.byteLength(content),
390
+ created: id === null,
391
+ tokenSource: resolved.source,
392
+ },
393
+ })
394
+ sendJson(response, 200, {
395
+ ref,
396
+ created: id === null,
397
+ tokenSource: resolved.source,
398
+ bytes: Buffer.byteLength(content),
399
+ files: backup.files.length,
400
+ createdAt: backup.createdAt,
401
+ backupBytes: backupBytes(backup),
402
+ // Machine-local dependency specs left out of what was uploaded, so the
403
+ // page can say so instead of the user finding out on the other machine.
404
+ dropped,
405
+ droppedEntries,
406
+ })
407
+ return
408
+ }
409
+ if (route === '/api/gist/read' && method === 'POST') {
410
+ const body = await readJsonBody(request)
411
+ const resolved = await resolveTokenSource(body?.token)
412
+ const id = targetId(body?.id)
413
+ if (id === null) throw new ConfigSyncError('no cloud backup is set up yet', 'no-cloud')
414
+ const { ref, backup } = await readGist(resolved.token, id)
415
+ sendJson(response, 200, { ref, backup, preview: planRestore(backup), tokenSource: resolved.source })
416
+ return
417
+ }
418
+ if (route === '/api/sync' && method === 'POST') {
419
+ // One call for the whole job: read the cloud copy, then write it here with
420
+ // an undo snapshot taken first.
421
+ const body = await readJsonBody(request)
422
+ const resolved = await resolveTokenSource(body?.token)
423
+ const id = targetId(body?.id)
424
+ if (id === null) {
425
+ throw new ConfigSyncError('there is no cloud backup yet: upload this machine first', 'no-cloud')
426
+ }
427
+ const { ref, backup } = await readGist(resolved.token, id)
428
+ const { report, warnings } = restoreGistConfiguration(ref, backup, { bindUploadTarget: true })
429
+ sendJson(response, 200, { ref, report, tokenSource: resolved.source, undoDir: report.undoDir, ...(warnings.length ? { warnings } : {}) })
430
+ return
431
+ }
432
+ sendJson(response, 404, { error: `no such route: ${route}`, code: 'notfound' })
433
+ } catch (error) {
434
+ sendJson(response, statusOf(error), describeError(error))
435
+ } finally {
436
+ release?.()
437
+ }
438
+ }
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
+ }