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.
@@ -0,0 +1,255 @@
1
+ /** Rename regression: real v0.2 export/restore code, temporary profiles, no sockets or package manager. */
2
+ import assert from 'node:assert/strict'
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { pathToFileURL } from 'node:url'
6
+ import { createReport, makeProfile, tempDir, TEST_GIST_ID, useProfile } from './harness.mjs'
7
+ import { applyRestore, exportBackup, planRestore, rememberProfile, resolveProfile, undoLastRestore, undoStatus, validateBackup, WORK_DIR } from '../lib/backup.js'
8
+ import { installMissingPlugins, pluginInventory } from '../lib/plugins.js'
9
+ import { readSettings, settingsPath } from '../lib/store.js'
10
+ import { createRestoreSession } from '../lib/sync-install.js'
11
+
12
+ const { check, finish } = createReport('npm rename compatibility')
13
+ const OLD = 'dsh-profile-gist-sync-plus'
14
+ const NEW = 'dsh-multi-device-config-sync'
15
+ const UPSTREAM = 'dsh-profile-gist-sync'
16
+ const OTHER = `${OLD}-helper` // a real, distinct name; never collapse a prefix or row ID into the sync package
17
+ const GIT = `git+https://github.com/Xeonice/${OLD}.git#${'a'.repeat(40)}`
18
+ const home = tempDir('dsh-rename-')
19
+ process.env.HOME = process.env.USERPROFILE = process.env.DSH_HOME = home
20
+ process.env.PATH = join(home, 'no-executables')
21
+ for (const key of ['GITHUB_TOKEN', 'DSH_GITHUB_TOKEN', 'GH_TOKEN', 'DSH_PROFILE', 'DSH_PROFILE_DIR']) delete process.env[key]
22
+ globalThis.fetch = () => { throw new Error('unexpected network request') }
23
+ const json = path => JSON.parse(readFileSync(path, 'utf8'))
24
+ const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
25
+ const profileAt = (root, name, dependencies = {}, bundles = []) => makeProfile(join(root, 'profiles', name), { dependencies, bundles })
26
+ const pkgFile = dir => join(dir, 'package.json')
27
+ function installed(dir, name, version = '1.0.0') {
28
+ const path = join(dir, 'node_modules', name)
29
+ mkdirSync(path, { recursive: true })
30
+ writeJson(pkgFile(path), { name, version, type: 'module' })
31
+ return path
32
+ }
33
+ async function test(label, fn) {
34
+ rememberProfile(null)
35
+ try { await fn(); check(label, true) } catch (error) { check(label, false, error.stack) }
36
+ }
37
+ function noHint(root) {
38
+ process.env.DSH_HOME = root
39
+ delete process.env.DSH_PROFILE
40
+ delete process.env.DSH_PROFILE_DIR
41
+ }
42
+
43
+ // These are the manifest key, pinned Git source, bundle selection and unchanged
44
+ // row id a 1.4.1 profile carries. Export it, rather than hand-normalizing a fixture.
45
+ const sender = profileAt(home, 'git-machine', { [OLD]: GIT, [UPSTREAM]: '1.0.2', [OTHER]: '2.3.4', present: '1.0.0' }, [OLD, UPSTREAM])
46
+ installed(sender, OLD, '1.4.1')
47
+ writeFileSync(join(sender, 'cordis.patch.yml'), `# keep the stable row id ${OLD} as ordinary text\n[]\n`)
48
+ useProfile(sender, home)
49
+ const original = exportBackup()
50
+ const originalBytes = JSON.stringify(original)
51
+ const manifestOf = backup => backup.files.find(f => f.path === 'package.json').json
52
+ const receiver = profileAt(home, 'npm-machine', { [NEW]: '~1.5.0', 'target-only': '4.0.0' }, [NEW])
53
+ installed(receiver, NEW, '1.5.0')
54
+ installed(receiver, 'present')
55
+
56
+ await test('the current package, not a separate old Git or upstream profile, resolves the existing Plus settings, exports and undo', () => {
57
+ installed(profileAt(home, 'upstream-only'), UPSTREAM)
58
+ const work = join(receiver, '.dsh-config-sync-plus')
59
+ mkdirSync(join(work, 'exports'), { recursive: true })
60
+ writeJson(join(work, 'exports', 'from-plus.json'), original)
61
+ mkdirSync(join(work, 'undo', '0001'), { recursive: true })
62
+ writeJson(join(work, 'undo', '0001', 'manifest.json'), { createdAt: '2020-01-01', entries: [] })
63
+ writeJson(join(work, 'settings.json'), { gistId: TEST_GIST_ID, includeMachine: true })
64
+ noHint(home)
65
+ assert.equal(resolveProfile().dir, receiver)
66
+ assert.equal(resolveProfile().source, 'profile with this plugin installed')
67
+ assert.equal(settingsPath(), join(work, 'settings.json'))
68
+ assert.equal(readSettings().gistId, TEST_GIST_ID)
69
+ assert.equal(undoStatus().stamp, '0001')
70
+ assert.equal(WORK_DIR, '.dsh-config-sync-plus')
71
+ assert.deepEqual(json(join(work, 'exports', 'from-plus.json')), original)
72
+ assert.ok(!exportBackup().files.some(f => f.path.includes(WORK_DIR)))
73
+ })
74
+
75
+ await test('no implicit old-only profile; ambiguous new installations need matching module provenance or an explicit profile', async () => {
76
+ for (const name of [OLD, UPSTREAM]) {
77
+ const root = join(home, `${name}-in-isolation`)
78
+ noHint(root)
79
+ profileAt(root, 'not-this-process', { [name]: '1.0.0' }, [])
80
+ assert.throws(resolveProfile, { code: 'no-profile' })
81
+ // A second profile is not permission to pick the one holding the old package either.
82
+ installed(profileAt(root, 'elsewhere'), name)
83
+ assert.throws(resolveProfile, { code: 'no-profile' })
84
+ }
85
+ const aliasHome = join(home, 'wrong-package')
86
+ noHint(aliasHome)
87
+ const alias = installed(profileAt(aliasHome, 'alias-only'), NEW)
88
+ writeJson(pkgFile(alias), { name: OLD, version: '1.4.1' })
89
+ assert.throws(resolveProfile, { code: 'no-profile' }, 'a directory named after the new package is not enough')
90
+ const root = join(home, 'two-new-copies')
91
+ const a = profileAt(root, 'one'), b = profileAt(root, 'two')
92
+ installed(a, NEW); const loaded = installed(b, NEW)
93
+ noHint(root)
94
+ assert.throws(resolveProfile, { code: 'no-profile' }, 'a separate source checkout has no unique match')
95
+ mkdirSync(join(loaded, 'lib'))
96
+ for (const file of ['backup.js', 'errors.js']) copyFileSync(new URL(`../lib/${file}`, import.meta.url), join(loaded, 'lib', file))
97
+ const realCopy = await import(pathToFileURL(join(loaded, 'lib', 'backup.js')).href)
98
+ assert.equal(realCopy.resolveProfile().dir, b)
99
+ useProfile(a, root)
100
+ assert.equal(realCopy.resolveProfile().dir, a, 'explicit profile wins over installation heuristics')
101
+ })
102
+
103
+ // A manager that records the precise installer handoff and represents successful
104
+ // installs by writing a tiny manifest in the fixture. No package code is fetched or run.
105
+ function fixtureManager(dir, permitted) {
106
+ const calls = []
107
+ return { calls,
108
+ listPlugins: () => [], listBundles: () => [],
109
+ async installBundle(spec, options) {
110
+ calls.push({ spec, options, manifestBefore: json(pkgFile(dir)) })
111
+ const pair = permitted.find(([name, version]) => `${name}@${version}` === spec)
112
+ assert.ok(pair, `unexpected installer target: ${spec}`)
113
+ const [name, version] = pair
114
+ installed(dir, name, version)
115
+ const manifest = json(pkgFile(dir))
116
+ writeJson(pkgFile(dir), { ...manifest, dependencies: { ...manifest.dependencies, [name]: version } })
117
+ return { changed: true, application: 'applied' }
118
+ },
119
+ }
120
+ }
121
+
122
+ await test('a pinned-Git export previews skipped self entries and only confirms real third-party gaps; old, new and local-only targets never reach the installer', async () => {
123
+ useProfile(receiver, home)
124
+ assert.equal(manifestOf(original).dependencies[OLD], GIT)
125
+ assert.ok(manifestOf(original).dsh.profile.bundles.includes(OLD))
126
+ const manager = fixtureManager(receiver, [[UPSTREAM, '1.0.2'], [OTHER, '2.3.4']])
127
+ const session = createRestoreSession({ pluginManager: manager })
128
+ try {
129
+ const before = readFileSync(pkgFile(receiver), 'utf8')
130
+ const plan = await session.preview({ id: TEST_GIST_ID }, validateBackup(original))
131
+ assert.deepEqual(plan.plugins.installed, ['present'])
132
+ assert.deepEqual(plan.plugins.missing.map(p => [p.name, p.installSpec]), [[UPSTREAM, `${UPSTREAM}@1.0.2`], [OTHER, `${OTHER}@2.3.4`]])
133
+ const skips = plan.preview.dropped.filter(f => f.code === 'legacy-sync-package')
134
+ assert.equal(skips.length, 2)
135
+ assert.ok(['dependencies', 'dsh.profile.bundles'].every(field => skips.some(s => s.path.includes(field) && s.path.includes(OLD))))
136
+ assert.ok(!plan.preview.manifest.bundlesAdded.includes(OLD))
137
+ await assert.rejects(session.confirm(plan.planId, false), { code: 'invalid' })
138
+ assert.equal(manager.calls.length, 0)
139
+ assert.equal(readFileSync(pkgFile(receiver), 'utf8'), before)
140
+ const result = await session.confirm(plan.planId, true)
141
+ assert.deepEqual(result.report.dropped, plan.preview.dropped, 'all reasons including local-policy exclusions survive confirmation')
142
+ assert.deepEqual(manager.calls.map(call => call.spec), [`${UPSTREAM}@1.0.2`, `${OTHER}@2.3.4`])
143
+ assert.deepEqual(manager.calls.map(call => call.options.enabled), [true, false])
144
+ for (const call of manager.calls) {
145
+ assert.equal(call.manifestBefore.dependencies[NEW], '~1.5.0')
146
+ assert.ok(!Object.hasOwn(call.manifestBefore.dependencies, OLD) && !call.manifestBefore.dsh.profile.bundles.includes(OLD))
147
+ assert.ok(!Object.hasOwn(call.options, 'approvedBuilds'))
148
+ }
149
+ assert.equal(result.complete, true)
150
+ assert.deepEqual(json(pkgFile(receiver)).dsh.profile.bundles, [NEW, UPSTREAM])
151
+ assert.equal(JSON.stringify(original), originalBytes)
152
+ await assert.rejects(session.confirm(plan.planId, true), { code: 'stale-plan' })
153
+ } finally { session.dispose() }
154
+ })
155
+
156
+ await test('full local/cloud previews, confirmation and undo preserve receiver self specs/selection in a mixed backup; upstream and other config retain normal semantics', () => {
157
+ const mixed = structuredClone(original)
158
+ const fields = ['devDependencies', 'optionalDependencies', 'peerDependencies']
159
+ const incoming = manifestOf(mixed)
160
+ incoming.dependencies[NEW] = '9.9.9'
161
+ incoming.dsh.profile.bundles.push(NEW)
162
+ for (const field of fields) incoming[field] = { [OLD]: GIT, [NEW]: '9.9.9', 'other-library': '2.0.0' }
163
+ const sourceBytes = JSON.stringify(mixed)
164
+ for (const mode of ['local', 'config']) {
165
+ const target = profileAt(home, `mixed-${mode}`, { [NEW]: '~1.5.0', [UPSTREAM]: '1.0.0' }, [])
166
+ useProfile(target, home)
167
+ const current = json(pkgFile(target))
168
+ for (const field of fields) current[field] = { [NEW]: '~1.5.0', 'other-library': '1.0.0' }
169
+ writeJson(pkgFile(target), current)
170
+ const before = readFileSync(pkgFile(target), 'utf8')
171
+ const session = createRestoreSession({ get() { throw new Error('no manager in a configuration-only restore') } })
172
+ try {
173
+ const doc = validateBackup(mixed)
174
+ const plan = mode === 'local' ? session.previewLocal(doc) : session.previewConfig({ id: TEST_GIST_ID }, doc)
175
+ for (const [name, code] of [[OLD, 'legacy-sync-package'], [NEW, 'local-sync-package']]) {
176
+ const skipped = plan.preview.dropped.filter(row => row.code === code)
177
+ assert.ok(['dependencies', ...fields, 'dsh.profile.bundles'].every(field => skipped.some(row => row.path.includes(field) && row.path.endsWith(name))))
178
+ assert.ok(!plan.preview.manifest.dependenciesAdded.includes(name) && !plan.preview.manifest.bundlesAdded.includes(name))
179
+ }
180
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
181
+ const { report } = mode === 'local' ? session.confirmLocal(plan.planId, true) : session.confirmConfig(plan.planId, true)
182
+ assert.deepEqual(report.dropped, plan.preview.dropped)
183
+ assert.equal(report.droppedEntries, plan.preview.dropped.length)
184
+ const after = json(pkgFile(target))
185
+ for (const field of ['dependencies', ...fields]) {
186
+ assert.ok(!Object.hasOwn(after[field], OLD))
187
+ assert.equal(after[field][NEW], '~1.5.0')
188
+ }
189
+ for (const field of fields) assert.equal(after[field]['other-library'], '2.0.0')
190
+ assert.equal(after.dependencies[UPSTREAM], '1.0.2')
191
+ assert.deepEqual(after.dsh.profile.bundles, [UPSTREAM], 'neither sync package was enabled')
192
+ assert.equal(readFileSync(join(target, 'cordis.patch.yml'), 'utf8'), readFileSync(join(sender, 'cordis.patch.yml'), 'utf8'))
193
+ assert.ok(!existsSync(join(target, 'node_modules', UPSTREAM)), 'configuration-only is not an installation')
194
+ undoLastRestore()
195
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
196
+ assert.equal(JSON.stringify(mixed), sourceBytes)
197
+ assert.deepEqual(manifestOf(doc), manifestOf(mixed), 'the validated source is not rewritten either')
198
+ } finally { session.dispose() }
199
+ }
200
+ })
201
+
202
+ await test('a restore differing only by ignored self declarations leaves a matching local manifest byte-for-byte intact with no undo point', () => {
203
+ const target = profileAt(home, 'self-only-difference', { [NEW]: '~1.5.0' }, [NEW])
204
+ useProfile(target, home)
205
+ const here = json(pkgFile(target))
206
+ here.devDependencies = { [NEW]: '~1.5.0', helper: '1.0.0' }
207
+ here.optionalDependencies = { 'receiver-only': '1.0.0' }
208
+ writeJson(pkgFile(target), here)
209
+ const before = readFileSync(pkgFile(target), 'utf8')
210
+ const doc = { ...original, files: [{ path: 'package.json', json: {
211
+ ...here, dependencies: { [OLD]: GIT }, dsh: { profile: { bundles: [OLD] } },
212
+ devDependencies: { [OLD]: GIT, [NEW]: '9.9.9', helper: '1.0.0' }, optionalDependencies: { [OLD]: GIT },
213
+ } }] }
214
+ assert.equal(planRestore(doc).counts.identical, 1)
215
+ const { report, undoDir } = applyRestore(doc)
216
+ assert.ok(report.dropped.some(row => row.code === 'legacy-sync-package'))
217
+ assert.equal(report.restored, 0)
218
+ assert.equal(undoDir, null)
219
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
220
+ })
221
+
222
+ await test('local/tool restore never synthesizes a new npm spec or claims legacy was installed on a machine with neither declaration', () => {
223
+ const target = profileAt(home, 'neither')
224
+ useProfile(target, home)
225
+ const doc = validateBackup(original)
226
+ const plan = planRestore(doc)
227
+ const { report } = applyRestore(doc)
228
+ assert.deepEqual(report.dropped, plan.dropped)
229
+ const saved = json(pkgFile(target))
230
+ for (const name of [OLD, NEW]) assert.ok(!Object.hasOwn(saved.dependencies, name) && !saved.dsh.profile.bundles.includes(name))
231
+ assert.equal(saved.dependencies[OTHER], '2.3.4')
232
+ assert.equal(manifestOf(doc).dependencies[OLD], GIT)
233
+ })
234
+
235
+ await test('stale local declarations stay visibly missing but are never submitted to the installer, even if a caller offers them; other installs honor their allowlist', async () => {
236
+ const target = profileAt(home, 'residue', { [OLD]: GIT, [NEW]: '1.5.0', [OTHER]: '2.3.4', 'not-approved': '7.0.0' })
237
+ useProfile(target, home)
238
+ const manager = fixtureManager(target, [[OTHER, '2.3.4']])
239
+ const ctx = { pluginManager: manager }
240
+ const list = await pluginInventory(ctx)
241
+ assert.deepEqual(list.installed, [])
242
+ for (const [name, reason] of [[OLD, 'legacy-sync-package'], [NEW, 'local-sync-package']]) {
243
+ const row = list.missing.find(p => p.name === name)
244
+ assert.deepEqual([row.resolvable, row.installSpec, row.note], [false, null, reason])
245
+ }
246
+ const approved = new Map([[OLD, GIT], [NEW, `${NEW}@1.5.0`], [OTHER, `${OTHER}@2.3.4`]])
247
+ const result = await installMissingPlugins(ctx, { approved })
248
+ assert.deepEqual(manager.calls.map(call => call.spec), [`${OTHER}@2.3.4`])
249
+ assert.deepEqual(result.installed, [OTHER])
250
+ assert.deepEqual(result.results.filter(row => row.outcome === 'skipped').map(row => row.message), ['legacy-sync-package', 'local-sync-package', 'stale-plan'])
251
+ assert.deepEqual(json(pkgFile(target)).dsh.profile.bundles, [])
252
+ assert.equal(JSON.stringify(original), originalBytes)
253
+ })
254
+
255
+ process.exitCode = finish()
package/test/run.mjs ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Run every check in this directory.
3
+ *
4
+ * Each `*.test.mjs` is a separate process, so one crash cannot hide the others,
5
+ * and every check is offline: profiles are temporary directories, the GitHub
6
+ * layer is stubbed, and the only host any check talks to is its own loopback
7
+ * server. A check may report itself as skipped (no package manager to pack
8
+ * with); that is not a failure.
9
+ *
10
+ * node test/run.mjs
11
+ */
12
+ import { spawnSync } from 'node:child_process'
13
+ import { readdirSync } from 'node:fs'
14
+ import { join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+
17
+ const here = fileURLToPath(new URL('.', import.meta.url))
18
+ const files = readdirSync(here).filter(name => name.endsWith('.test.mjs')).sort()
19
+
20
+ let failed = 0
21
+ for (const file of files) {
22
+ const started = Date.now()
23
+ const result = spawnSync(process.execPath, [join(here, file)], { stdio: 'inherit' })
24
+ const elapsed = `${((Date.now() - started) / 1000).toFixed(1)}s`
25
+ if (result.status !== 0) {
26
+ failed += 1
27
+ console.log(`\n>>> ${file} FAILED (${elapsed})\n`)
28
+ }
29
+ }
30
+
31
+ console.log(`\n${files.length} check file(s), ${files.length - failed} passed, ${failed} failed`)
32
+ process.exit(failed === 0 ? 0 : 1)
@@ -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()