dsh-plugin-syncer 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/merge.js ADDED
@@ -0,0 +1,146 @@
1
+ import { nowIso, stableStringify, valueHash } from './util.js'
2
+
3
+ export const DOC_FORMAT = 'dsh-sync-doc'
4
+ export const SCHEMA_VERSION = 1
5
+ const CONFLICT_WINDOW_MS = 5000
6
+
7
+ export function emptyDoc(deviceId) {
8
+ return {
9
+ format: DOC_FORMAT,
10
+ schemaVersion: SCHEMA_VERSION,
11
+ deviceId,
12
+ updatedAt: nowIso(),
13
+ entries: {},
14
+ }
15
+ }
16
+
17
+ export function parseDoc(text, expectedDeviceId) {
18
+ let doc
19
+ try {
20
+ doc = JSON.parse(text)
21
+ } catch {
22
+ return null
23
+ }
24
+ if (!doc || typeof doc !== 'object') return null
25
+ if (doc.format !== DOC_FORMAT || doc.schemaVersion !== SCHEMA_VERSION) return null
26
+ if (typeof doc.entries !== 'object' || doc.entries === null) return null
27
+ if (expectedDeviceId && doc.deviceId !== expectedDeviceId) return null
28
+ for (const [id, rec] of Object.entries(doc.entries)) {
29
+ if (!rec || typeof rec !== 'object' || typeof rec.name !== 'string') delete doc.entries[id]
30
+ }
31
+ return doc
32
+ }
33
+
34
+ export function recordOf(entry, { rev, origin }) {
35
+ return {
36
+ name: entry.name,
37
+ enabled: entry.enabled === true,
38
+ config: entry.config ?? {},
39
+ // The version/source describe the code that produced this config. They ride
40
+ // along so another machine can install or upgrade to the same plugin before
41
+ // replaying the config.
42
+ version: typeof entry.version === 'string' && entry.version ? entry.version : null,
43
+ source: normalizeSource(entry.source),
44
+ rev: Math.max(1, Number(rev) || 1),
45
+ at: nowIso(),
46
+ origin,
47
+ }
48
+ }
49
+
50
+ export function normalizeSource(source) {
51
+ if (!source || typeof source !== 'object') return null
52
+ const kind = typeof source.kind === 'string' ? source.kind.trim() : ''
53
+ if (!kind) return null
54
+ return { kind, spec: typeof source.spec === 'string' ? source.spec : '' }
55
+ }
56
+
57
+ export function normalizeRecord(rec, origin) {
58
+ return {
59
+ name: String(rec.name || ''),
60
+ enabled: rec.enabled === true,
61
+ config: rec.config && typeof rec.config === 'object' && !Array.isArray(rec.config) ? rec.config : {},
62
+ version: typeof rec.version === 'string' && rec.version ? rec.version : null,
63
+ source: normalizeSource(rec.source),
64
+ rev: Math.max(1, Number(rec.rev) || 1),
65
+ at: rec.at || '1970-01-01T00:00:00.000Z',
66
+ origin: rec.origin || origin || '',
67
+ }
68
+ }
69
+
70
+ export function recordValue(rec) {
71
+ return { enabled: rec.enabled === true, config: rec.config ?? {} }
72
+ }
73
+
74
+ export function recordHash(rec) {
75
+ return valueHash(recordValue(rec))
76
+ }
77
+
78
+ export function recordKey(rec) {
79
+ return stableStringify(recordValue(rec))
80
+ }
81
+
82
+ function timeOf(rec) {
83
+ const t = Date.parse(rec.at)
84
+ return Number.isFinite(t) ? t : 0
85
+ }
86
+
87
+ /** Last write wins by wall clock, then Lamport counter, then device id. */
88
+ export function compareRecords(a, b) {
89
+ const ta = timeOf(a)
90
+ const tb = timeOf(b)
91
+ if (ta !== tb) return ta - tb
92
+ const ra = Number(a.rev) || 0
93
+ const rb = Number(b.rev) || 0
94
+ if (ra !== rb) return ra - rb
95
+ return String(a.origin || '').localeCompare(String(b.origin || ''))
96
+ }
97
+
98
+ /**
99
+ * Merge every device document into one winner per entry.
100
+ *
101
+ * A conflict is reported when two different values were written within a few
102
+ * seconds of each other: their wall clocks cannot order them meaningfully, so
103
+ * the winner is deterministic but the loser is preserved for inspection.
104
+ */
105
+ export function mergeDocs(docs) {
106
+ const groups = new Map()
107
+ for (const { deviceId, doc } of docs) {
108
+ if (!doc || typeof doc !== 'object' || !doc.entries) continue
109
+ for (const [id, raw] of Object.entries(doc.entries)) {
110
+ if (!raw || typeof raw !== 'object') continue
111
+ const rec = normalizeRecord(raw, deviceId)
112
+ if (!rec.name) continue
113
+ const list = groups.get(id) ?? []
114
+ list.push({ id, deviceId, rec })
115
+ groups.set(id, list)
116
+ }
117
+ }
118
+
119
+ const winners = new Map()
120
+ const conflicts = []
121
+ for (const [id, list] of groups) {
122
+ list.sort((a, b) => compareRecords(a.rec, b.rec))
123
+ const top = list[list.length - 1]
124
+ winners.set(id, { ...top.rec })
125
+ const topTime = timeOf(top.rec)
126
+ const topHash = recordHash(top.rec)
127
+ const others = list
128
+ .slice(0, -1)
129
+ .filter(
130
+ (item) =>
131
+ Number(item.rec.rev) === Number(top.rec.rev) &&
132
+ Math.abs(timeOf(item.rec) - topTime) <= CONFLICT_WINDOW_MS &&
133
+ recordHash(item.rec) !== topHash,
134
+ )
135
+ .map((item) => ({ ...item.rec, deviceId: item.deviceId }))
136
+ if (others.length > 0) {
137
+ conflicts.push({
138
+ id,
139
+ name: top.rec.name,
140
+ winner: { ...top.rec, deviceId: top.deviceId },
141
+ others,
142
+ })
143
+ }
144
+ }
145
+ return { winners, conflicts }
146
+ }
@@ -0,0 +1,119 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { isJsonSafe, valueHash } from './util.js'
4
+
5
+ const PACKAGE_NAME = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
6
+
7
+ function readJson(file) {
8
+ try {
9
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
10
+ } catch {
11
+ return null
12
+ }
13
+ }
14
+
15
+ function profileDependencies(profileDir) {
16
+ const pkg = profileDir ? readJson(path.join(profileDir, 'package.json')) : null
17
+ const deps = {}
18
+ for (const field of ['dependencies', 'devDependencies']) {
19
+ const section = pkg?.[field]
20
+ if (!section || typeof section !== 'object') continue
21
+ for (const [name, spec] of Object.entries(section)) {
22
+ if (typeof spec === 'string') deps[name] = spec
23
+ }
24
+ }
25
+ return deps
26
+ }
27
+
28
+ /** Installed version of a registry/link package, or null when unreadable. */
29
+ export function installedVersion(profileDir, name) {
30
+ if (!profileDir || typeof name !== 'string' || !PACKAGE_NAME.test(name)) return null
31
+ const pkg = readJson(path.join(profileDir, 'node_modules', ...name.split('/'), 'package.json'))
32
+ return typeof pkg?.version === 'string' && pkg.version ? pkg.version : null
33
+ }
34
+
35
+ /**
36
+ * Where this entry's code comes from. The profile package.json keeps the
37
+ * install spec (registry range, `file:` link, git URL), which is what another
38
+ * machine would need to reproduce the same plugin.
39
+ */
40
+ function sourceOf(name, deps) {
41
+ if (typeof name !== 'string' || !name) return null
42
+ const spec = deps[name]
43
+ if (!spec) return PACKAGE_NAME.test(name) ? null : { kind: 'path', spec: name }
44
+ const value = spec.trim()
45
+ if (/^(file:|link:|workspace:)/i.test(value)) return { kind: 'local', spec: value }
46
+ if (/^(git\+|git:|github:|gitlab:|bitbucket:|https?:\/\/)/i.test(value)) return { kind: 'git', spec: value }
47
+ return { kind: 'npm', spec: value }
48
+ }
49
+
50
+ /**
51
+ * Read the syncable state of this profile: every plugin entry the profile
52
+ * layer owns, with its enable/disable state and its effective config.
53
+ *
54
+ * configEditor.entries() already excludes entries this profile cannot address
55
+ * (nested includes, duplicate ids), which is exactly the set we can replay on
56
+ * another machine without ambiguity.
57
+ */
58
+ export function readSnapshot(ctx, cfg, scope = {}) {
59
+ const editor = ctx.get('configEditor')
60
+ if (!editor || typeof editor.entries !== 'function') {
61
+ throw new Error('configEditor service is unavailable')
62
+ }
63
+ const patchIds = scope.patchIds instanceof Set ? scope.patchIds : new Set()
64
+ const profileDir = scope.profileDir || cfg.profileDir || ''
65
+ const deps = profileDependencies(profileDir)
66
+ const rows = editor.entries()
67
+ const inventory = new Map()
68
+ try {
69
+ const manager = ctx.get('pluginManager')
70
+ if (manager && typeof manager.listPlugins === 'function') {
71
+ for (const row of manager.listPlugins()) inventory.set(row.entryId, row)
72
+ }
73
+ } catch {}
74
+
75
+ const entries = []
76
+ const skipped = []
77
+ for (const entry of rows) {
78
+ const id = entry?.options?.id
79
+ const name = entry?.options?.name
80
+ if (!id || !name) continue
81
+ if (name === 'dsh-sync' || id === 'dsh-sync') continue
82
+ // Core profile internals only travel when the user has explicitly patched
83
+ // them; syncing the whole core graph would let one machine disable a
84
+ // component the others rely on.
85
+ if (name.startsWith('@deepseek-ai/') && !patchIds.has(id)) continue
86
+ if (cfg.excludeEntries.includes(id) || cfg.excludeEntries.includes(name)) {
87
+ skipped.push({ id, name, reason: 'excluded' })
88
+ continue
89
+ }
90
+ const config = entry.options.config ?? {}
91
+ if (!isJsonSafe(config)) {
92
+ skipped.push({ id, name, reason: 'config is not JSON-serializable' })
93
+ continue
94
+ }
95
+ let stable = true
96
+ if (inventory.size > 0) {
97
+ const row = inventory.get(id)
98
+ if (row?.readOnlyReason) {
99
+ skipped.push({ id, name, reason: `read-only: ${row.readOnlyReason}` })
100
+ stable = false
101
+ }
102
+ }
103
+ if (!stable) continue
104
+ entries.push({
105
+ id,
106
+ name,
107
+ enabled: entry.disabled !== true,
108
+ config: JSON.parse(JSON.stringify(config)),
109
+ readOnly: false,
110
+ version: installedVersion(profileDir, name),
111
+ source: sourceOf(name, deps),
112
+ })
113
+ }
114
+ return { entries, skipped }
115
+ }
116
+
117
+ export function snapshotHash(entries) {
118
+ return valueHash(entries.map((entry) => ({ id: entry.id, enabled: entry.enabled, config: entry.config })))
119
+ }
package/lib/token.js ADDED
@@ -0,0 +1,37 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { stateDir } from './config.js'
4
+
5
+ export function defaultTokenFile() {
6
+ return path.join(stateDir(), 'token')
7
+ }
8
+
9
+ export function readTokenFile(file) {
10
+ try {
11
+ return fs.readFileSync(file, 'utf8').trim()
12
+ } catch {
13
+ return ''
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Token lookup order: explicit config value, token file, environment variable.
19
+ * The token file lives outside the profile so it is never synced.
20
+ */
21
+ export function resolveToken(cfg) {
22
+ if (cfg.provider === 'file') return { token: '', source: 'none' }
23
+ if (cfg.token) return { token: cfg.token, source: 'config' }
24
+ const file = cfg.tokenFile || defaultTokenFile()
25
+ const fromFile = readTokenFile(file)
26
+ if (fromFile) return { token: fromFile, source: `file:${file}` }
27
+ const envName = cfg.tokenEnv || 'DSH_SYNC_TOKEN'
28
+ const fromEnv = (process.env[envName] || '').trim()
29
+ if (fromEnv) return { token: fromEnv, source: `env:${envName}` }
30
+ return { token: '', source: 'none', file, envName }
31
+ }
32
+
33
+ export function maskToken(token) {
34
+ if (!token) return ''
35
+ if (token.length <= 8) return '***'
36
+ return `${token.slice(0, 4)}…${token.slice(-4)}`
37
+ }
@@ -0,0 +1,283 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { ensureDir, sha256 } from './util.js'
4
+
5
+ const TIMEOUT_MS = 30_000
6
+ const USER_AGENT = 'dsh-sync/0.1.0'
7
+
8
+ export class TransportError extends Error {
9
+ constructor(message, { status, code, body } = {}) {
10
+ super(message)
11
+ this.name = 'TransportError'
12
+ this.status = status
13
+ this.code = code
14
+ this.body = body
15
+ }
16
+ }
17
+
18
+ function extractMessage(data) {
19
+ if (!data) return ''
20
+ if (typeof data === 'string') return data.slice(0, 300)
21
+ return data.message || data.error_description || data.error || ''
22
+ }
23
+
24
+ async function httpJson(url, init = {}) {
25
+ const controller = new AbortController()
26
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
27
+ let res
28
+ try {
29
+ res = await fetch(url, {
30
+ ...init,
31
+ signal: controller.signal,
32
+ headers: { 'user-agent': USER_AGENT, ...(init.headers || {}) },
33
+ })
34
+ } catch (error) {
35
+ throw new TransportError(`network request failed: ${error.message}`, { code: 'network' })
36
+ }
37
+ const text = await res.text()
38
+ clearTimeout(timer)
39
+ let data = null
40
+ try {
41
+ data = text ? JSON.parse(text) : null
42
+ } catch {
43
+ data = text
44
+ }
45
+ if (!res.ok) {
46
+ const code =
47
+ res.status === 401 || res.status === 403
48
+ ? 'auth'
49
+ : res.status === 404
50
+ ? 'not-found'
51
+ : res.status === 409 || res.status === 412 || res.status === 422
52
+ ? 'conflict'
53
+ : 'http'
54
+ const hint = code === 'auth' ? ' (check the token and its scope)' : ''
55
+ throw new TransportError(`${res.status} ${extractMessage(data) || res.statusText}${hint}`, {
56
+ status: res.status,
57
+ code,
58
+ body: data,
59
+ })
60
+ }
61
+ return data
62
+ }
63
+
64
+ function decodeBase64(content) {
65
+ return Buffer.from(String(content || '').replace(/\s+/g, ''), 'base64').toString('utf8')
66
+ }
67
+
68
+ function joinPath(root, rel) {
69
+ const base = String(root || '').replace(/^\/+|\/+$/g, '')
70
+ const tail = String(rel || '').replace(/^\/+|\/+$/g, '')
71
+ return tail ? `${base}/${tail}` : base
72
+ }
73
+
74
+ const TOKEN_QUERY = 'access_token'
75
+
76
+ /** Gitee / Gitea contents API. Both accept access_token in the query string. */
77
+ export class GiteeContentsTransport {
78
+ constructor(cfg, token) {
79
+ this.apiBase = (cfg.apiBase || 'https://gitee.com/api/v5').replace(/\/+$/, '')
80
+ this.owner = cfg.owner
81
+ this.repo = cfg.repo
82
+ this.branch = cfg.branch
83
+ this.root = cfg.path
84
+ this.token = token
85
+ }
86
+
87
+ url(rel) {
88
+ const filePath = joinPath(this.root, rel)
89
+ .split('/')
90
+ .filter(Boolean)
91
+ .map(encodeURIComponent)
92
+ .join('/')
93
+ return `${this.apiBase}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}/contents/${filePath}`
94
+ }
95
+
96
+ withToken(url, extra = {}) {
97
+ const u = new URL(url)
98
+ u.searchParams.set('access_token', this.token)
99
+ for (const [key, value] of Object.entries(extra)) if (value !== undefined) u.searchParams.set(key, String(value))
100
+ return u.toString()
101
+ }
102
+
103
+ async list(rel = '') {
104
+ try {
105
+ const data = await httpJson(this.withToken(this.url(rel), { ref: this.branch }))
106
+ if (!Array.isArray(data)) return []
107
+ return data
108
+ .filter((item) => item.type === 'file')
109
+ .map((item) => ({ name: item.name, path: item.path, sha: item.sha, size: item.size }))
110
+ } catch (error) {
111
+ if (error.status === 404) return []
112
+ throw error
113
+ }
114
+ }
115
+
116
+ async get(rel) {
117
+ try {
118
+ const data = await httpJson(this.withToken(this.url(rel), { ref: this.branch }))
119
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null
120
+ return { text: decodeBase64(data.content), sha: data.sha, size: data.size }
121
+ } catch (error) {
122
+ if (error.status === 404) return null
123
+ throw error
124
+ }
125
+ }
126
+
127
+ async put(rel, text, { message, sha } = {}) {
128
+ const body = {
129
+ access_token: this.token,
130
+ content: Buffer.from(text, 'utf8').toString('base64'),
131
+ message: message || `dsh-sync: update ${rel}`,
132
+ branch: this.branch,
133
+ }
134
+ if (sha) body.sha = sha
135
+ // Gitee and Gitea distinguish create (POST) from update (PUT).
136
+ const data = await httpJson(this.url(rel), {
137
+ method: sha ? 'PUT' : 'POST',
138
+ headers: { 'content-type': 'application/json;charset=UTF-8', accept: 'application/json' },
139
+ body: JSON.stringify(body),
140
+ })
141
+ return data?.content?.sha || data?.sha || null
142
+ }
143
+ }
144
+
145
+ class GithubContentsTransport {
146
+ constructor(cfg, token) {
147
+ this.apiBase = (cfg.apiBase || 'https://api.github.com').replace(/\/+$/, '')
148
+ this.owner = cfg.owner
149
+ this.repo = cfg.repo
150
+ this.branch = cfg.branch
151
+ this.root = cfg.path
152
+ this.token = token
153
+ }
154
+
155
+ url(rel) {
156
+ const filePath = joinPath(this.root, rel)
157
+ .split('/')
158
+ .filter(Boolean)
159
+ .map(encodeURIComponent)
160
+ .join('/')
161
+ return `${this.apiBase}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}/contents/${filePath}`
162
+ }
163
+
164
+ headers(extra = {}) {
165
+ return {
166
+ authorization: `Bearer ${this.token}`,
167
+ accept: 'application/vnd.github+json',
168
+ 'x-github-api-version': '2022-11-28',
169
+ ...extra,
170
+ }
171
+ }
172
+
173
+ async list(rel = '') {
174
+ const url = new URL(this.url(rel))
175
+ url.searchParams.set('ref', this.branch)
176
+ try {
177
+ const data = await httpJson(url.toString(), { headers: this.headers() })
178
+ if (!Array.isArray(data)) return []
179
+ return data
180
+ .filter((item) => item.type === 'file')
181
+ .map((item) => ({ name: item.name, path: item.path, sha: item.sha, size: item.size }))
182
+ } catch (error) {
183
+ if (error.status === 404) return []
184
+ throw error
185
+ }
186
+ }
187
+
188
+ async get(rel) {
189
+ const url = new URL(this.url(rel))
190
+ url.searchParams.set('ref', this.branch)
191
+ try {
192
+ const data = await httpJson(url.toString(), { headers: this.headers() })
193
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null
194
+ return { text: decodeBase64(data.content), sha: data.sha, size: data.size }
195
+ } catch (error) {
196
+ if (error.status === 404) return null
197
+ throw error
198
+ }
199
+ }
200
+
201
+ async put(rel, text, { message, sha } = {}) {
202
+ const body = {
203
+ message: message || `dsh-sync: update ${rel}`,
204
+ content: Buffer.from(text, 'utf8').toString('base64'),
205
+ branch: this.branch,
206
+ }
207
+ if (sha) body.sha = sha
208
+ const data = await httpJson(this.url(rel), {
209
+ method: 'PUT',
210
+ headers: this.headers({ 'content-type': 'application/json;charset=UTF-8' }),
211
+ body: JSON.stringify(body),
212
+ })
213
+ return data?.content?.sha || null
214
+ }
215
+ }
216
+
217
+ /** Shared folder / mounted drive. Useful for tests and for WebDAV-synced folders. */
218
+ export class FileTransport {
219
+ constructor(cfg) {
220
+ this.root = path.resolve(cfg.dir)
221
+ this.readOnlyHint = false
222
+ }
223
+
224
+ resolve(rel) {
225
+ const target = path.resolve(this.root, rel)
226
+ const relative = path.relative(this.root, target)
227
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
228
+ throw new TransportError(`path escapes the sync directory: ${rel}`, { code: 'invalid-path' })
229
+ }
230
+ return target
231
+ }
232
+
233
+ async list(rel = '') {
234
+ const dir = this.resolve(rel)
235
+ let names
236
+ try {
237
+ names = await fs.promises.readdir(dir, { withFileTypes: true })
238
+ } catch (error) {
239
+ if (error.code === 'ENOENT') return []
240
+ throw error
241
+ }
242
+ const files = []
243
+ for (const entry of names) {
244
+ if (!entry.isFile()) continue
245
+ if (entry.name.startsWith('.')) continue
246
+ const full = path.join(dir, entry.name)
247
+ try {
248
+ const text = await fs.promises.readFile(full, 'utf8')
249
+ files.push({
250
+ name: entry.name,
251
+ path: joinPath(rel, entry.name),
252
+ sha: sha256(text).slice(0, 20),
253
+ size: Buffer.byteLength(text),
254
+ })
255
+ } catch {}
256
+ }
257
+ return files
258
+ }
259
+
260
+ async get(rel) {
261
+ const file = this.resolve(rel)
262
+ try {
263
+ const text = await fs.promises.readFile(file, 'utf8')
264
+ return { text, sha: sha256(text).slice(0, 20), size: Buffer.byteLength(text) }
265
+ } catch (error) {
266
+ if (error.code === 'ENOENT') return null
267
+ throw error
268
+ }
269
+ }
270
+
271
+ async put(rel, text) {
272
+ const file = this.resolve(rel)
273
+ ensureDir(path.dirname(file))
274
+ await fs.promises.writeFile(file, text, 'utf8')
275
+ return sha256(text).slice(0, 20)
276
+ }
277
+ }
278
+
279
+ export function createTransport(cfg, token) {
280
+ if (cfg.provider === 'file') return new FileTransport(cfg)
281
+ if (cfg.provider === 'github') return new GithubContentsTransport(cfg, token)
282
+ return new GiteeContentsTransport(cfg, token)
283
+ }