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.
@@ -0,0 +1,338 @@
1
+ /** One confirmation for the exact Gist snapshot and plugin sources reviewed. */
2
+ import assert from 'node:assert/strict'
3
+ import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import {
6
+ backupDocument, callRoute, createReport, makeProfile, serveHandler,
7
+ stubGithub, tempDir, TEST_GIST_ID as ID, TEST_TOKEN, useProfile,
8
+ } from './harness.mjs'
9
+
10
+ const { check, finish } = createReport('preview and install')
11
+ const home = tempDir('dpg-sync-install-')
12
+ // The runner gives this file its own process. Even a mistaken token lookup or
13
+ // attempt to start a package manager must not find the user's gh, token or home.
14
+ useProfile(join(home, 'profiles', 'test'), home)
15
+ process.env.HOME = process.env.USERPROFILE = home
16
+ process.env.PATH = join(home, 'no-executables')
17
+ for (const name of ['GITHUB_TOKEN', 'DSH_GITHUB_TOKEN', 'GH_TOKEN']) delete process.env[name]
18
+ const { BASE_PATH, registerRoutes } = await import('../lib/routes.js')
19
+ check('routes use the fork namespace', BASE_PATH === '/dsh-profile-gist-sync-plus', BASE_PATH)
20
+
21
+ const CLOUD = 'cloud-plugin'
22
+ const SPEC = `${CLOUD}@1.2.3`
23
+ const NOTE = 'data/note.json'
24
+ const reviewed = '{"revision":"reviewed"}'
25
+ const applied = { changed: true, application: 'applied' }
26
+
27
+ // An upstream v0.2 document: no fork-specific metadata or installation list.
28
+ function legacyBackup(dependencies = { [CLOUD]: '1.2.3' }, bundles = Object.keys(dependencies)) {
29
+ const doc = backupDocument('other-machine', [{ path: NOTE, lines: [reviewed] }])
30
+ Object.assign(doc.files[0].json, { dependencies, dsh: { profile: { bundles } } })
31
+ return doc
32
+ }
33
+
34
+ // Bind the manager to a particular throwaway manifest. Like the Host, an
35
+ // applied install records its dependency. It never downloads or runs anything.
36
+ function managerWith(present = [], install = () => applied) {
37
+ return profile => {
38
+ const installed = new Set(present)
39
+ const calls = []
40
+ const file = join(profile, 'package.json')
41
+ return {
42
+ calls,
43
+ listPlugins: async () => [],
44
+ listBundles: () => [...installed].map(name => ({ name, availability: 'profile', installed: true, enabled: true })),
45
+ async installBundle(spec, options) {
46
+ const [name, version] = spec.split('@') // fixture specs use unscoped npm names
47
+ const manifest = JSON.parse(readFileSync(file, 'utf8'))
48
+ calls.push({ spec, options, priorSpec: manifest.dependencies?.[name] })
49
+ const result = await install(spec)
50
+ if (result.application === 'applied' || result.application === 'restart-required') {
51
+ installed.add(name)
52
+ manifest.dependencies = { ...manifest.dependencies, [name]: version }
53
+ writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`)
54
+ }
55
+ return { stage: 'install', target: spec, ...result }
56
+ },
57
+ }
58
+ }
59
+ }
60
+
61
+ // Compare the whole fixture, including hidden settings, undo and node_modules,
62
+ // not just the manifest. A preview must not create even an empty directory.
63
+ function snapshot(dir) {
64
+ return Object.fromEntries(readdirSync(dir, { withFileTypes: true }).map(entry => {
65
+ const file = join(dir, entry.name)
66
+ return [entry.name, entry.isDirectory() ? snapshot(file) : readFileSync(file, 'base64')]
67
+ }))
68
+ }
69
+
70
+ function expectStatus(response, status) {
71
+ assert.equal(response.status, status, `${response.status}: ${JSON.stringify(response.payload).slice(0, 240)}`)
72
+ return response.payload
73
+ }
74
+
75
+ let serial = 0
76
+ async function scenario(label, {
77
+ document = legacyBackup(), manager: makeManager = managerWith(), local = { dependencies: {}, bundles: [] }, onRequest,
78
+ }, run) {
79
+ const profile = makeProfile(join(home, 'profiles', `case-${++serial}`), local)
80
+ useProfile(profile, home)
81
+ const manager = makeManager?.(profile)
82
+ let handler
83
+ const webServer = { register(route) { handler = route.handler; return () => {} } }
84
+ const dispose = registerRoutes({ get: name => ({ webServer, pluginManager: manager })[name] })
85
+ const served = await serveHandler((req, res) => { onRequest?.(req, res); handler(req, res) })
86
+ const repo = stubGithub({ gistId: ID, document })
87
+ const api = (path, body) => callRoute(served.base, `${BASE_PATH}/api/${path}`, body)
88
+ const post = (path, body) => api(`sync/${path}`, body)
89
+ const preview = async () => expectStatus(await post('preview', { id: ID, token: TEST_TOKEN }), 200)
90
+ const confirm = (planId, extra) => post('install', { planId, confirm: true, ...extra })
91
+ try {
92
+ await run({ profile, document, manager, repo, api, post, preview, confirm })
93
+ check(label, true)
94
+ } catch (error) {
95
+ check(label, false, error.stack)
96
+ } finally {
97
+ repo.restore()
98
+ served.close()
99
+ dispose()
100
+ }
101
+ }
102
+
103
+ const requested = manager => manager.calls.map(call => call.spec)
104
+ const reads = repo => repo.calls.map(({ method, path }) => `${method} ${path}`)
105
+ const singleRead = [`GET /gists/${ID}`]
106
+
107
+ await scenario('v0.2 preview is read-only; one confirmation restores and installs exactly what was reviewed', {
108
+ document: legacyBackup({ [CLOUD]: '1.2.3', 'present-plugin': '2.0.0' }),
109
+ local: { dependencies: { 'target-only': '4.0.0' }, bundles: ['target-only'] },
110
+ manager: managerWith(['present-plugin'], () => ({ changed: true, application: 'restart-required' })),
111
+ }, async ({ profile, document, manager, repo, preview, confirm }) => {
112
+ const before = snapshot(profile)
113
+ const plan = await preview()
114
+ assert.equal(typeof plan.planId, 'string')
115
+ assert.ok(plan.planId.length > 0)
116
+ assert.equal(plan.ref.id, ID)
117
+ assert.ok(plan.preview.files.some(file => file.path === NOTE && file.status === 'overwrite'))
118
+ assert.equal(plan.plugins.available, true)
119
+ assert.deepEqual(plan.plugins.missing.map(row => row.installSpec), [SPEC])
120
+ assert.deepEqual(snapshot(profile), before)
121
+ assert.deepEqual(requested(manager), [])
122
+ assert.deepEqual(reads(repo), singleRead)
123
+
124
+ // Someone edits the remote backing document after the user sees the plan.
125
+ document.files[0].json.dependencies[CLOUD] = '9.9.9'
126
+ document.files.find(file => file.path === NOTE).lines = ['{"revision":"later"}']
127
+ const result = expectStatus(await confirm(plan.planId), 200)
128
+ assert.ok(result.report.files.some(file => file.path === NOTE))
129
+ assert.equal(readFileSync(join(profile, NOTE), 'utf8'), reviewed)
130
+ const restored = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8'))
131
+ assert.equal(restored.dependencies[CLOUD], '1.2.3')
132
+ assert.equal(restored.dependencies['target-only'], '4.0.0')
133
+ assert.deepEqual(requested(manager), [SPEC], 'neither the present plugin nor the unrelated local gap is installed')
134
+ assert.equal(manager.calls[0].priorSpec, undefined, 'only the installer introduces the new dependency')
135
+ const row = result.plugins.results.find(row => row.name === CLOUD)
136
+ assert.equal(row?.outcome, 'installed')
137
+ assert.deepEqual(row.pendingBuilds, [])
138
+ assert.equal(result.complete, true)
139
+ assert.equal(result.restart, true, 'installation complete does not mean already active')
140
+ assert.deepEqual(reads(repo), singleRead)
141
+
142
+ // Detect a replayed *restore* even if the updated inventory hides a second install.
143
+ writeFileSync(join(profile, NOTE), '{"after":"confirmation"}')
144
+ const after = snapshot(profile)
145
+ expectStatus(await confirm(plan.planId), 409)
146
+ assert.deepEqual(snapshot(profile), after)
147
+ assert.deepEqual(requested(manager), [SPEC])
148
+ assert.deepEqual(reads(repo), singleRead)
149
+ })
150
+
151
+ await scenario('missing confirmation, unknown and expired plans cannot write or install', {}, async ({ profile, manager, repo, post, preview, confirm }) => {
152
+ const before = snapshot(profile)
153
+ const { planId } = await preview()
154
+ expectStatus(await post('install', { planId }), 400)
155
+ expectStatus(await post('install', { planId, confirm: 'true' }), 400)
156
+ expectStatus(await confirm('not-a-plan'), 409)
157
+ // Use a fresh plan so an earlier denial cannot be mistaken for expiry.
158
+ const fresh = await preview()
159
+ const now = Date.now
160
+ try {
161
+ const afterExpiry = now() + 5 * 60_000 + 1_000
162
+ Date.now = () => afterExpiry
163
+ expectStatus(await confirm(fresh.planId), 409)
164
+ } finally {
165
+ Date.now = now
166
+ }
167
+ assert.deepEqual(snapshot(profile), before)
168
+ assert.deepEqual(requested(manager), [])
169
+ assert.deepEqual(reads(repo), [...singleRead, ...singleRead])
170
+ })
171
+
172
+ // Hold the manager open until both confirmation bodies reached the HTTP handler.
173
+ // Otherwise an unguarded first call may finish before a 'parallel' second call starts.
174
+ {
175
+ let release
176
+ const gate = new Promise(resolve => { release = resolve })
177
+ let requests = 0
178
+ const manager = managerWith([], async () => { await gate; return applied })
179
+ await scenario('overlapping submissions consume one plan and call installBundle once', {
180
+ manager,
181
+ onRequest(req, res) {
182
+ if (!req.url.endsWith('/api/sync/install') || ++requests !== 2) return
183
+ req.once('end', () => setImmediate(release))
184
+ res.once('finish', release) // a busy route may refuse before consuming the body
185
+ },
186
+ }, async ({ preview, confirm, repo, manager }) => {
187
+ const { planId } = await preview()
188
+ const both = await Promise.all([confirm(planId), confirm(planId)])
189
+ assert.deepEqual(both.map(response => response.status).sort(), [200, 409])
190
+ assert.equal(both.find(response => response.status === 200).payload.complete, true)
191
+ assert.deepEqual(requested(manager), [SPEC])
192
+ assert.deepEqual(reads(repo), singleRead)
193
+ })
194
+ }
195
+
196
+ await scenario('no usable manager means no confirmable plan or restore', { manager: null }, async ({ profile, preview, confirm, repo }) => {
197
+ const before = snapshot(profile)
198
+ const plan = await preview()
199
+ assert.equal(plan.plugins.available, false)
200
+ assert.equal(plan.planId, null)
201
+ const refusal = await confirm(plan.planId)
202
+ assert.ok(refusal.status >= 400 && refusal.status < 500)
203
+ assert.deepEqual(snapshot(profile), before)
204
+ assert.deepEqual(reads(repo), singleRead)
205
+ })
206
+
207
+ const unresolved = ['local-plugin', 'file-plugin', 'bundle-only']
208
+ await scenario('foreign local paths and a bundle name without a source are reported, never downloaded', {
209
+ document: legacyBackup({ 'local-plugin': 'link:D:/sender-only/plugin', 'file-plugin': 'file:../other-checkout' }, unresolved),
210
+ local: { dependencies: { 'local-plugin': '4.5.6' }, bundles: [] },
211
+ }, async ({ profile, preview, confirm, manager }) => {
212
+ const plan = await preview()
213
+ for (const name of unresolved) {
214
+ const row = plan.plugins.missing.find(entry => entry.name === name)
215
+ assert.equal(row?.resolvable, false, name)
216
+ assert.equal(row.installSpec, null, name)
217
+ }
218
+ const result = expectStatus(await confirm(plan.planId), 200)
219
+ assert.equal(result.complete, false)
220
+ assert.equal(readFileSync(join(profile, NOTE), 'utf8'), reviewed)
221
+ assert.deepEqual(JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')).dependencies, { 'local-plugin': '4.5.6' })
222
+ for (const name of unresolved) {
223
+ const row = result.plugins.results.find(entry => entry.name === name)
224
+ assert.equal(row?.outcome, 'skipped', name)
225
+ assert.deepEqual(row.pendingBuilds, [])
226
+ }
227
+ assert.deepEqual(requested(manager), [])
228
+ })
229
+
230
+ for (const [label, change] of [
231
+ ['failed install', { changed: false, application: 'failed', error: { code: 'operation-error', diagnostic: 'fake registry offline' } }],
232
+ ['pending build approval', { ...applied, pendingBuilds: ['native-helper'] }],
233
+ ]) {
234
+ await scenario(`${label}: a restored configuration is not a fully successful install`, {
235
+ manager: managerWith([], () => change),
236
+ }, async ({ profile, preview, confirm, manager }) => {
237
+ const { planId } = await preview()
238
+ const result = expectStatus(await confirm(planId), 200)
239
+ assert.equal(readFileSync(join(profile, NOTE), 'utf8'), reviewed)
240
+ assert.equal(result.complete, false)
241
+ const row = result.plugins.results.find(entry => entry.name === CLOUD)
242
+ assert.deepEqual(row?.pendingBuilds, change.pendingBuilds ?? [])
243
+ if (change.error) assert.equal(row.outcome, 'failed')
244
+ assert.deepEqual(requested(manager), [SPEC])
245
+ assert.deepEqual(manager.calls[0].options?.approvedBuilds ?? [], [])
246
+ })
247
+ }
248
+
249
+ // The installer must see the receiving machine's policy, not the sender's,
250
+ // even momentarily. Observe it from inside the fake manager as well as after.
251
+ {
252
+ const document = legacyBackup()
253
+ Object.assign(document.files[0].json, { scripts: { install: 'sender-marker' }, version: '7.0.0' })
254
+ document.files.push(
255
+ { path: '.npmrc', lines: ['registry=https://sender.invalid/', ''] },
256
+ { path: 'pnpm-workspace.yaml', lines: ['packages: [sender-workspace]', ''] },
257
+ )
258
+ function policy(profile) {
259
+ const { scripts, version } = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8'))
260
+ return { scripts, version, npmrc: readFileSync(join(profile, '.npmrc'), 'utf8'), workspace: readFileSync(join(profile, 'pnpm-workspace.yaml'), 'utf8') }
261
+ }
262
+ const observed = []
263
+ await scenario('restore keeps package-manager inputs and manifest scripts/version local', {
264
+ document,
265
+ manager: profile => managerWith([], () => { observed.push(policy(profile)); return applied })(profile),
266
+ }, async ({ profile, preview, confirm }) => {
267
+ const manifest = join(profile, 'package.json')
268
+ const local = JSON.parse(readFileSync(manifest, 'utf8'))
269
+ Object.assign(local, { scripts: { test: 'receiver-marker' }, version: '1.0.0' })
270
+ writeFileSync(manifest, `${JSON.stringify(local, null, 2)}\n`)
271
+ const expected = policy(profile)
272
+ const plan = await preview()
273
+ for (const name of ['.npmrc', 'pnpm-workspace.yaml']) {
274
+ assert.ok(!plan.preview.files.some(file => file.path === name))
275
+ assert.ok(plan.preview.dropped.some(file => file.path === name))
276
+ }
277
+ const result = expectStatus(await confirm(plan.planId), 200)
278
+ assert.equal(result.complete, true)
279
+ assert.deepEqual(observed, [expected])
280
+ assert.deepEqual(policy(profile), expected)
281
+ })
282
+ }
283
+
284
+ for (const [path, before, after] of [[NOTE, 'world', 'earth'], ['package.json', 'dsh-profile-test', 'dsh-profile-edit']]) {
285
+ await scenario(`editing ${path} after preview invalidates confirmation before any writes or install`, {}, async ({ profile, manager, repo, preview, confirm }) => {
286
+ const { planId } = await preview()
287
+ const file = join(profile, path)
288
+ const original = readFileSync(file, 'utf8')
289
+ assert.ok(original.includes(before))
290
+ writeFileSync(file, original.replace(before, after)) // same byte length, still an overwrite/merge
291
+ const edited = snapshot(profile)
292
+ expectStatus(await confirm(planId), 409)
293
+ assert.deepEqual(snapshot(profile), edited)
294
+ assert.deepEqual(requested(manager), [])
295
+ assert.deepEqual(reads(repo), singleRead)
296
+ })
297
+ }
298
+
299
+ await scenario('confirmation cannot substitute a client-supplied install target', {}, async ({ preview, confirm, manager, repo, profile }) => {
300
+ const { planId } = await preview()
301
+ const before = snapshot(profile)
302
+ const alternate = 'unreviewed-target@7.0.0'
303
+ const response = await confirm(planId, { spec: alternate, plugins: [{ name: CLOUD, installSpec: alternate }] })
304
+ if (response.status === 200) assert.deepEqual(requested(manager), [SPEC]) // unknown fields ignored
305
+ else {
306
+ assert.ok(response.status >= 400 && response.status < 500)
307
+ assert.deepEqual(requested(manager), []) // strict validation is also safe
308
+ assert.deepEqual(snapshot(profile), before)
309
+ }
310
+ assert.deepEqual(reads(repo), singleRead)
311
+ })
312
+
313
+ await scenario('token verification rejects a GitHub 401 and a response without an account login', {}, async ({ api, repo }) => {
314
+ const offlineFetch = globalThis.fetch // already stubbed by the fixture, including all Gist traffic
315
+ const verify = () => api('gist/token', { token: TEST_TOKEN })
316
+ try {
317
+ for (const [status, account] of [[401, { message: 'Bad credentials' }], [200, { id: 123 }]]) {
318
+ let checks = 0
319
+ globalThis.fetch = (input, init) => {
320
+ const url = typeof input === 'string' ? input : input?.url ?? String(input)
321
+ if (url !== 'https://api.github.com/user') return offlineFetch(input, init)
322
+ checks++
323
+ return Response.json(account, { status })
324
+ }
325
+ const error = expectStatus(await verify(), 401)
326
+ assert.equal(error.code, 'auth')
327
+ assert.equal(error.login, undefined)
328
+ assert.equal(checks, 1)
329
+ }
330
+ } finally {
331
+ globalThis.fetch = offlineFetch
332
+ }
333
+ // Control: a verified login succeeds; no Gist download was needed for any token check.
334
+ assert.equal(expectStatus(await verify(), 200).login, 'someone')
335
+ assert.deepEqual(reads(repo), ['GET /user'])
336
+ })
337
+
338
+ process.exitCode = finish()