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/LICENSE +21 -0
- package/README.md +97 -2
- package/assets/icon-256.png +0 -0
- package/client.js +1334 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +19 -0
- package/index.js +52 -0
- package/lib/backup.js +1087 -0
- package/lib/errors.js +67 -0
- package/lib/gist.js +343 -0
- package/lib/plugins.js +469 -0
- package/lib/routes.js +438 -0
- package/lib/store.js +73 -0
- package/lib/sync-install.js +201 -0
- package/lib/tool.js +191 -0
- package/locale/en.json +24 -0
- package/locale/zh.json +24 -0
- package/package.json +66 -4
- package/test/activation.test.mjs +141 -0
- package/test/client-decisions.test.mjs +55 -0
- package/test/client-registration.test.mjs +98 -0
- package/test/config-preview.test.mjs +454 -0
- package/test/first-run.test.mjs +104 -0
- package/test/harness.mjs +176 -0
- package/test/library.test.mjs +169 -0
- package/test/package.test.mjs +162 -0
- package/test/plugins.test.mjs +543 -0
- package/test/rename-compat.test.mjs +255 -0
- package/test/run.mjs +32 -0
- package/test/sync-install.test.mjs +338 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Reviewed restore snapshots. Only the combined cloud flow can confirm an installation. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { applyRestore, backupForRestore, existingBackupFile, planRestore, profileRoot } from './backup.js'
|
|
6
|
+
import { ConfigSyncError } from './errors.js'
|
|
7
|
+
import { declarationsFromManifest, installMissingPlugins, pluginInventory, validPackageName } from './plugins.js'
|
|
8
|
+
import { writeSettings } from './store.js'
|
|
9
|
+
|
|
10
|
+
const PLAN_TTL_MS = 5 * 60_000
|
|
11
|
+
const stale = () => new ConfigSyncError('This preview expired or the local state changed. Preview the restore again.', 'stale-plan')
|
|
12
|
+
const busyError = () => new ConfigSyncError('Another restore or installation is running.', 'busy')
|
|
13
|
+
|
|
14
|
+
// Standard DSH state plus additional plugins' ordinary text configuration. Do
|
|
15
|
+
// not bring across package-manager policy, env files or unmanaged executables.
|
|
16
|
+
function isConfiguration(path) {
|
|
17
|
+
const basename = path.split('/').at(-1).toLowerCase()
|
|
18
|
+
if (basename.startsWith('.') || /^(?:package(?:-lock)?\.json|npm-shrinkwrap\.json|pnpm-workspace\.ya?ml|pnpmfile\..+|yarn\.lock)$/.test(basename)) return false
|
|
19
|
+
return /^(?:data|suppliers|config|presets)\//.test(path) || /\.(?:ya?ml|jsonc?|toml|ini|conf|cfg|xml|md|txt)$/i.test(path)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The installer must run under THIS machine's package-manager policy. In
|
|
24
|
+
* particular, writing all incoming deps first would let the first pnpm add
|
|
25
|
+
* resolve every spec, including ones the preview marked unresolvable. Give
|
|
26
|
+
* DSH each approved dependency individually; keep the local manifest's other
|
|
27
|
+
* fields and apply only the portable bundle selection from the remote manifest.
|
|
28
|
+
* Config-only restore remains the upstream full-profile operation.
|
|
29
|
+
*/
|
|
30
|
+
function portableConfiguration(source) {
|
|
31
|
+
// Filter before deriving either bundle selections or the install allowlist.
|
|
32
|
+
const backup = backupForRestore(source)
|
|
33
|
+
const incoming = backup.files.find(file => file.path === 'package.json').json
|
|
34
|
+
const declarations = declarationsFromManifest(incoming)
|
|
35
|
+
const wanted = declarations.filter(row => row.kind !== 'dependency' && validPackageName(row.name)).map(row => row.name)
|
|
36
|
+
const dropped = [...(backup.dropped ?? [])]
|
|
37
|
+
const files = []
|
|
38
|
+
for (const file of backup.files) {
|
|
39
|
+
if (file.path === 'package.json') {
|
|
40
|
+
files.push({ path: file.path, json: { dsh: { profile: { bundles: wanted } } } })
|
|
41
|
+
} else if (isConfiguration(file.path)) {
|
|
42
|
+
files.push(file)
|
|
43
|
+
} else {
|
|
44
|
+
// Root dotfiles (including .npmrc), pnpm workspace policy/hooks and other
|
|
45
|
+
// unmanaged profile files stay local instead of affecting this install.
|
|
46
|
+
dropped.push({ path: file.path, code: 'local-policy' })
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { config: { ...backup, files, dropped, droppedEntries: dropped.length }, declarations, wanted }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Bind consent to the profile and every target's bytes (or absence). Only an install plan also binds a missing list. */
|
|
53
|
+
function fingerprint(config, plugins) {
|
|
54
|
+
const root = profileRoot()
|
|
55
|
+
const hash = createHash('sha256').update(root)
|
|
56
|
+
for (const file of config.files) {
|
|
57
|
+
const bytes = existingBackupFile(root, file.path)
|
|
58
|
+
const digest = bytes === null ? null : createHash('sha256').update(bytes).digest('hex')
|
|
59
|
+
hash.update(JSON.stringify([file.path, digest]))
|
|
60
|
+
}
|
|
61
|
+
if (plugins) hash.update(JSON.stringify([plugins.available, plugins.missing?.map(p => [p.name, p.installSpec, p.note])]))
|
|
62
|
+
return hash.digest('hex')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** applyRestore revalidates retained files; preserve the omissions the user actually reviewed. */
|
|
66
|
+
function restoreValidatedFiles(config) {
|
|
67
|
+
const { report } = applyRestore(config)
|
|
68
|
+
// Revalidation sees only retained files. Keep prior file/policy omissions
|
|
69
|
+
// as well as any self declarations filtered by the full-profile restore.
|
|
70
|
+
report.dropped = [...(config.dropped ?? []), ...report.dropped]
|
|
71
|
+
report.droppedEntries = report.dropped.length
|
|
72
|
+
return report
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Recording cloud history is not part of committing the files. Local imports never call this. */
|
|
76
|
+
export function restoreGistConfiguration(ref, config, { bindUploadTarget = false } = {}) {
|
|
77
|
+
const report = restoreValidatedFiles(config)
|
|
78
|
+
const warnings = []
|
|
79
|
+
try {
|
|
80
|
+
// Reviewing a restore source is not consent to use it for future uploads.
|
|
81
|
+
// Only the legacy one-call /sync route also remembers it as the target.
|
|
82
|
+
writeSettings({
|
|
83
|
+
...(bindUploadTarget ? { gistId: ref.id } : {}),
|
|
84
|
+
lastSync: { gistId: ref.id, at: new Date().toISOString(), files: report.restored, counts: report.counts, source: 'gist', remoteUpdatedAt: ref.updatedAt ?? null },
|
|
85
|
+
})
|
|
86
|
+
} catch (error) {
|
|
87
|
+
warnings.push(`Configuration restored, but sync history could not be saved: ${error.message}`)
|
|
88
|
+
}
|
|
89
|
+
const { add, overwrite, merge } = report.counts
|
|
90
|
+
return { ref, report, warnings, restart: add + overwrite + merge > 0 }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** One expiring, one-use in-memory snapshot for one mode. Other modes cannot take its plan ID. */
|
|
94
|
+
function createPlanSlot() {
|
|
95
|
+
let pending = null
|
|
96
|
+
let expiry = null
|
|
97
|
+
function clear() { pending = null; clearTimeout(expiry); expiry = null }
|
|
98
|
+
return {
|
|
99
|
+
clear,
|
|
100
|
+
save(snapshot) {
|
|
101
|
+
clear()
|
|
102
|
+
const planId = randomUUID()
|
|
103
|
+
pending = { ...snapshot, planId, endsAt: Date.now() + PLAN_TTL_MS }
|
|
104
|
+
expiry = setTimeout(clear, PLAN_TTL_MS)
|
|
105
|
+
expiry.unref?.()
|
|
106
|
+
return planId
|
|
107
|
+
},
|
|
108
|
+
take(planId) {
|
|
109
|
+
if (!pending || pending.planId !== planId) throw stale()
|
|
110
|
+
const plan = pending
|
|
111
|
+
clear() // consume before any await or write, including an attempt that later fails
|
|
112
|
+
if (Date.now() >= plan.endsAt) throw stale()
|
|
113
|
+
return plan
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The three review modes have independent plan slots and share this route registration’s single writer. */
|
|
119
|
+
export function createRestoreSession(ctx) {
|
|
120
|
+
const combined = createPlanSlot()
|
|
121
|
+
const configOnly = createPlanSlot()
|
|
122
|
+
const local = createPlanSlot()
|
|
123
|
+
let busy = false
|
|
124
|
+
let disposed = false
|
|
125
|
+
function requireIdle() { if (busy || disposed) throw busyError() }
|
|
126
|
+
function verify(plan, plugins) {
|
|
127
|
+
if (disposed || fingerprint(plan.config, plugins) !== plan.digest || Date.now() >= plan.endsAt) throw stale()
|
|
128
|
+
}
|
|
129
|
+
// Full configuration review, with no package-manager filtering or inventory.
|
|
130
|
+
// Only a cloud slot needs source metadata; neither slot retains a token.
|
|
131
|
+
function previewFiles(slot, config, source) {
|
|
132
|
+
requireIdle()
|
|
133
|
+
const digest = fingerprint(config)
|
|
134
|
+
const preview = planRestore(config)
|
|
135
|
+
const planId = slot.save({ config, digest, ...source })
|
|
136
|
+
return { planId, preview }
|
|
137
|
+
}
|
|
138
|
+
function takeFiles(slot, planId, confirm) {
|
|
139
|
+
if (confirm !== true) throw new ConfigSyncError('Review the plan and explicitly confirm the configuration restore.', 'invalid')
|
|
140
|
+
const plan = slot.take(planId)
|
|
141
|
+
verify(plan)
|
|
142
|
+
return plan
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
dispose() { disposed = true; combined.clear(); configOnly.clear(); local.clear() },
|
|
146
|
+
lock() {
|
|
147
|
+
requireIdle()
|
|
148
|
+
busy = true
|
|
149
|
+
return () => { busy = false }
|
|
150
|
+
},
|
|
151
|
+
previewConfig(ref, backup) { return { ...previewFiles(configOnly, backup, { ref }), ref } },
|
|
152
|
+
confirmConfig(planId, confirm) {
|
|
153
|
+
const plan = takeFiles(configOnly, planId, confirm)
|
|
154
|
+
return restoreGistConfiguration(plan.ref, plan.config)
|
|
155
|
+
},
|
|
156
|
+
previewLocal(backup) { return previewFiles(local, backup) },
|
|
157
|
+
confirmLocal(planId, confirm) {
|
|
158
|
+
const plan = takeFiles(local, planId, confirm)
|
|
159
|
+
return { report: restoreValidatedFiles(plan.config) }
|
|
160
|
+
},
|
|
161
|
+
async preview(ref, backup) {
|
|
162
|
+
requireIdle()
|
|
163
|
+
const { config, declarations, wanted } = portableConfiguration(backup)
|
|
164
|
+
const plugins = await pluginInventory(ctx, declarations)
|
|
165
|
+
requireIdle()
|
|
166
|
+
const preview = planRestore(config)
|
|
167
|
+
if (!plugins.available) {
|
|
168
|
+
combined.clear()
|
|
169
|
+
return { planId: null, ref, preview, plugins }
|
|
170
|
+
}
|
|
171
|
+
const planId = combined.save({ ref, config, declarations, wanted, digest: fingerprint(config, plugins) })
|
|
172
|
+
return { planId, ref, preview, plugins }
|
|
173
|
+
},
|
|
174
|
+
async confirm(planId, confirm) {
|
|
175
|
+
if (confirm !== true) throw new ConfigSyncError('Review the plan and explicitly confirm the restore and installation.', 'invalid')
|
|
176
|
+
const plan = combined.take(planId)
|
|
177
|
+
const { ref, config, declarations, wanted } = plan
|
|
178
|
+
const pluginsBefore = await pluginInventory(ctx, declarations)
|
|
179
|
+
if (!pluginsBefore.available) throw stale()
|
|
180
|
+
verify(plan, pluginsBefore)
|
|
181
|
+
const approved = new Map(pluginsBefore.missing.filter(row => row.resolvable).map(row => [row.name, row.installSpec]))
|
|
182
|
+
const current = JSON.parse(readFileSync(join(profileRoot(), 'package.json'), 'utf8'))
|
|
183
|
+
const localBundles = current?.dsh?.profile?.bundles
|
|
184
|
+
const selected = new Set([...(Array.isArray(localBundles) ? localBundles : []), ...wanted])
|
|
185
|
+
const restored = restoreGistConfiguration(ref, config) // if writing fails, do not start an installation
|
|
186
|
+
let plugins
|
|
187
|
+
try {
|
|
188
|
+
plugins = await installMissingPlugins(ctx, { declarations, approved, selected })
|
|
189
|
+
} catch (error) {
|
|
190
|
+
// The configuration is already on disk and can be undone. Never report
|
|
191
|
+
// an installer/inventory error as if the restore had not happened.
|
|
192
|
+
restored.warnings.push(String(error.message ?? error))
|
|
193
|
+
plugins = { available: false, reason: 'plugin-manager-error', results: [], restart: false }
|
|
194
|
+
}
|
|
195
|
+
const restart = restored.restart || plugins.results.some(row => row.application === 'restart-required')
|
|
196
|
+
const complete = plugins.available && plugins.counts?.missing === 0 && plugins.results.every(row =>
|
|
197
|
+
(row.outcome === 'installed' || row.outcome === 'already-present') && row.pendingBuilds.length === 0)
|
|
198
|
+
return { ...restored, plugins, restart, complete: complete === true }
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
}
|
package/lib/tool.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `config_backup_plus` shares the page's configuration-only backup operations.
|
|
3
|
+
* Confirming a combined restore and package installation is a user action on
|
|
4
|
+
* the page, not a tool action.
|
|
5
|
+
*
|
|
6
|
+
* File actions are scoped to local backup paths:
|
|
7
|
+
* - `export` writes inside this plugin's own directory in the profile.
|
|
8
|
+
* - `restore` reads a file only from inside the DSH home directory; importing an
|
|
9
|
+
* arbitrary path stays a user action on the settings page.
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
applyRestore, backupBytes, collectProfileFiles, exportBackupWithReport, planRestore, profileName, profileRoot,
|
|
13
|
+
profileSource, readBackupFile, undoLastRestore, undoStatus, writeExportFile,
|
|
14
|
+
} from './backup.js'
|
|
15
|
+
import { createGist, parseGistId, readGist, resolveTokenSource, updateGist } from './gist.js'
|
|
16
|
+
import { ConfigSyncError } from './errors.js'
|
|
17
|
+
import { readSettings, writeSettings } from './store.js'
|
|
18
|
+
|
|
19
|
+
/** Actions this tool accepts. */
|
|
20
|
+
const ACTIONS = ['status', 'export', 'gist_upload', 'gist_read', 'restore', 'undo']
|
|
21
|
+
|
|
22
|
+
/** Tool definition handed to the host's tool registry. */
|
|
23
|
+
const DEFINITION = {
|
|
24
|
+
name: 'config_backup_plus',
|
|
25
|
+
description: [
|
|
26
|
+
'Back up or restore this DSH profile using Multi-device config sync.',
|
|
27
|
+
'status lists backup scope; export writes a local JSON; gist_upload updates or creates an unlisted (not private) Gist.',
|
|
28
|
+
'gist_read and restore preview configuration changes by default. Use only trusted backups; review text files for secrets before upload.',
|
|
29
|
+
'undo reverts configuration, not installed packages. This tool never installs plugins or approves builds; open Settings → Multi-device config sync to review and confirm a combined restore.',
|
|
30
|
+
].join(' '),
|
|
31
|
+
parameters: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
additionalProperties: false,
|
|
34
|
+
properties: {
|
|
35
|
+
action: { type: 'string', enum: ACTIONS, description: 'What to do.' },
|
|
36
|
+
gistId: {
|
|
37
|
+
type: 'string',
|
|
38
|
+
description: 'Gist id or gist.github.com link. Omit to use the Gist this profile remembers, or, on the first gist_upload, to create one.',
|
|
39
|
+
},
|
|
40
|
+
path: {
|
|
41
|
+
type: 'string',
|
|
42
|
+
description: 'export: optional file name inside the export folder. restore: a backup file path inside the DSH home directory. Ignored otherwise.',
|
|
43
|
+
},
|
|
44
|
+
token: {
|
|
45
|
+
type: 'string',
|
|
46
|
+
description: 'Optional GitHub token for this call. Prefer the host’s DSH_GITHUB_TOKEN/GITHUB_TOKEN or signed-in gh CLI to keep tokens out of chat and tool logs.',
|
|
47
|
+
},
|
|
48
|
+
includeMachine: {
|
|
49
|
+
type: 'boolean',
|
|
50
|
+
description: "Also carry this machine's local usage counters (data/usage.json). Default false.",
|
|
51
|
+
},
|
|
52
|
+
apply: {
|
|
53
|
+
type: 'boolean',
|
|
54
|
+
description: 'For gist_read and restore: true writes configuration files only. Omit for a read-only plan. Never installs packages.',
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
required: ['action'],
|
|
58
|
+
},
|
|
59
|
+
output: {
|
|
60
|
+
schema: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
properties: {
|
|
64
|
+
summary: { type: 'string', description: 'Human-readable result.' },
|
|
65
|
+
},
|
|
66
|
+
required: ['summary'],
|
|
67
|
+
},
|
|
68
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.summary ?? '') }],
|
|
69
|
+
},
|
|
70
|
+
async execute(args) {
|
|
71
|
+
const action = String(args?.action ?? '')
|
|
72
|
+
if (!ACTIONS.includes(action)) throw new ConfigSyncError(`unknown action: ${action}`, 'invalid')
|
|
73
|
+
const includeMachine = args?.includeMachine === true
|
|
74
|
+
if (action === 'status') return { summary: statusText() }
|
|
75
|
+
if (action === 'export') {
|
|
76
|
+
const { backup } = exportBackupWithReport({ includeMachine })
|
|
77
|
+
const target = writeExportFile(backup, args?.path === undefined ? undefined : String(args.path))
|
|
78
|
+
return { summary: `Wrote ${backup.files.length} files to ${target}. Read it from there; the backup body is not echoed here.` }
|
|
79
|
+
}
|
|
80
|
+
if (action === 'gist_upload') {
|
|
81
|
+
const resolved = await resolveTokenSource(args?.token)
|
|
82
|
+
const { backup, dropped, droppedEntries } = exportBackupWithReport({ includeMachine })
|
|
83
|
+
const content = `${JSON.stringify(backup, null, 2)}\n`
|
|
84
|
+
// No id given means "the cloud copy this profile already uses"; only a
|
|
85
|
+
// profile that has none gets a new Gist.
|
|
86
|
+
const rawId = args?.gistId === undefined ? '' : String(args.gistId).trim()
|
|
87
|
+
const id = rawId === '' ? readSettings().gistId : parseGistId(rawId)
|
|
88
|
+
const ref = id === null
|
|
89
|
+
? await createGist(resolved.token, content)
|
|
90
|
+
: await updateGist(resolved.token, id, content)
|
|
91
|
+
writeSettings({
|
|
92
|
+
gistId: ref.id,
|
|
93
|
+
lastUpload: { gistId: ref.id, at: new Date().toISOString(), files: backup.files.length, bytes: Buffer.byteLength(content), created: id === null, tokenSource: resolved.source },
|
|
94
|
+
})
|
|
95
|
+
return {
|
|
96
|
+
summary: [
|
|
97
|
+
`${id === null ? 'Created' : 'Updated'} a secret Gist with ${backup.files.length} files (${Buffer.byteLength(content)} bytes).`,
|
|
98
|
+
`id: ${ref.id}`,
|
|
99
|
+
`link: ${ref.htmlUrl}`,
|
|
100
|
+
`token source: ${resolved.source}.`,
|
|
101
|
+
droppedEntries === 0
|
|
102
|
+
? 'No machine-local dependency was omitted from the export.'
|
|
103
|
+
: `Left out ${droppedEntries} machine-local ${droppedEntries === 1 ? 'dependency' : 'dependencies'}, so the other machine does not inherit a path from this one: ${dropped.map(entry => `${entry.name} (${entry.spec}${entry.version === null ? '' : `, ${entry.package ?? entry.name}@${entry.version}`})`).join(', ')}. A later restore there keeps whatever it already has for them.`,
|
|
104
|
+
'Note: a secret Gist is unlisted, not private — anyone with the link can read it, so do not post it publicly.',
|
|
105
|
+
].join('\n'),
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (action === 'gist_read' || action === 'restore') {
|
|
109
|
+
const rawId = args?.gistId === undefined ? '' : String(args.gistId).trim()
|
|
110
|
+
const rawPath = args?.path === undefined ? '' : String(args.path).trim()
|
|
111
|
+
let backup
|
|
112
|
+
let origin
|
|
113
|
+
if (rawId !== '' || (rawPath === '' && readSettings().gistId !== null)) {
|
|
114
|
+
// An explicit id wins; otherwise the remembered cloud copy is used, so
|
|
115
|
+
// the common case ("sync my configuration") needs no id at all.
|
|
116
|
+
const resolved = await resolveTokenSource(args?.token)
|
|
117
|
+
const target = rawId === '' ? readSettings().gistId : parseGistId(rawId)
|
|
118
|
+
const read = await readGist(resolved.token, target)
|
|
119
|
+
backup = read.backup
|
|
120
|
+
origin = `Gist ${read.ref.id}`
|
|
121
|
+
} else if (rawPath !== '') {
|
|
122
|
+
backup = readBackupFile(rawPath)
|
|
123
|
+
origin = rawPath
|
|
124
|
+
} else {
|
|
125
|
+
throw new ConfigSyncError('gistId or path is required for this action', 'invalid')
|
|
126
|
+
}
|
|
127
|
+
const plan = planRestore(backup)
|
|
128
|
+
if (args?.apply !== true) return { summary: `${planText(plan, origin)}\nNothing was written: pass apply: true to restore.` }
|
|
129
|
+
const { report } = applyRestore(backup)
|
|
130
|
+
return {
|
|
131
|
+
summary: [
|
|
132
|
+
`Restored ${report.restored} files from ${origin}.`,
|
|
133
|
+
`added ${report.counts.add}, overwritten ${report.counts.overwrite}, merged ${report.counts.merge}, unchanged ${report.counts.identical}.`,
|
|
134
|
+
plan.dropped.length === 0
|
|
135
|
+
? 'Nothing in the backup was skipped.'
|
|
136
|
+
: `Skipped, never written here: ${plan.dropped.map(entry => `${entry.path} [${entry.code}]`).join(', ')}.`,
|
|
137
|
+
report.manifest === null || (report.manifest.dependenciesAdded.length === 0 && report.manifest.bundlesAdded.length === 0)
|
|
138
|
+
? 'No new plugin declarations; this configuration-only restore did not install any packages.'
|
|
139
|
+
: `New plugin declarations (not installed): ${[...new Set([...report.manifest.dependenciesAdded, ...report.manifest.bundlesAdded])].join(', ')}. Review their sources before installing from the plugins page.`,
|
|
140
|
+
...(report.undoDir === null ? ['The files already matched: no write, new undo point or restart is necessary.']
|
|
141
|
+
: [`Undo snapshot: ${report.undoDir} (use action "undo" to revert).`, 'Restart DSH to activate the restored configuration.']),
|
|
142
|
+
].join('\n'),
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const report = undoLastRestore()
|
|
146
|
+
return { summary: `Reverted ${report.reverted} configuration files from ${report.stamp}. No packages were uninstalled. Restart DSH to activate.` }
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Profile summary as text. */
|
|
151
|
+
function statusText() {
|
|
152
|
+
const root = profileRoot()
|
|
153
|
+
const { backup, dropped } = exportBackupWithReport({})
|
|
154
|
+
const undo = undoStatus()
|
|
155
|
+
const settings = readSettings()
|
|
156
|
+
return [
|
|
157
|
+
`Profile ${profileName()} at ${root} (found via ${profileSource()}).`,
|
|
158
|
+
`${backup.files.length} files, ${backupBytes(backup)} bytes, ${collectProfileFiles(root).excluded.length} excluded.`,
|
|
159
|
+
dropped.length === 0
|
|
160
|
+
? 'No machine-local dependency would be left out of an upload.'
|
|
161
|
+
: `An upload would leave out ${dropped.length} machine-local ${dropped.length === 1 ? 'dependency' : 'dependencies'}: ${dropped.map(entry => `${entry.name} (${entry.spec})`).join(', ')}.`,
|
|
162
|
+
settings.gistId === null ? 'No cloud copy yet; gist_upload creates one.' : `Cloud copy: Gist ${settings.gistId}.`,
|
|
163
|
+
settings.lastUpload === null ? 'Never uploaded.' : `Last upload ${settings.lastUpload.at} (${settings.lastUpload.files} files).`,
|
|
164
|
+
settings.lastSync === null ? 'Never synced here.' : `Last sync ${settings.lastSync.at} (${settings.lastSync.files} files).`,
|
|
165
|
+
undo === null ? 'No restore to undo.' : `A restore from ${undo.stamp} can still be undone.`,
|
|
166
|
+
'Plugin packages are not in the backup. Review missing packages and their sources on the Multi-device config sync page; restart DSH as indicated.',
|
|
167
|
+
].join('\n')
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Restore plan as text, so the model sees exactly what would change. */
|
|
171
|
+
function planText(plan, origin) {
|
|
172
|
+
const lines = [
|
|
173
|
+
`Backup from ${origin}: profile ${plan.sourceProfile}, created ${plan.createdAt}.`,
|
|
174
|
+
`Restoring it would add ${plan.counts.add}, overwrite ${plan.counts.overwrite}, merge ${plan.counts.merge}, and leave ${plan.counts.identical} unchanged.`,
|
|
175
|
+
`Files: ${plan.files.map(file => `${file.path} (${file.status})`).join(', ')}`,
|
|
176
|
+
]
|
|
177
|
+
if (plan.manifest !== null && plan.manifest.dependenciesAdded.length > 0) {
|
|
178
|
+
lines.push(`Dependencies this backup adds: ${plan.manifest.dependenciesAdded.join(', ')} — they need a plugin install afterwards.`)
|
|
179
|
+
}
|
|
180
|
+
if (plan.dropped.length > 0) {
|
|
181
|
+
lines.push(`Ignored (never written here): ${plan.dropped.map(entry => `${entry.path} [${entry.code}]`).join(', ')}.`)
|
|
182
|
+
}
|
|
183
|
+
return lines.join('\n')
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Register the tool; the returned disposer unregisters it. */
|
|
187
|
+
export function registerTool(ctx) {
|
|
188
|
+
const tools = ctx.get('tools')
|
|
189
|
+
if (tools === undefined || tools === null) return () => {}
|
|
190
|
+
return tools.register(DEFINITION)
|
|
191
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Multi-device config sync",
|
|
4
|
+
"description": "Back up your DSH profile to a GitHub Gist. Open Multi-device config sync in the Settings sidebar to preview file changes and missing plugins before confirming a restore. Use a trusted Gist; undo restores configuration only, not packages."
|
|
5
|
+
},
|
|
6
|
+
"tab": "Multi-device config sync",
|
|
7
|
+
"title": "Multi-device config sync",
|
|
8
|
+
"subtitle": "Move your configuration and plugins between computers.",
|
|
9
|
+
"backup": "Back up this machine",
|
|
10
|
+
"restore": "Restore from backup",
|
|
11
|
+
"copyBackupLink": "Copy backup link",
|
|
12
|
+
"plugins": "Plugins",
|
|
13
|
+
"pluginsHint": "The backup does not contain plugin packages. Review the names and sources of missing plugins before allowing installation.",
|
|
14
|
+
"pluginsInstall": "Install the missing plugins",
|
|
15
|
+
"setupTitle": "Restore from backup",
|
|
16
|
+
"previewAction": "View preview",
|
|
17
|
+
"confirmAction": "Confirm configuration restore",
|
|
18
|
+
"newMachineTitle": "Using this on a new machine",
|
|
19
|
+
"newMachineStep1": "Install Multi-device config sync in the target profile.",
|
|
20
|
+
"newMachineStep2": "Choose Restore from backup and use the linked backup or paste a trusted link from another machine.",
|
|
21
|
+
"newMachineStep3": "Review file changes, plugin sources and items that need manual setup. Address GitHub access only if prompted.",
|
|
22
|
+
"newMachineStep4": "Confirm only if you trust the plan. Review the results, handle pending builds separately and restart DSH as indicated.",
|
|
23
|
+
"tokenHelp": "Use the token field, DSH_GITHUB_TOKEN / GITHUB_TOKEN on the host, or a signed-in gh CLI. Do not share tokens or Gist links."
|
|
24
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "多端配置同步",
|
|
4
|
+
"description": "将 DSH 配置备份到 GitHub Gist。在设置左侧打开「多端配置同步」,先预览文件变更和缺失插件,确认后再恢复并安装。只使用可信 Gist;撤销只恢复配置,不卸载软件包。"
|
|
5
|
+
},
|
|
6
|
+
"tab": "多端配置同步",
|
|
7
|
+
"title": "多端配置同步",
|
|
8
|
+
"subtitle": "在不同电脑之间迁移配置和插件。",
|
|
9
|
+
"backup": "备份本机",
|
|
10
|
+
"restore": "从备份恢复",
|
|
11
|
+
"copyBackupLink": "复制备份链接",
|
|
12
|
+
"plugins": "插件",
|
|
13
|
+
"pluginsHint": "备份不含插件本体。请先核对缺失插件的名称和来源,再决定是否安装。",
|
|
14
|
+
"pluginsInstall": "安装缺的插件",
|
|
15
|
+
"setupTitle": "从备份恢复",
|
|
16
|
+
"previewAction": "查看预览",
|
|
17
|
+
"confirmAction": "确认恢复配置",
|
|
18
|
+
"newMachineTitle": "在新机器上使用",
|
|
19
|
+
"newMachineStep1": "在目标配置中安装「多端配置同步」。",
|
|
20
|
+
"newMachineStep2": "点「从备份恢复」,使用已关联的备份,或粘贴另一台电脑生成的链接。",
|
|
21
|
+
"newMachineStep3": "查看预览,核对文件变更、插件来源和需手动处理的项目。若 GitHub 拒绝访问,再按提示配置凭据。",
|
|
22
|
+
"newMachineStep4": "信任该计划才确认。查看结果,单独处理待审批的构建脚本,并按提示重启 DSH。",
|
|
23
|
+
"tokenHelp": "可使用页面令牌栏、宿主环境的 DSH_GITHUB_TOKEN / GITHUB_TOKEN 或已登录的 gh CLI;不要分享令牌或 Gist 链接。"
|
|
24
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-multi-device-config-sync",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
"version": "1.5.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"registry": "https://registry.npmjs.org/",
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"description": "Multi-device config sync: back up a DSH profile to a GitHub Gist and preview file changes and missing plugins before restoring on another machine. · 多端配置同步:把 DSH 配置备份到 Gist,在另一台机器先预览配置变更和缺失插件,再确认恢复。",
|
|
10
|
+
"icon": "icon.svg",
|
|
11
|
+
"main": "./index.js",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./index.js",
|
|
14
|
+
"./client": "./client.js",
|
|
15
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
16
|
+
"./package.json": "./package.json",
|
|
17
|
+
"./locale/*.json": "./locale/*.json",
|
|
18
|
+
"./icon": "./icon.svg"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"client.js",
|
|
23
|
+
"lib/*.js",
|
|
24
|
+
"test/*.mjs",
|
|
25
|
+
"assets/icon-256.png",
|
|
26
|
+
"cordis.patch.yml",
|
|
27
|
+
"locale/*.json",
|
|
28
|
+
"icon.svg",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"dsh": {
|
|
33
|
+
"bundle": {
|
|
34
|
+
"patch": "./cordis.patch.yml"
|
|
35
|
+
},
|
|
36
|
+
"client": {
|
|
37
|
+
"platform": "web",
|
|
38
|
+
"immediately": true
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"test": "node test/run.mjs"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"deepseek-harness",
|
|
46
|
+
"dsh",
|
|
47
|
+
"dsh-plugin",
|
|
48
|
+
"config",
|
|
49
|
+
"backup",
|
|
50
|
+
"gist",
|
|
51
|
+
"sync",
|
|
52
|
+
"profile"
|
|
53
|
+
],
|
|
54
|
+
"author": "Meta-Virgo",
|
|
55
|
+
"contributors": ["Xeonice (https://github.com/Xeonice)"],
|
|
56
|
+
"license": "MIT",
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/Xeonice/dsh-profile-gist-sync-plus.git"
|
|
60
|
+
},
|
|
61
|
+
"homepage": "https://github.com/Xeonice/dsh-profile-gist-sync-plus#readme",
|
|
62
|
+
"bugs": {
|
|
63
|
+
"url": "https://github.com/Xeonice/dsh-profile-gist-sync-plus/issues"
|
|
64
|
+
},
|
|
65
|
+
"engines": {
|
|
66
|
+
"node": ">=20"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Activation: what DSH gets when it loads this plugin.
|
|
3
|
+
*
|
|
4
|
+
* The row is loaded once, at DSH start, and everything the plugin does happens
|
|
5
|
+
* through `apply(ctx)` — so the contract matters as much as the behaviour:
|
|
6
|
+
* Cordis fails the whole row with "Invalid effect" when an `ctx.effect` callback
|
|
7
|
+
* returns something that is not a disposer, and a failed row means no routes and
|
|
8
|
+
* no tool. That is checked here, not assumed.
|
|
9
|
+
*/
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { createReport, makeProfile, tempDir, useProfile, callRoute, serveHandler } from './harness.mjs'
|
|
12
|
+
|
|
13
|
+
const { check, finish } = createReport('activation')
|
|
14
|
+
|
|
15
|
+
const home = tempDir('dpg-activation-')
|
|
16
|
+
const profile = makeProfile(join(home, 'profiles', 'test'))
|
|
17
|
+
useProfile(profile, home)
|
|
18
|
+
|
|
19
|
+
const { apply } = await import('../index.js')
|
|
20
|
+
const { BASE_PATH } = await import('../lib/routes.js')
|
|
21
|
+
|
|
22
|
+
/** A host context, with Cordis's effect contract enforced. */
|
|
23
|
+
function hostContext({ webServer = true, tools = true, profileContext = null, throwOnProfileContext = false } = {}) {
|
|
24
|
+
const seen = { routes: [], tools: [], effects: [], disposers: [] }
|
|
25
|
+
const ctx = {
|
|
26
|
+
get(name) {
|
|
27
|
+
if (name === 'webServer' && webServer) return { register(route) { seen.routes.push(route); return () => {} } }
|
|
28
|
+
if (name === 'profileContext') {
|
|
29
|
+
if (throwOnProfileContext) throw new Error('this host has no service registry')
|
|
30
|
+
return profileContext
|
|
31
|
+
}
|
|
32
|
+
if (name === 'tools' && tools) return { register(tool) { seen.tools.push(tool); return () => {} } }
|
|
33
|
+
return undefined
|
|
34
|
+
},
|
|
35
|
+
effect(fn, label) {
|
|
36
|
+
const dispose = fn()
|
|
37
|
+
if (typeof dispose !== 'function') throw new Error(`Invalid effect: ${String(label)}`)
|
|
38
|
+
seen.effects.push(label)
|
|
39
|
+
seen.disposers.push(dispose)
|
|
40
|
+
return dispose
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
return { ctx, seen }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ---- the happy path -----------------------------------------------------
|
|
47
|
+
{
|
|
48
|
+
const { ctx, seen } = hostContext()
|
|
49
|
+
let threw = null
|
|
50
|
+
try {
|
|
51
|
+
apply(ctx)
|
|
52
|
+
} catch (error) {
|
|
53
|
+
threw = error
|
|
54
|
+
}
|
|
55
|
+
check('apply activates without throwing', threw === null, threw?.message)
|
|
56
|
+
check('one prefix route is registered', seen.routes.length === 1 && seen.routes[0].kind === 'prefix', JSON.stringify(seen.routes.map(route => `${route.kind} ${route.path}`)))
|
|
57
|
+
check('the route uses the fork’s own prefix', BASE_PATH === '/dsh-profile-gist-sync-plus' && seen.routes[0]?.path === BASE_PATH, seen.routes[0]?.path)
|
|
58
|
+
check('every effect returned a disposer', seen.effects.length === 2, seen.effects.join(', '))
|
|
59
|
+
check('the tool is registered once', seen.tools.length === 1)
|
|
60
|
+
const definition = seen.tools[0]
|
|
61
|
+
check('the tool has its own name, distinct from upstream', definition?.name === 'config_backup_plus', definition?.name)
|
|
62
|
+
const properties = definition?.parameters?.properties ?? {}
|
|
63
|
+
check('the agent cannot confirm a plugin install or approve builds',
|
|
64
|
+
definition?.parameters?.additionalProperties === false && ['confirm', 'planId', 'approvedBuilds'].every(key => !Object.hasOwn(properties, key)))
|
|
65
|
+
let installError = null
|
|
66
|
+
try { await definition?.execute({ action: 'sync_install', confirm: true, planId: 'test-plan' }) }
|
|
67
|
+
catch (error) { installError = error }
|
|
68
|
+
check('an install/confirm request is rejected even when passed directly to the tool', installError?.code === 'invalid')
|
|
69
|
+
check('and it offers every action the README lists',
|
|
70
|
+
JSON.stringify(definition?.parameters?.properties?.action?.enum) === JSON.stringify(['status', 'export', 'gist_upload', 'gist_read', 'restore', 'undo']),
|
|
71
|
+
JSON.stringify(definition?.parameters?.properties?.action?.enum))
|
|
72
|
+
check('the disposers can be called', (() => {
|
|
73
|
+
try {
|
|
74
|
+
for (const dispose of seen.disposers) dispose()
|
|
75
|
+
return true
|
|
76
|
+
} catch {
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
})())
|
|
80
|
+
|
|
81
|
+
// ---- the status route, on the real handler -----------------------------
|
|
82
|
+
const served = await serveHandler(seen.routes[0].handler)
|
|
83
|
+
const status = await callRoute(served.base, `${BASE_PATH}/api/status`)
|
|
84
|
+
check('the status route answers', status.status === 200 && status.payload.profile === 'test', `${status.status} ${JSON.stringify(status.payload).slice(0, 120)}`)
|
|
85
|
+
check('it reports the profile it is working on', status.payload.root === profile, status.payload.root)
|
|
86
|
+
check('it says which source identified the profile', status.payload.profileSource === 'DSH_PROFILE_DIR', status.payload.profileSource)
|
|
87
|
+
check('it lists the files a backup would carry', status.payload.counts.files > 0 && Array.isArray(status.payload.files))
|
|
88
|
+
check('and it reports the exclusions', status.payload.counts.excluded > 0, JSON.stringify(status.payload.counts))
|
|
89
|
+
check('a fresh profile has no cloud copy', status.payload.cloud.gistId === null && status.payload.cloud.lastUpload === null)
|
|
90
|
+
const unknown = await callRoute(served.base, `${BASE_PATH}/api/nope`)
|
|
91
|
+
check('an unknown subpath answers JSON, not a crash', unknown.status === 404 && unknown.payload.code === 'notfound', JSON.stringify(unknown.payload))
|
|
92
|
+
const outside = await callRoute(served.base, '/dsh-profile-gist-sync/api/status')
|
|
93
|
+
check('the Plus handler does not claim the upstream route', outside.status === 404, String(outside.status))
|
|
94
|
+
served.close()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---- hosts that publish less -------------------------------------------
|
|
98
|
+
{
|
|
99
|
+
const { ctx, seen } = hostContext({ profileContext: null })
|
|
100
|
+
let threw = null
|
|
101
|
+
try {
|
|
102
|
+
apply(ctx)
|
|
103
|
+
} catch (error) {
|
|
104
|
+
threw = error
|
|
105
|
+
}
|
|
106
|
+
check('a host that reports no profile facts still activates', threw === null && seen.routes.length === 1, threw?.message)
|
|
107
|
+
}
|
|
108
|
+
{
|
|
109
|
+
const { ctx, seen } = hostContext({ tools: false })
|
|
110
|
+
let threw = null
|
|
111
|
+
try {
|
|
112
|
+
apply(ctx)
|
|
113
|
+
} catch (error) {
|
|
114
|
+
threw = error
|
|
115
|
+
}
|
|
116
|
+
check('a host without a tools service still activates', threw === null && seen.routes.length === 1 && seen.tools.length === 0, threw?.message)
|
|
117
|
+
}
|
|
118
|
+
{
|
|
119
|
+
const { ctx, seen } = hostContext({ throwOnProfileContext: true })
|
|
120
|
+
let threw = null
|
|
121
|
+
try {
|
|
122
|
+
apply(ctx)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
threw = error
|
|
125
|
+
}
|
|
126
|
+
check('a host whose profile lookup throws still activates', threw === null && seen.routes.length === 1, threw?.message)
|
|
127
|
+
}
|
|
128
|
+
{
|
|
129
|
+
const { ctx, seen } = hostContext({ webServer: false })
|
|
130
|
+
check('a host without a web server is left alone', apply(ctx) === undefined && seen.routes.length === 0)
|
|
131
|
+
}
|
|
132
|
+
{
|
|
133
|
+
const { ctx, seen } = hostContext({ profileContext: { name: 'reported', dir: profile } })
|
|
134
|
+
apply(ctx)
|
|
135
|
+
const backup = await import('../lib/backup.js')
|
|
136
|
+
check('the profile the host reports is the one used',
|
|
137
|
+
backup.profileRoot() === profile && backup.profileSource() === 'host', `${backup.profileRoot()} (${backup.profileSource()})`)
|
|
138
|
+
check('and its name is kept for the document', backup.profileName() === 'reported', backup.profileName())
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
process.exit(finish())
|