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,104 @@
1
+ /**
2
+ * The first run: a machine that has never had a cloud copy.
3
+ *
4
+ * This is the journey every new user takes, and the only one that cannot be
5
+ * exercised against a real GitHub account without creating a Gist in it. The
6
+ * GitHub HTTP layer is stubbed instead — which also gives the plugin a privacy
7
+ * assertion worth having, because the stub refuses every host but
8
+ * api.github.com: any request anywhere else fails this check.
9
+ */
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
11
+ import { join } from 'node:path'
12
+ import { createReport, makeProfile, tempDir, useProfile, callRoute, serveHandler, stubGithub, backupDocument, TEST_GIST_ID as NEW_ID, TEST_TOKEN } from './harness.mjs'
13
+
14
+ const { check, finish } = createReport('first run')
15
+
16
+ const home = tempDir('dpg-firstrun-')
17
+ const profile = makeProfile(join(home, 'profiles', 'test'))
18
+ useProfile(profile, home)
19
+ process.env.DSH_GITHUB_TOKEN = TEST_TOKEN
20
+
21
+ // The cloud copy this profile will find: the same v0.2 shape upstream writes.
22
+ const stub = stubGithub({
23
+ gistId: NEW_ID,
24
+ document: backupDocument('test', [{ path: 'data/note.json', lines: ['{"hello":"from the cloud"}'] }]),
25
+ })
26
+
27
+ const { registerRoutes, BASE_PATH } = await import('../lib/routes.js')
28
+ let handler = null
29
+ registerRoutes({ get: (name) => (name === 'webServer' ? { register: (route) => { handler = route.handler; return () => {} } } : undefined) })
30
+ const served = await serveHandler(handler)
31
+ const call = (path, body) => callRoute(served.base, `${BASE_PATH}${path}`, body)
32
+ const settingsFile = join(profile, '.dsh-config-sync-plus', 'settings.json')
33
+ // A machine may already run upstream. Its state is neither imported implicitly
34
+ // nor changed by the Plus fork, even when both point at the same profile.
35
+ const upstreamState = join(profile, '.dsh-config-sync')
36
+ mkdirSync(upstreamState)
37
+ const upstreamSettings = '{"gistId":"upstream-fixture"}\n'
38
+ writeFileSync(join(upstreamState, 'settings.json'), upstreamSettings)
39
+
40
+ check('a fresh Plus profile remembers nothing yet', !existsSync(settingsFile))
41
+ const before = await call('/api/status')
42
+ check('status reports no cloud copy', before.status === 200 && before.payload.cloud.gistId === null, JSON.stringify(before.payload.cloud))
43
+
44
+ // A fresh installation can adopt the *document* from upstream by id without
45
+ // importing its settings, uploading, or creating another Gist.
46
+ const legacy = await call('/api/gist/read', { id: NEW_ID })
47
+ check('Plus reads an existing upstream v0.2 Gist before the first upload',
48
+ legacy.status === 200 && legacy.payload.backup?.format === 'dsh-profile-backup' && legacy.payload.backup.version === 0.2
49
+ && !existsSync(settingsFile) && stub.calls.every(entry => entry.method === 'GET'))
50
+
51
+ // ---- the first upload creates a secret Gist ----------------------------
52
+ const upload = await call('/api/gist/upload', {})
53
+ check('the first upload creates a Gist', upload.status === 200 && upload.payload.created === true, JSON.stringify(upload.payload).slice(0, 160))
54
+ const creation = stub.calls.find(entry => entry.method === 'POST' && entry.path === '/gists')
55
+ check('exactly one Gist was created', stub.calls.filter(entry => entry.method === 'POST' && entry.path === '/gists').length === 1)
56
+ check('it is created secret, never public', creation?.body?.public === false, JSON.stringify(creation?.body?.public))
57
+ check('it carries exactly one file, the backup',
58
+ Object.keys(creation?.body?.files ?? {}).join() === 'dsh-profile-backup.json', JSON.stringify(Object.keys(creation?.body?.files ?? {})))
59
+ check('the backup in it is a valid document', typeof creation?.body?.files['dsh-profile-backup.json'].content === 'string'
60
+ && JSON.parse(creation.body.files['dsh-profile-backup.json'].content).format === 'dsh-profile-backup')
61
+ check('the token travels in the header only',
62
+ String(creation?.headers?.authorization ?? '').includes(TEST_TOKEN)
63
+ && !JSON.stringify(creation?.body ?? {}).includes(TEST_TOKEN),
64
+ String(creation?.headers?.authorization ?? '').slice(0, 12))
65
+ check('the Gist description and user agent identify the fork',
66
+ creation?.body?.description?.includes('dsh-multi-device-config-sync') === true && creation?.headers['user-agent'] === 'dsh-multi-device-config-sync')
67
+ check('the created id is remembered in this profile',
68
+ existsSync(settingsFile) && JSON.parse(readFileSync(settingsFile, 'utf8')).gistId === NEW_ID)
69
+
70
+ const after = await call('/api/status')
71
+ check('status now reports the remembered Gist',
72
+ after.payload.cloud.gistId === NEW_ID && after.payload.cloud.lastUpload?.created === true, JSON.stringify(after.payload.cloud))
73
+
74
+ // ---- a second upload updates the same Gist -----------------------------
75
+ const again = await call('/api/gist/upload', {})
76
+ check('a second upload updates instead of creating another',
77
+ again.status === 200 && again.payload.created === false
78
+ && stub.calls.filter(entry => entry.method === 'POST' && entry.path === '/gists').length === 1)
79
+ check('and it targets the remembered id', stub.calls.some(entry => entry.method === 'PATCH' && entry.path === `/gists/${NEW_ID}`))
80
+
81
+ // ---- reading and syncing that cloud copy -------------------------------
82
+ const read = await call('/api/gist/read', {})
83
+ check('the cloud copy reads back', read.status === 200 && read.payload.ref.id === NEW_ID, JSON.stringify(read.payload).slice(0, 160))
84
+ check('and the plan names what a restore would change', read.payload.preview.files.length > 0, JSON.stringify(read.payload.preview.counts))
85
+
86
+ const sync = await call('/api/sync', {})
87
+ check('sync applies the cloud copy here', sync.status === 200 && typeof sync.payload.undoDir === 'string', JSON.stringify(sync.payload).slice(0, 160))
88
+ check('the file it wrote holds the cloud content',
89
+ readFileSync(join(profile, 'data', 'note.json'), 'utf8').includes('from the cloud'),
90
+ readFileSync(join(profile, 'data', 'note.json'), 'utf8'))
91
+ check('an undo is offered', (await call('/api/status')).payload.undo !== null)
92
+
93
+ // ---- what the plugin never does ----------------------------------------
94
+ const paths = stub.calls.map(entry => entry.path)
95
+ check('every call went to api.github.com', stub.calls.length > 0 && paths.every(path => path.startsWith('/')))
96
+ check('no request carried a credential store', !JSON.stringify(stub.calls).includes('credentials'))
97
+ check('no request carried local usage counters', !JSON.stringify(stub.calls).includes('usage.json'))
98
+ check('the token is never written into the profile', !readFileSync(settingsFile, 'utf8').includes(TEST_TOKEN))
99
+ check('upstream settings were neither uploaded nor changed', !JSON.stringify(stub.calls).includes('upstream-fixture')
100
+ && readFileSync(join(upstreamState, 'settings.json'), 'utf8') === upstreamSettings)
101
+
102
+ stub.restore()
103
+ served.close()
104
+ process.exit(finish())
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Shared pieces for this plugin's checks.
3
+ *
4
+ * Everything here is deliberately offline and disposable: every profile is a
5
+ * temporary directory built from scratch, and the only network traffic any check
6
+ * produces is what a stub in that check answers. No check reads a real DSH
7
+ * profile, and none of them carries a real Gist id or path.
8
+ */
9
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+
13
+ /** One check, one line of output; failures accumulate instead of throwing. */
14
+ export function createReport(name) {
15
+ const state = { failures: 0, passed: 0 }
16
+ const check = (label, ok, detail) => {
17
+ if (ok === true) state.passed += 1
18
+ else state.failures += 1
19
+ const suffix = ok === true || detail === undefined ? '' : ` -- ${detail}`
20
+ console.log(`${ok === true ? 'ok ' : 'FAIL'} ${label}${suffix}`)
21
+ }
22
+ const finish = () => {
23
+ console.log(state.failures === 0
24
+ ? `\n${name}: ALL CHECKS PASSED (${state.passed})`
25
+ : `\n${name}: ${state.failures} CHECK(S) FAILED, ${state.passed} passed`)
26
+ return state.failures === 0 ? 0 : 1
27
+ }
28
+ return { check, finish, state }
29
+ }
30
+
31
+ /** A temporary directory that is removed when the process exits. */
32
+ export function tempDir(prefix) {
33
+ const directory = mkdtempSync(join(tmpdir(), prefix))
34
+ process.on('exit', () => {
35
+ try {
36
+ rmSync(directory, { recursive: true, force: true })
37
+ } catch {
38
+ // Best effort: a failed cleanup must not change a check's verdict.
39
+ }
40
+ })
41
+ return directory
42
+ }
43
+
44
+ /**
45
+ * A profile with the shape the exporter reads: a manifest, a patch layer, a
46
+ * profile config, npm settings, `data/*.json`, and a `suppliers/` tree — plus a
47
+ * credential store and a binary file, which must be dropped rather than carried.
48
+ *
49
+ * `dependencies` and `bundles`, when given, replace the manifest's own; that is
50
+ * how a check builds the profile the publisher's machine actually has — this
51
+ * plugin installed by path into a local checkout.
52
+ */
53
+ export function makeProfile(root, { dependencies = null, bundles = null } = {}) {
54
+ mkdirSync(join(root, 'data', 'auths'), { recursive: true })
55
+ mkdirSync(join(root, 'suppliers'), { recursive: true })
56
+ mkdirSync(join(root, 'node_modules', 'some-dep'), { recursive: true })
57
+ writeFileSync(join(root, 'package.json'), `${JSON.stringify({
58
+ name: 'dsh-profile-test',
59
+ private: true,
60
+ dependencies: dependencies ?? { 'some-plugin': '1.2.3' },
61
+ dsh: { profile: { bundles: bundles ?? ['@deepseek-ai/dsh-base'] } },
62
+ }, null, 2)}\n`)
63
+ writeFileSync(join(root, 'cordis.patch.yml'), '- insert:\n - id: local-row\n name: some-plugin\n')
64
+ writeFileSync(join(root, 'cordis.yml'), 'plugins:\n some-plugin: {}\n')
65
+ writeFileSync(join(root, '.npmrc'), 'registry=https://registry.example/\n')
66
+ writeFileSync(join(root, 'pnpm-workspace.yaml'), 'packages: []\n')
67
+ writeFileSync(join(root, 'data', 'note.json'), '{"hello":"world"}\n')
68
+ writeFileSync(join(root, 'data', 'usage.json'), '{"turns":3}\n')
69
+ writeFileSync(join(root, 'data', 'auths', 'credentials.sqlite'), Buffer.from([0, 1, 2, 3, 0, 255]))
70
+ writeFileSync(join(root, 'suppliers', 'one.js'), 'export const one = 1\n')
71
+ writeFileSync(join(root, 'node_modules', 'some-dep', 'index.js'), 'module.exports = 1\n')
72
+ writeFileSync(join(root, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
73
+ return root
74
+ }
75
+
76
+ /** Point the plugin at a profile without touching the ambient environment. */
77
+ export function useProfile(root, home) {
78
+ process.env.DSH_PROFILE_DIR = root
79
+ if (home !== undefined) process.env.DSH_HOME = home
80
+ process.env.DSH_PROFILE = 'test'
81
+ }
82
+
83
+ /** An HTTP request against a route handler, with a JSON body when given. */
84
+ export async function callRoute(base, path, body) {
85
+ const response = await fetch(`${base}${path}`, {
86
+ method: body === undefined ? 'GET' : 'POST',
87
+ headers: body === undefined ? undefined : { 'content-type': 'application/json' },
88
+ body: body === undefined ? undefined : JSON.stringify(body),
89
+ })
90
+ const text = await response.text()
91
+ let payload = null
92
+ try {
93
+ payload = JSON.parse(text)
94
+ } catch {
95
+ payload = text
96
+ }
97
+ return { status: response.status, payload }
98
+ }
99
+
100
+ /** A backup document v0.2, as this plugin and the plugin market both write it. */
101
+ export function backupDocument(profile = 'test', extraFiles = []) {
102
+ return {
103
+ format: 'dsh-profile-backup',
104
+ version: 0.2,
105
+ createdAt: '2026-01-01T00:00:00.000Z',
106
+ profile,
107
+ files: [
108
+ { path: 'package.json', json: { name: 'dsh-profile-test', dsh: { profile: { bundles: [] } } } },
109
+ ...extraFiles,
110
+ ],
111
+ }
112
+ }
113
+
114
+ /** The sole Gist id used in fixtures (not a user or repository secret). */
115
+ export const TEST_GIST_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'
116
+
117
+ /**
118
+ * Replace the GitHub HTTP layer with a recording stub.
119
+ *
120
+ * Anything that is not GitHub is either this check's own loopback server (which
121
+ * is passed through) or a host the plugin has no business contacting (which
122
+ * throws) — so a green run is also the plugin's privacy contract: nothing but
123
+ * api.github.com was reached. Returns the call log and a restore function.
124
+ */
125
+ export function stubGithub({ gistId = TEST_GIST_ID, document = null } = {}) {
126
+ const calls = []
127
+ const real = globalThis.fetch
128
+ const reply = (status, payload) => new Response(JSON.stringify(payload), {
129
+ status,
130
+ headers: { 'content-type': 'application/json' },
131
+ })
132
+ globalThis.fetch = async (input, init = {}) => {
133
+ const url = typeof input === 'string' ? input : input?.url ?? String(input)
134
+ if (url.startsWith('http://127.0.0.1:') || url.startsWith('http://localhost:')) return real(input, init)
135
+ if (!url.startsWith('https://api.github.com/')) {
136
+ throw new Error(`a request went to ${url}; only api.github.com is allowed`)
137
+ }
138
+ const method = (init.method ?? 'GET').toUpperCase()
139
+ const body = typeof init.body === 'string' ? JSON.parse(init.body) : null
140
+ // Header names are case-insensitive on the wire; record them lowercased so a
141
+ // check can look one up without guessing how the caller spelled it.
142
+ const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]))
143
+ calls.push({ method, path: url.replace('https://api.github.com', ''), body, headers })
144
+ if (method === 'POST' && url.endsWith('/gists')) {
145
+ return reply(201, { id: gistId, html_url: `https://gist.github.com/${gistId}`, updated_at: '2026-01-01T00:00:01Z', files: { 'dsh-profile-backup.json': {} } })
146
+ }
147
+ if (method === 'PATCH' && url.includes('/gists/')) {
148
+ return reply(200, { id: gistId, html_url: `https://gist.github.com/${gistId}`, updated_at: '2026-01-01T00:00:02Z', files: { 'dsh-profile-backup.json': {} } })
149
+ }
150
+ if (method === 'GET' && url.includes('/gists/')) {
151
+ return reply(200, {
152
+ id: gistId,
153
+ html_url: `https://gist.github.com/${gistId}`,
154
+ updated_at: '2026-01-01T00:00:02Z',
155
+ files: { 'dsh-profile-backup.json': { content: JSON.stringify(document ?? backupDocument()) } },
156
+ })
157
+ }
158
+ if (method === 'GET' && url.endsWith('/user')) return reply(200, { login: 'someone' })
159
+ return reply(404, { message: `not stubbed: ${method} ${url}` })
160
+ }
161
+ return { calls, restore: () => { globalThis.fetch = real } }
162
+ }
163
+
164
+ /** The pinned token a stubbed call must carry. */
165
+ export const TEST_TOKEN = 'gho_test_token_not_a_real_one'
166
+
167
+ /** Serve one registered route handler on an ephemeral loopback port. */
168
+ export async function serveHandler(handler) {
169
+ const { createServer } = await import('node:http')
170
+ const server = createServer((request, response) => handler(request, response))
171
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
172
+ return {
173
+ base: `http://127.0.0.1:${server.address().port}`,
174
+ close: () => server.close(),
175
+ }
176
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The backup document itself: what it carries, what it refuses, and what a
3
+ * restore would do — all on a throwaway profile built by the harness.
4
+ */
5
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { createReport, makeProfile, tempDir, useProfile, backupDocument } from './harness.mjs'
8
+
9
+ const { check, finish } = createReport('library')
10
+ const backup = await import('../lib/backup.js')
11
+
12
+ const home = tempDir('dpg-library-')
13
+ const profile = makeProfile(join(home, 'profiles', 'test'))
14
+ useProfile(profile, home)
15
+
16
+ // ---- what an export carries --------------------------------------------
17
+ const document = backup.exportBackup()
18
+ const paths = document.files.map(file => file.path)
19
+ check('the document declares the shared format and revision',
20
+ document.format === 'dsh-profile-backup' && document.version === 0.2 && backup.BACKUP_FILENAME === 'dsh-profile-backup.json',
21
+ `${document.format} v${document.version}`)
22
+ check('the manifest travels as an object, other files as text lines',
23
+ typeof document.files.find(file => file.path === 'package.json')?.json === 'object'
24
+ && Array.isArray(document.files.find(file => file.path === 'cordis.yml')?.lines))
25
+ check('configuration is carried', ['cordis.yml', 'cordis.patch.yml', '.npmrc', 'pnpm-workspace.yaml', 'data/note.json', 'suppliers/one.js']
26
+ .every(path => paths.includes(path)), paths.join(', '))
27
+ check('the credential store is never carried', !paths.includes('data/auths/credentials.sqlite'))
28
+ check('dependencies and the lockfile are never carried',
29
+ !paths.some(path => path.startsWith('node_modules/') || path === 'pnpm-lock.yaml'))
30
+ check('local usage counters are excluded by default', !paths.includes('data/usage.json'))
31
+ check('but travel when asked for', backup.exportBackup({ includeMachine: true }).files.map(file => file.path).includes('data/usage.json'))
32
+ check('the exclusions are reported, not silent',
33
+ backup.collectProfileFiles(profile).excluded.some(entry => entry.code === 'credential')
34
+ && backup.collectProfileFiles(profile).excluded.some(entry => entry.code === 'machine-state'))
35
+ check('the size helper agrees with the document', backup.backupBytes(document) > 0)
36
+
37
+ // ---- what a restore accepts and refuses --------------------------------
38
+ const validated = backup.validateBackup(document)
39
+ check('a document this plugin wrote validates', validated.files.length === document.files.length)
40
+ const refuse = (label, value, code) => {
41
+ let error = null
42
+ try {
43
+ backup.validateBackup(value)
44
+ } catch (caught) {
45
+ error = caught
46
+ }
47
+ check(label, error !== null && error.code === code, `${error?.code}: ${error?.message}`)
48
+ }
49
+ refuse('a foreign format is refused', { ...document, format: 'something-else' }, 'invalid')
50
+ refuse('a future revision is refused', { ...document, version: 9.9 }, 'invalid')
51
+ refuse('a path escape is refused', backupDocument('test', [{ path: '../outside.txt', lines: ['x'] }]), 'unsafe-path')
52
+ refuse('an absolute path is refused', backupDocument('test', [{ path: 'C:/outside.txt', lines: ['x'] }]), 'unsafe-path')
53
+ refuse('a dependency path is refused', backupDocument('test', [{ path: 'node_modules/dep/index.js', lines: ['x'] }]), 'unsafe-path')
54
+ refuse('a duplicate path is refused',
55
+ backupDocument('test', [{ path: 'a.txt', lines: ['x'] }, { path: 'a.txt', lines: ['y'] }]), 'invalid')
56
+ refuse('a document without a manifest is not a profile backup',
57
+ { format: backup.BACKUP_FORMAT, version: backup.BACKUP_VERSION, createdAt: 'x', profile: 'test', files: [{ path: 'a.txt', lines: ['x'] }] },
58
+ 'invalid')
59
+ const dropped = backup.validateBackup(backupDocument('test', [
60
+ { path: 'data/auths/credentials.sqlite', lines: ['secret'] },
61
+ { path: 'data/blob.bin', lines: ['\u0000binary'] },
62
+ ]))
63
+ check('a credential store inside an incoming document is dropped, not refused',
64
+ dropped.dropped.some(entry => entry.code === 'credential') && !dropped.files.some(file => file.path.includes('credentials')))
65
+
66
+ // ---- the restore plan ---------------------------------------------------
67
+ const incoming = backupDocument('other', [
68
+ { path: 'data/note.json', lines: ['{"hello":"from the cloud"}'] },
69
+ { path: 'data/fresh.json', lines: ['{"new":true}'] },
70
+ { path: '.npmrc', lines: readFileSync(join(profile, '.npmrc'), 'utf8').split('\n') },
71
+ ])
72
+ // A manifest from another machine: it adds a dependency and a bundle, and a
73
+ // merge must keep this machine's plugin as well.
74
+ incoming.files.find(file => file.path === 'package.json').json = {
75
+ name: 'dsh-profile-cloud',
76
+ dependencies: { 'cloud-plugin': '9.9.9' },
77
+ dsh: { profile: { bundles: ['cloud-bundle'] } },
78
+ }
79
+ const plan = backup.planRestore(incoming)
80
+ const status = Object.fromEntries(plan.files.map(file => [file.path, file.status]))
81
+ check('a file only the cloud has is an addition', status['data/fresh.json'] === 'add', JSON.stringify(status))
82
+ check('a file that differs is an overwrite', status['data/note.json'] === 'overwrite', JSON.stringify(status))
83
+ check('the local-only file is left out of the plan', status['cordis.yml'] === undefined, JSON.stringify(status))
84
+ check('a manifest that changes is a merge, not a replacement', status['package.json'] === 'merge', JSON.stringify(status))
85
+ check('and the plan says which dependency and bundle it adds',
86
+ plan.manifest.dependenciesAdded.includes('cloud-plugin') && plan.manifest.bundlesAdded.includes('cloud-bundle'),
87
+ JSON.stringify(plan.manifest))
88
+
89
+ // ---- applying and undoing ----------------------------------------------
90
+ const before = readFileSync(join(profile, 'data', 'note.json'), 'utf8')
91
+ const identicalPath = join(profile, '.npmrc')
92
+ const beforeInode = statSync(identicalPath).ino
93
+ const { report, undoDir } = backup.applyRestore(incoming)
94
+ check('the restore reports what it did', report.files.length === plan.files.length, JSON.stringify(report.counts))
95
+ check('the cloud content was written', readFileSync(join(profile, 'data', 'note.json'), 'utf8').includes('from the cloud'))
96
+ check('the new file appeared', existsSync(join(profile, 'data', 'fresh.json')))
97
+ check('the local-only file survived', existsSync(join(profile, 'cordis.yml')))
98
+ check('a manifest merge keeps the local plugin', readFileSync(join(profile, 'package.json'), 'utf8').includes('some-plugin'))
99
+ check('a manifest merge takes in the cloud plugin too', readFileSync(join(profile, 'package.json'), 'utf8').includes('cloud-plugin'))
100
+ check('the changed bytes were snapshotted first', existsSync(undoDir) && backup.undoStatus() !== null)
101
+ const snapshot = backup.undoStatus()
102
+ check('identical files are not replaced or included in the undo scope', status['.npmrc'] === 'identical'
103
+ && statSync(identicalPath).ino === beforeInode && !existsSync(join(undoDir, 'files', '.npmrc'))
104
+ && snapshot.files === plan.counts.add + plan.counts.overwrite + plan.counts.merge && report.restored === snapshot.files
105
+ && report.undoStamp === snapshot.stamp)
106
+ const repeat = backup.applyRestore(incoming)
107
+ check('an entirely unchanged restore creates no undo point, preserving the preceding real one',
108
+ repeat.report.restored === 0 && repeat.undoDir === null && repeat.report.undoStamp === null && backup.undoStatus().stamp === snapshot.stamp)
109
+ writeFileSync(identicalPath, 'registry=https://edited-later.invalid/\n')
110
+ const undone = backup.undoLastRestore()
111
+ check('undo leaves later edits to a previously identical file alone', readFileSync(identicalPath, 'utf8') === 'registry=https://edited-later.invalid/\n')
112
+ check('undo reports the files it reverted', undone.reverted > 0, JSON.stringify(undone))
113
+ check('undo restored the previous bytes', readFileSync(join(profile, 'data', 'note.json'), 'utf8') === before)
114
+ check('undo removed the added file', !existsSync(join(profile, 'data', 'fresh.json')))
115
+ check('and there is nothing left to undo', backup.undoStatus() === null)
116
+
117
+ // ---- exports the agent tool hands out ----------------------------------
118
+ const exported = backup.writeExportFile(document, 'named-export.json')
119
+ check('an export file is written inside the profile work directory',
120
+ exported === join(profile, backup.WORK_DIR, 'exports', 'named-export.json') && existsSync(exported), exported)
121
+ let escaped = null
122
+ try {
123
+ backup.writeExportFile(document, '../escape.json')
124
+ } catch (error) {
125
+ escaped = error
126
+ }
127
+ check('an export name cannot escape the folder', escaped?.code === 'unsafe-path', escaped?.message)
128
+ check('the fork has its own work directory, which is never exported',
129
+ backup.WORK_DIR === '.dsh-config-sync-plus' && !backup.exportBackup().files.some(file => file.path.startsWith(backup.WORK_DIR + '/')))
130
+ check('a backup read from disk round-trips', backup.readBackupFile(exported).files.length === document.files.length)
131
+
132
+ // ---- profile resolution, without any environment ------------------------
133
+ const single = tempDir('dpg-single-')
134
+ makeProfile(join(single, 'profiles', 'only-one'))
135
+ delete process.env.DSH_PROFILE_DIR
136
+ delete process.env.DSH_PROFILE
137
+ process.env.DSH_HOME = single
138
+ backup.rememberProfile(null)
139
+ check('a lone profile is used when nothing identifies one',
140
+ backup.profileRoot() === join(single, 'profiles', 'only-one') && backup.profileSource() === 'the only profile present',
141
+ `${backup.profileRoot()} (${backup.profileSource()})`)
142
+ const originalOnly = makeProfile(join(single, 'profiles', 'upstream-only'))
143
+ mkdirSync(join(originalOnly, 'node_modules', 'dsh-profile-gist-sync'))
144
+ let unresolved = null
145
+ try { backup.profileRoot() } catch (error) { unresolved = error }
146
+ check('an ambiguous profile is not selected just because upstream is installed', unresolved?.code === 'no-profile', unresolved?.message)
147
+ const plusOnly = join(single, 'profiles', 'only-one')
148
+ mkdirSync(join(plusOnly, 'node_modules', 'dsh-multi-device-config-sync'))
149
+ writeFileSync(join(plusOnly, 'node_modules', 'dsh-multi-device-config-sync', 'package.json'), JSON.stringify({ name: 'dsh-multi-device-config-sync', version: '1.5.0' }))
150
+ check('the npm installation resolves its own profile', backup.profileRoot() === plusOnly, backup.profileRoot())
151
+ backup.rememberProfile({ name: 'reported', dir: profile })
152
+ check('what the host reports wins over everything else',
153
+ backup.profileRoot() === profile && backup.profileSource() === 'host', backup.profileSource())
154
+ backup.rememberProfile({ name: '', dir: 'C:\\no\\such\\directory' })
155
+ check('an unusable host report is ignored rather than trusted', backup.profileSource() !== 'host', backup.profileSource())
156
+ backup.rememberProfile(null)
157
+ process.env.DSH_PROFILE_DIR = join(single, 'no-such-profile')
158
+ delete process.env.DSH_HOME
159
+ check('an explicitly configured directory is taken as given',
160
+ backup.profileRoot() === join(single, 'no-such-profile'), backup.profileRoot())
161
+ let missing = null
162
+ try {
163
+ backup.exportBackup()
164
+ } catch (error) {
165
+ missing = error
166
+ }
167
+ check('and a missing one fails loudly', missing?.code === 'no-profile', missing?.message)
168
+
169
+ process.exit(finish())
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The published package, not the working copy.
3
+ *
4
+ * In this repository the plugin is developed in place, so a file the manifest
5
+ * forgets to ship is still present and everything looks fine. A user gets only
6
+ * what `files` allows. This check packs the package the way a registry would,
7
+ * unpacks it somewhere else, and runs the plugin from THAT tree — then asserts
8
+ * the package carries no author-specific state.
9
+ *
10
+ * Without npm or pnpm, stage the same files in a temporary directory.
11
+ */
12
+ import { execFileSync, spawnSync } from 'node:child_process'
13
+ import { cpSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'
14
+ import { dirname, join } from 'node:path'
15
+ import { fileURLToPath, pathToFileURL } from 'node:url'
16
+ import { createReport, makeProfile, tempDir, useProfile, callRoute, serveHandler, TEST_GIST_ID } from './harness.mjs'
17
+
18
+ const { check, finish } = createReport('package')
19
+
20
+ const PLUGIN = fileURLToPath(new URL('..', import.meta.url))
21
+ const manifest = JSON.parse(readFileSync(join(PLUGIN, 'package.json'), 'utf8'))
22
+ const workspace = tempDir('dpg-pack-')
23
+ const packDir = join(workspace, 'pack')
24
+ const installed = join(workspace, 'installed')
25
+ mkdirSync(packDir, { recursive: true })
26
+ mkdirSync(installed, { recursive: true })
27
+
28
+ /**
29
+ * A tarball when this machine has npm or pnpm, otherwise a staged copy built
30
+ * from the manifest's own `files` list. The fallback proves the same thing the
31
+ * tarball does — that nothing the runtime needs is missing from `files` — and
32
+ * keeps the check useful on a machine with no package manager at all.
33
+ */
34
+ function pack() {
35
+ const commands = process.platform === 'win32' ? ['npm.cmd', 'pnpm.cmd'] : ['npm', 'pnpm']
36
+ const env = {
37
+ ...process.env, HOME: workspace, USERPROFILE: workspace,
38
+ npm_config_userconfig: join(workspace, 'empty.npmrc'), npm_config_cache: join(workspace, 'cache'),
39
+ npm_config_offline: 'true', npm_config_ignore_scripts: 'true', COREPACK_ENABLE_NETWORK: '0',
40
+ }
41
+ for (const command of commands) {
42
+ try {
43
+ execFileSync(command, ['pack', '--pack-destination', packDir], { cwd: PLUGIN, env, stdio: ['ignore', 'pipe', 'pipe'] })
44
+ } catch (error) {
45
+ if (error.code === 'ENOENT' || (process.platform === 'win32' && error.code === 'EINVAL')) continue
46
+ throw error // An available packager failing must not pass as a staged-copy success.
47
+ }
48
+ const tarballs = readdirSync(packDir).filter(name => name.endsWith('.tgz'))
49
+ if (tarballs.length !== 1) throw new Error(`expected one tarball, got ${tarballs.length}`)
50
+ const tarball = join(packDir, tarballs[0])
51
+ execFileSync('tar', ['-xzf', tarball, '-C', installed, '--strip-components=1'], { stdio: ['ignore', 'pipe', 'pipe'] })
52
+ return { mode: 'tarball', by: command, size: statSync(tarball).size }
53
+ }
54
+ // Without a packager, expand the simple directory/*.ext patterns used by
55
+ // this manifest. package.json is included automatically in a real pack.
56
+ for (const entry of ['package.json', ...(manifest.files ?? [])]) {
57
+ const [directory, pattern] = entry.split('/')
58
+ const paths = pattern?.startsWith('*.')
59
+ ? readdirSync(join(PLUGIN, directory)).filter(name => name.endsWith(pattern.slice(1))).map(name => join(directory, name))
60
+ : [entry]
61
+ for (const relative of paths) {
62
+ const target = join(installed, relative)
63
+ mkdirSync(dirname(target), { recursive: true })
64
+ cpSync(join(PLUGIN, relative), target, { recursive: true })
65
+ }
66
+ }
67
+ return { mode: 'manifest', by: 'the files list', size: null }
68
+ }
69
+
70
+ const packed = pack()
71
+ check(packed.mode === 'tarball'
72
+ ? `the package can be packed (${packed.by})`
73
+ : `the manifest's files list only (no package manager; staged ${packed.by})`, true)
74
+
75
+ const listing = (dir, prefix = '') => readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
76
+ entry.isDirectory() ? listing(join(dir, entry.name), `${prefix}${entry.name}/`) : [`${prefix}${entry.name}`])
77
+ const shipped = listing(installed)
78
+
79
+ // ---- everything the runtime needs is inside the tarball ----------------
80
+ check('the host entry is shipped', shipped.includes('index.js'))
81
+ check('every lib module is shipped',
82
+ readdirSync(join(PLUGIN, 'lib')).filter(name => name.endsWith('.js')).every(name => shipped.includes(`lib/${name}`)),
83
+ shipped.filter(file => file.startsWith('lib/')).join(', '))
84
+ check('the client half is shipped', shipped.includes('client.js'))
85
+ check('the bundle patch is shipped', shipped.includes('cordis.patch.yml'))
86
+ const packedManifest = JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8'))
87
+ check('the tarball identifies the public npm release and its source repository',
88
+ packedManifest.name === 'dsh-multi-device-config-sync' && packedManifest.version === '1.5.0'
89
+ && packedManifest.publishConfig.access === 'public' && packedManifest.publishConfig.registry === 'https://registry.npmjs.org/'
90
+ && packedManifest.repository.url === 'git+https://github.com/Xeonice/dsh-profile-gist-sync-plus.git')
91
+ check('installing the public bundle introduces no dependencies and runs no lifecycle scripts',
92
+ ['dependencies', 'optionalDependencies', 'peerDependencies'].every(key => Object.keys(packedManifest[key] ?? {}).length === 0)
93
+ && Object.keys(packedManifest.scripts ?? {}).every(hook => hook === 'test'))
94
+ const patch = readFileSync(join(installed, 'cordis.patch.yml'), 'utf8')
95
+ check('the stable Cordis row loads the renamed npm package (not the old Git module)',
96
+ /^\s*- id: dsh-profile-gist-sync-plus$/m.test(patch) && /^\s*name: dsh-multi-device-config-sync$/m.test(patch))
97
+ check('both packaged plugin titles and help text use the localized display name',
98
+ [['zh', '多端配置同步'], ['en', 'Multi-device config sync']].every(([lang, title]) => {
99
+ const copy = JSON.parse(readFileSync(join(installed, 'locale', `${lang}.json`), 'utf8'))
100
+ return [copy.meta.title, copy.title, copy.tab].every(value => value === title)
101
+ && copy.meta.description.includes('Gist') && copy.meta.description.includes(title) && copy.newMachineStep1.includes(title)
102
+ }))
103
+ check('both icon forms and the README are shipped', ['icon.svg', 'assets/icon-256.png', 'README.md'].every(file => shipped.includes(file)))
104
+ check('the tarball does not advertise or include upstream screenshots', !shipped.some(file => /screenshot/i.test(file)))
105
+ check('the original author and MIT licence travel with it', packedManifest.author === 'Meta-Virgo' && packedManifest.license === 'MIT'
106
+ && readFileSync(join(installed, 'LICENSE'), 'utf8').includes('Copyright (c) 2026 Meta-Virgo'))
107
+ check('the checks travel with it, so a reader can run them', shipped.some(file => file.startsWith('test/')))
108
+ if (packed.size !== null) check(`the tarball is below 200 KiB (${packed.size} bytes)`, packed.size < 200 * 1024)
109
+ check('no working state leaked into the package',
110
+ !shipped.some(file => file.includes('.dsh-config-sync') || file.includes('node_modules') || file.endsWith('settings.json')),
111
+ shipped.join(', '))
112
+
113
+ // ---- the packed copy actually runs -------------------------------------
114
+ const root = pathToFileURL(installed).href
115
+ const { apply } = await import(`${root}/index.js`)
116
+ const { BASE_PATH } = await import(`${root}/lib/routes.js`)
117
+ const home = tempDir('dpg-pack-profile-')
118
+ const profile = makeProfile(join(home, 'profiles', 'test'))
119
+ useProfile(profile, home)
120
+ let handler = null
121
+ const seen = { routes: 0, tools: 0 }
122
+ const ctx = {
123
+ get(name) {
124
+ if (name === 'webServer') return { register: (route) => { handler = route.handler; seen.routes += 1; return () => {} } }
125
+ if (name === 'tools') return { register: () => { seen.tools += 1; return () => {} } }
126
+ return undefined
127
+ },
128
+ effect(fn) {
129
+ const dispose = fn()
130
+ if (typeof dispose !== 'function') throw new Error('Invalid effect')
131
+ return dispose
132
+ },
133
+ }
134
+ let applyError = null
135
+ try {
136
+ apply(ctx)
137
+ } catch (error) {
138
+ applyError = error
139
+ }
140
+ check('the packed host half activates', applyError === null, applyError?.message)
141
+ check('and registers its route and tool', seen.routes === 1 && seen.tools === 1, `routes=${seen.routes} tools=${seen.tools}`)
142
+ const served = await serveHandler(handler)
143
+ const status = await callRoute(served.base, `${BASE_PATH}/api/status`)
144
+ check('the packed copy answers its own status route',
145
+ status.status === 200 && status.payload.profile === 'test' && status.payload.version === packedManifest.version,
146
+ `${status.status}, profile ${status.payload.profile}, version ${status.payload.version}`)
147
+ served.close()
148
+
149
+ // Resolve and execute ./client from the unpacked package, not the working tree.
150
+ const packedClient = spawnSync(process.execPath, ['test/client-registration.test.mjs'], { cwd: installed, encoding: 'utf8' })
151
+ check('the packed client registers its own localized Settings section with no API calls',
152
+ packedClient.status === 0, `${packedClient.stdout ?? ''}${packedClient.stderr || packedClient.error || ''}`)
153
+
154
+ // ---- nothing about the author travels ----------------------------------
155
+ // The checks themselves use invented ids, so those are excluded by name: a real
156
+ // Gist id or a personal path appearing anywhere in the package is a leak.
157
+ const text = shipped.map(file => readFileSync(join(installed, file), 'utf8')).join('\n')
158
+ const leaks = (text.match(/[A-Za-z]:\\\\?Users\\\\?[^"'\s]+|gho_[A-Za-z0-9]{20,}|\b[0-9a-f]{32}\b/g) ?? [])
159
+ .filter(value => value !== TEST_GIST_ID)
160
+ check('no personal path, token, or Gist id is baked into the package', leaks.length === 0, leaks.slice(0, 3).join(', '))
161
+
162
+ process.exit(finish())