dsh-session-sync 0.1.4 → 0.2.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/ARCHITECTURE.md +4 -1
- package/CHANGELOG.md +11 -0
- package/README.es.md +5 -2
- package/README.hi.md +5 -2
- package/README.md +26 -4
- package/README.pt.md +5 -2
- package/README.zh.md +5 -2
- package/cordis.patch.yml +9 -2
- package/index.mjs +107 -7
- package/lib/age.mjs +77 -0
- package/lib/backend.mjs +57 -0
- package/lib/constants.mjs +18 -1
- package/lib/encrypted.mjs +523 -0
- package/lib/errors.mjs +12 -2
- package/lib/git.mjs +38 -0
- package/lib/render.mjs +8 -4
- package/package.json +1 -1
- package/types.d.ts +11 -2
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
// lib/encrypted.mjs — age 加密的 git 传输后端(零 DSH 依赖)。
|
|
2
|
+
//
|
|
3
|
+
// 传输语义(在镜像层之上):明文镜像只存在于本地工作树 <repoDir>/sessions/
|
|
4
|
+
// (.gitignore 忽略、绝不提交);git 仓库只跟踪 <repoDir>/encrypted/**/*.age
|
|
5
|
+
// 密文(每会话文件一个 age 密文)。远端看到的只有密文 + git 元数据(提交信息、
|
|
6
|
+
// 文件名结构、.gitignore),绝无明文会话字节。
|
|
7
|
+
//
|
|
8
|
+
// - push:镜像 → sessions/ → 加密到 encrypted/ → 提交 → push(被拒时拉取调和
|
|
9
|
+
// 重推一次,绝不强推)。
|
|
10
|
+
// - pull:本地提交检查点 → fetch → 取 merge-base 与远端的密文树解密成明文 →
|
|
11
|
+
// 用 lib/merge.mjs 的三分支语义在明文上合并(append-only keep-both + fork)
|
|
12
|
+
// → 重新加密 → 提交(与 git 后端一致,pull 不自动 push)。
|
|
13
|
+
// - 无 age / 缺 recipient / identity:resolve 期降级为明文 git(内部复用
|
|
14
|
+
// SyncEngine),显式警告进入 status/push/pull 结果与日志;绝不静默降级。
|
|
15
|
+
// - 加密模式下 age 加解密失败 → AGE_FAILED fail closed,绝不回退明文传输。
|
|
16
|
+
|
|
17
|
+
import { promises as fs } from 'node:fs'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { BACKENDS, ENC_DIR, ENC_EXT, FORK_NAME_RE, MERGE_KINDS, MIRROR_DIR } from './constants.mjs'
|
|
21
|
+
import { SyncEngine } from './engine.mjs'
|
|
22
|
+
import { mirrorSessionRoot } from './mirror.mjs'
|
|
23
|
+
import { classifyPath } from './merge.mjs'
|
|
24
|
+
import { detectAge, ageEncrypt, ageDecrypt } from './age.mjs'
|
|
25
|
+
import { selectEncryptionMode, BACKEND_MODES } from './backend.mjs'
|
|
26
|
+
import { collectStatus } from './status.mjs'
|
|
27
|
+
import { forkFileName } from './paths.mjs'
|
|
28
|
+
import { messageOf, SyncError } from './errors.mjs'
|
|
29
|
+
import { redactText, sanitizeRemote } from './sanitize.mjs'
|
|
30
|
+
|
|
31
|
+
/** 插件自有引用:记录最近一次已调和(push/pull 后本地与远端一致)的远端头,
|
|
32
|
+
* 作为下一次三方合并的基点(encrypted 后端不做 git 合并提交,需自持基点)。 */
|
|
33
|
+
const BASE_REF = 'refs/dsh-sync/base'
|
|
34
|
+
|
|
35
|
+
/** 递归枚举 root 下全部常规文件(POSIX 相对路径;符号链接跳过)。 */
|
|
36
|
+
async function listRelFiles(root) {
|
|
37
|
+
const files = []
|
|
38
|
+
const walk = async (dir) => {
|
|
39
|
+
let entries
|
|
40
|
+
try {
|
|
41
|
+
entries = await fs.readdir(dir, { withFileTypes: true })
|
|
42
|
+
} catch {
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
for (const entry of entries) {
|
|
46
|
+
if (entry.isSymbolicLink()) continue
|
|
47
|
+
const absolute = path.join(dir, entry.name)
|
|
48
|
+
if (entry.isDirectory()) {
|
|
49
|
+
await walk(absolute)
|
|
50
|
+
continue
|
|
51
|
+
}
|
|
52
|
+
if (entry.isFile()) files.push(path.relative(root, absolute).split(path.sep).join('/'))
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
await walk(root)
|
|
56
|
+
return files
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 读整棵树为 Map<rel, Buffer>。 */
|
|
60
|
+
async function readTree(root) {
|
|
61
|
+
const map = new Map()
|
|
62
|
+
for (const rel of await listRelFiles(root)) {
|
|
63
|
+
map.set(rel, await fs.readFile(path.join(root, ...rel.split('/'))))
|
|
64
|
+
}
|
|
65
|
+
return map
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 把 Map<rel, Buffer> 写回 root(mkdir -p;删除 map 中不存在的既有文件)。 */
|
|
69
|
+
async function writeTree(root, map) {
|
|
70
|
+
for (const rel of await listRelFiles(root)) {
|
|
71
|
+
if (!map.has(rel)) await fs.unlink(path.join(root, ...rel.split('/')))
|
|
72
|
+
}
|
|
73
|
+
for (const [rel, content] of map) {
|
|
74
|
+
const target = path.join(root, ...rel.split('/'))
|
|
75
|
+
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
76
|
+
await fs.writeFile(target, content)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 加密整棵明文树 → 密文树(每文件一个 age 密文;删除明文已消失的密文)。
|
|
82
|
+
* @param {string} plainRoot - 明文树根。
|
|
83
|
+
* @param {string} encRoot - 密文树根。
|
|
84
|
+
* @param {object} deps - {run, ageBin, recipient, timeoutMs}。
|
|
85
|
+
* @returns {Promise<number>} 加密文件数。
|
|
86
|
+
*/
|
|
87
|
+
export async function encryptTree(plainRoot, encRoot, deps) {
|
|
88
|
+
const plainFiles = await listRelFiles(plainRoot)
|
|
89
|
+
const expected = new Set(plainFiles.map(rel => `${rel}${ENC_EXT}`))
|
|
90
|
+
for (const rel of await listRelFiles(encRoot)) {
|
|
91
|
+
if (!expected.has(rel)) await fs.unlink(path.join(encRoot, ...rel.split('/')))
|
|
92
|
+
}
|
|
93
|
+
for (const rel of plainFiles) {
|
|
94
|
+
await fs.mkdir(encRoot, { recursive: true })
|
|
95
|
+
const outPath = path.join(encRoot, ...`${rel}${ENC_EXT}`.split('/'))
|
|
96
|
+
await fs.mkdir(path.dirname(outPath), { recursive: true })
|
|
97
|
+
await ageEncrypt(deps.run, {
|
|
98
|
+
ageBin: deps.ageBin,
|
|
99
|
+
recipient: deps.recipient,
|
|
100
|
+
inPath: path.join(plainRoot, ...rel.split('/')),
|
|
101
|
+
outPath,
|
|
102
|
+
timeoutMs: deps.timeoutMs,
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
return plainFiles.length
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 解密整棵密文树 → 明文 Map<rel, Buffer>(只读 .age 文件,其余跳过)。
|
|
110
|
+
* @param {string} encRoot - 密文树根。
|
|
111
|
+
* @param {object} deps - {run, ageBin, identity, timeoutMs}。
|
|
112
|
+
* @returns {Promise<Map<string, Buffer>>} 明文相对路径 → 内容。
|
|
113
|
+
*/
|
|
114
|
+
export async function decryptTree(encRoot, deps) {
|
|
115
|
+
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-session-sync-dec-'))
|
|
116
|
+
try {
|
|
117
|
+
const map = new Map()
|
|
118
|
+
let index = 0
|
|
119
|
+
for (const rel of await listRelFiles(encRoot)) {
|
|
120
|
+
if (!rel.endsWith(ENC_EXT)) continue
|
|
121
|
+
const inPath = path.join(encRoot, ...rel.split('/'))
|
|
122
|
+
const outPath = path.join(tmp, `out-${index}`)
|
|
123
|
+
await ageDecrypt(deps.run, {
|
|
124
|
+
ageBin: deps.ageBin,
|
|
125
|
+
identity: deps.identity,
|
|
126
|
+
inPath,
|
|
127
|
+
outPath,
|
|
128
|
+
timeoutMs: deps.timeoutMs,
|
|
129
|
+
})
|
|
130
|
+
map.set(rel.slice(0, -ENC_EXT.length), await fs.readFile(outPath))
|
|
131
|
+
index += 1
|
|
132
|
+
}
|
|
133
|
+
return map
|
|
134
|
+
} finally {
|
|
135
|
+
await fs.rm(tmp, { recursive: true, force: true })
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 明文三方合并(复用 lib/merge.mjs 的 classifyPath 语义):
|
|
141
|
+
* 以 ours 为底,theirs-only 采纳远端;append-both/diverged 保留 ours + 把 theirs
|
|
142
|
+
* 写为 fork 文件。返回合并后整树与计数。
|
|
143
|
+
* @param {Map<string, Buffer>} base - 合并基点树。
|
|
144
|
+
* @param {Map<string, Buffer>} ours - 本地树。
|
|
145
|
+
* @param {Map<string, Buffer>} theirs - 远端树。
|
|
146
|
+
* @param {string} stamp - fork 文件名 UTC 时间戳(yyyyMMddHHmmss)。
|
|
147
|
+
* @param {string} deviceShort - 设备短 id(fork 归属)。
|
|
148
|
+
* @returns {{merged: Map<string, Buffer>, forks: string[], adopted: number, appended: number, diverged: number}}
|
|
149
|
+
*/
|
|
150
|
+
export function mergeTrees(base, ours, theirs, stamp, deviceShort) {
|
|
151
|
+
const merged = new Map(ours)
|
|
152
|
+
const forks = []
|
|
153
|
+
let adopted = 0
|
|
154
|
+
let appended = 0
|
|
155
|
+
let diverged = 0
|
|
156
|
+
const keys = new Set([...base.keys(), ...ours.keys(), ...theirs.keys()])
|
|
157
|
+
for (const rel of keys) {
|
|
158
|
+
const verdict = classifyPath(base.get(rel), ours.get(rel), theirs.get(rel))
|
|
159
|
+
if (verdict.kind === MERGE_KINDS.THEIRS_ONLY) {
|
|
160
|
+
merged.set(rel, theirs.get(rel))
|
|
161
|
+
adopted += 1
|
|
162
|
+
} else if (verdict.forkTheirs) {
|
|
163
|
+
const forkRel = path.posix.join(path.posix.dirname(rel), forkFileName(path.posix.basename(rel), stamp, deviceShort))
|
|
164
|
+
merged.set(forkRel, theirs.get(rel))
|
|
165
|
+
forks.push(forkRel)
|
|
166
|
+
if (verdict.kind === MERGE_KINDS.APPEND_BOTH) appended += 1
|
|
167
|
+
else diverged += 1
|
|
168
|
+
}
|
|
169
|
+
// identical / ours-only:保留 ours(已在 merged 中)。
|
|
170
|
+
}
|
|
171
|
+
return { merged, forks, adopted, appended, diverged }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* age 加密的 git 传输后端:对会话镜像内容加密后再推、解密后再合并。
|
|
176
|
+
* 与 SyncEngine 同 surface(status/push/pull + deviceId setter),可作为引擎
|
|
177
|
+
* 直接交给命令/工具/自动模式;无 age 时内部降级为明文 SyncEngine。
|
|
178
|
+
*/
|
|
179
|
+
export class EncryptedBackend {
|
|
180
|
+
/** @type {import('./git.mjs').GitBackend} */
|
|
181
|
+
#git
|
|
182
|
+
/** @type {SyncEngine} 明文降级引擎(无 age / 缺配置时复用)。 */
|
|
183
|
+
#plain
|
|
184
|
+
/** @type {(args: string[], opts?: object) => Promise<{code: number, stdout: string|Buffer, stderr: string}>} age runner。 */
|
|
185
|
+
#run
|
|
186
|
+
/** @type {string} */
|
|
187
|
+
#ageBin
|
|
188
|
+
/** @type {string} */
|
|
189
|
+
#recipient
|
|
190
|
+
/** @type {string} */
|
|
191
|
+
#identity
|
|
192
|
+
/** @type {number} */
|
|
193
|
+
#timeoutMs
|
|
194
|
+
/** @type {string} */
|
|
195
|
+
#repoDir
|
|
196
|
+
/** @type {string} */
|
|
197
|
+
#sessionRoot
|
|
198
|
+
/** @type {string} */
|
|
199
|
+
#remote
|
|
200
|
+
/** @type {string} */
|
|
201
|
+
#branch
|
|
202
|
+
/** @type {string} */
|
|
203
|
+
#deviceId
|
|
204
|
+
/** @type {(patch: object) => void} */
|
|
205
|
+
#reportMeta
|
|
206
|
+
/** @type {(message: string) => void} */
|
|
207
|
+
#reportError
|
|
208
|
+
/** @type {(forkRelPaths: string[]) => void} */
|
|
209
|
+
#onForks
|
|
210
|
+
/** @type {{debug: Function, info: Function, warn: Function, error: Function}} */
|
|
211
|
+
#logger
|
|
212
|
+
/** @type {string[]} */
|
|
213
|
+
#warnings = []
|
|
214
|
+
/** @type {Promise<{mode: string, warnings: string[]}>|undefined} 惰性探测结果。 */
|
|
215
|
+
#ready
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* @param {object} deps - {git, sessionRoot, repoDir, remote, branch, deviceId, reportMeta, reportError, onForks, logger, run, ageBin, ageRecipient, ageIdentity, timeoutMs}。
|
|
219
|
+
*/
|
|
220
|
+
constructor(deps) {
|
|
221
|
+
this.#git = deps.git
|
|
222
|
+
this.#run = deps.run
|
|
223
|
+
this.#ageBin = deps.ageBin
|
|
224
|
+
this.#recipient = deps.ageRecipient
|
|
225
|
+
this.#identity = deps.ageIdentity
|
|
226
|
+
this.#timeoutMs = deps.timeoutMs
|
|
227
|
+
this.#repoDir = deps.repoDir
|
|
228
|
+
this.#sessionRoot = deps.sessionRoot
|
|
229
|
+
this.#remote = deps.remote
|
|
230
|
+
this.#branch = deps.branch
|
|
231
|
+
this.#deviceId = deps.deviceId ?? 'pending'
|
|
232
|
+
this.#reportMeta = deps.reportMeta
|
|
233
|
+
this.#reportError = deps.reportError
|
|
234
|
+
this.#onForks = deps.onForks
|
|
235
|
+
this.#logger = deps.logger
|
|
236
|
+
this.#plain = new SyncEngine({
|
|
237
|
+
git: deps.git,
|
|
238
|
+
sessionRoot: deps.sessionRoot,
|
|
239
|
+
repoDir: deps.repoDir,
|
|
240
|
+
remote: deps.remote,
|
|
241
|
+
branch: deps.branch,
|
|
242
|
+
deviceId: deps.deviceId ?? 'pending',
|
|
243
|
+
reportMeta: deps.reportMeta,
|
|
244
|
+
reportError: deps.reportError,
|
|
245
|
+
onForks: deps.onForks,
|
|
246
|
+
logger: deps.logger,
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** 设备 id(fork 归属;同步转发给明文降级引擎)。 */
|
|
251
|
+
set deviceId(value) {
|
|
252
|
+
this.#deviceId = value
|
|
253
|
+
this.#plain.deviceId = value
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 设备短 id(fork 文件名后缀,≤8 位小写十六进制)。 */
|
|
257
|
+
get deviceShort() {
|
|
258
|
+
return this.#deviceId.replaceAll('-', '').slice(0, 8).toLowerCase() || 'unknown'
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 惰性探测并解析传输模式(首次操作触发,结果缓存)。
|
|
263
|
+
* @returns {Promise<{mode: string, warnings: string[]}>}
|
|
264
|
+
*/
|
|
265
|
+
probeMode() {
|
|
266
|
+
if (this.#ready === undefined) {
|
|
267
|
+
this.#ready = (async () => {
|
|
268
|
+
const ageBin = await detectAge(this.#run, this.#ageBin, { timeoutMs: this.#timeoutMs })
|
|
269
|
+
const selection = selectEncryptionMode({
|
|
270
|
+
backend: BACKENDS.ENCRYPTED,
|
|
271
|
+
ageAvailable: ageBin !== null,
|
|
272
|
+
ageRecipient: this.#recipient,
|
|
273
|
+
ageIdentity: this.#identity,
|
|
274
|
+
})
|
|
275
|
+
this.#warnings = selection.warnings
|
|
276
|
+
for (const warning of selection.warnings) {
|
|
277
|
+
this.#logger.warn(`session-sync encrypted backend degraded: ${warning}`)
|
|
278
|
+
}
|
|
279
|
+
return selection
|
|
280
|
+
})()
|
|
281
|
+
}
|
|
282
|
+
return this.#ready
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 串行执行一次加密路径操作(同仓库互斥;明文降级由 SyncEngine 自行串行)。 */
|
|
286
|
+
#schedule(fn) {
|
|
287
|
+
return this.#git.schedule(fn)
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 失败包装:脱敏 → reportError → 结构化错误结果(warnings 一并携带)。 */
|
|
291
|
+
#fail(error) {
|
|
292
|
+
const message = redactText(messageOf(error))
|
|
293
|
+
this.#reportError(message)
|
|
294
|
+
this.#logger.warn(`sync failed: ${message}`)
|
|
295
|
+
return { ok: false, error: message, warnings: this.#warnings }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** remote 未配置时响亮失败(状态类操作不拦)。 */
|
|
299
|
+
#requireRemote() {
|
|
300
|
+
if (this.#remote === undefined || this.#remote.trim() === '') {
|
|
301
|
+
throw new Error('no sync remote configured — set config.remote (status/diff work without one)')
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** 镜像 sessionRoot → 明文工作树 sessions/(encrypted 后端不写 device.txt)。 */
|
|
306
|
+
async #mirrorOnly() {
|
|
307
|
+
return mirrorSessionRoot({
|
|
308
|
+
sessionRoot: this.#sessionRoot,
|
|
309
|
+
repoDir: this.#repoDir,
|
|
310
|
+
mirrorDir: MIRROR_DIR,
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** 确保 .gitignore(忽略明文 sessions/)与仓库就绪。 */
|
|
315
|
+
async #ensureEncryptedRepo() {
|
|
316
|
+
const gitignore = path.join(this.#repoDir, '.gitignore')
|
|
317
|
+
const content = Buffer.from(`${MIRROR_DIR}/\n`)
|
|
318
|
+
try {
|
|
319
|
+
const existing = await fs.readFile(gitignore)
|
|
320
|
+
if (!existing.equals(content)) await fs.writeFile(gitignore, content)
|
|
321
|
+
} catch {
|
|
322
|
+
await fs.writeFile(gitignore, content)
|
|
323
|
+
}
|
|
324
|
+
await this.#git.bootstrap()
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 加密明文 sessions/ → encrypted/(返回加密文件数)。 */
|
|
328
|
+
async #encryptMirror() {
|
|
329
|
+
const encRoot = path.join(this.#repoDir, ENC_DIR)
|
|
330
|
+
await fs.mkdir(encRoot, { recursive: true })
|
|
331
|
+
return encryptTree(path.join(this.#repoDir, MIRROR_DIR), encRoot, {
|
|
332
|
+
run: this.#run,
|
|
333
|
+
ageBin: this.#ageBin,
|
|
334
|
+
recipient: this.#recipient,
|
|
335
|
+
timeoutMs: this.#timeoutMs,
|
|
336
|
+
})
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** 明文工作树里的 fork 文件清单(sessions/ 前缀,排序)。 */
|
|
340
|
+
async #plainForkFiles() {
|
|
341
|
+
const files = await listRelFiles(path.join(this.#repoDir, MIRROR_DIR))
|
|
342
|
+
return files.filter(file => FORK_NAME_RE.test(file.split('/').at(-1) ?? '')).map(file => `${MIRROR_DIR}/${file}`).sort()
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 解密某提交的密文树为明文 Map<rel, Buffer>。
|
|
347
|
+
* @param {string} rev - 提交 sha 或引用名。
|
|
348
|
+
* @returns {Promise<Map<string, Buffer>>}
|
|
349
|
+
*/
|
|
350
|
+
async #treeAtRev(rev) {
|
|
351
|
+
const files = (await this.#git.listFilesAtRev(rev)).filter(rel => rel.startsWith(`${ENC_DIR}/`) && rel.endsWith(ENC_EXT))
|
|
352
|
+
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-session-sync-tree-'))
|
|
353
|
+
try {
|
|
354
|
+
const map = new Map()
|
|
355
|
+
let index = 0
|
|
356
|
+
for (const rel of files) {
|
|
357
|
+
const blob = await this.#git.readFileAtRev(rev, rel)
|
|
358
|
+
if (blob === undefined) continue
|
|
359
|
+
const inPath = path.join(tmp, `in-${index}${ENC_EXT}`)
|
|
360
|
+
const outPath = path.join(tmp, `out-${index}`)
|
|
361
|
+
await fs.writeFile(inPath, blob)
|
|
362
|
+
await ageDecrypt(this.#run, {
|
|
363
|
+
ageBin: this.#ageBin,
|
|
364
|
+
identity: this.#identity,
|
|
365
|
+
inPath,
|
|
366
|
+
outPath,
|
|
367
|
+
timeoutMs: this.#timeoutMs,
|
|
368
|
+
})
|
|
369
|
+
map.set(rel.slice(ENC_DIR.length + 1, -ENC_EXT.length), await fs.readFile(outPath))
|
|
370
|
+
index += 1
|
|
371
|
+
}
|
|
372
|
+
return map
|
|
373
|
+
} finally {
|
|
374
|
+
await fs.rm(tmp, { recursive: true, force: true })
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* 状态:先本地初始化 + 镜像(不提交),再收集 git 状态;fork 清单改从明文
|
|
380
|
+
* 树读取(密文树里的 fork 文件名带 .age 后缀,不是面向用户的形态)。
|
|
381
|
+
* @returns {Promise<object>}
|
|
382
|
+
*/
|
|
383
|
+
async status() {
|
|
384
|
+
const selection = await this.probeMode()
|
|
385
|
+
if (selection.mode === BACKEND_MODES.PLAINTEXT) {
|
|
386
|
+
return { ...(await this.#plain.status()), warnings: this.#warnings }
|
|
387
|
+
}
|
|
388
|
+
return this.#schedule(async () => {
|
|
389
|
+
try {
|
|
390
|
+
await fs.mkdir(this.#repoDir, { recursive: true })
|
|
391
|
+
await this.#ensureEncryptedRepo()
|
|
392
|
+
await this.#mirrorOnly()
|
|
393
|
+
} catch {
|
|
394
|
+
// 初始化/镜像失败不阻断状态:collectStatus 返回带 error 的快照。
|
|
395
|
+
}
|
|
396
|
+
const snapshot = await collectStatus(this.#git, { branch: this.#branch, remote: this.#remote ?? '' })
|
|
397
|
+
return { ...snapshot, forks: await this.#plainForkFiles(), warnings: this.#warnings }
|
|
398
|
+
})
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 推送:镜像 → 加密 → 提交 → push;被拒时拉取调和后重推一次。
|
|
403
|
+
* @param {object} [opts] - {signal?: AbortSignal}。
|
|
404
|
+
* @returns {Promise<object>}
|
|
405
|
+
*/
|
|
406
|
+
async push(opts = {}) {
|
|
407
|
+
const selection = await this.probeMode()
|
|
408
|
+
if (selection.mode === BACKEND_MODES.PLAINTEXT) {
|
|
409
|
+
return { ...(await this.#plain.push(opts)), warnings: this.#warnings }
|
|
410
|
+
}
|
|
411
|
+
return this.#schedule(async () => {
|
|
412
|
+
try {
|
|
413
|
+
this.#requireRemote()
|
|
414
|
+
await fs.mkdir(this.#repoDir, { recursive: true })
|
|
415
|
+
await this.#ensureEncryptedRepo()
|
|
416
|
+
const mirror = await this.#mirrorOnly()
|
|
417
|
+
await this.#encryptMirror()
|
|
418
|
+
await this.#git.commitAll('dsh-session-sync: push snapshot (encrypted)')
|
|
419
|
+
try {
|
|
420
|
+
await this.#git.push({ signal: opts.signal })
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (!(error instanceof SyncError && error.code === 'PUSH_REJECTED')) throw error
|
|
423
|
+
this.#logger.info('push rejected (remote moved); pulling and reconciling before one retry')
|
|
424
|
+
const pulled = await this.#pullInternal(opts)
|
|
425
|
+
if (!pulled.ok) throw error
|
|
426
|
+
await this.#git.push({ signal: opts.signal })
|
|
427
|
+
}
|
|
428
|
+
const head = await this.#git.headSha()
|
|
429
|
+
await this.#git.setRef(BASE_REF, head)
|
|
430
|
+
this.#reportMeta({ lastPushAt: Date.now(), lastPushHead: head })
|
|
431
|
+
this.#logger.info(`sync push ok (encrypted): head ${head ?? ''} (${mirror.mirrored} mirrored, ${mirror.deleted} deleted)`)
|
|
432
|
+
return {
|
|
433
|
+
ok: true,
|
|
434
|
+
pushed: true,
|
|
435
|
+
head,
|
|
436
|
+
mirrored: mirror.mirrored,
|
|
437
|
+
deleted: mirror.deleted.length,
|
|
438
|
+
remote: sanitizeRemote(this.#remote),
|
|
439
|
+
warnings: this.#warnings,
|
|
440
|
+
}
|
|
441
|
+
} catch (error) {
|
|
442
|
+
return this.#fail(error)
|
|
443
|
+
}
|
|
444
|
+
})
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* 拉取:本地提交检查点 → fetch → 明文三方合并 → 重新加密 → 提交。
|
|
449
|
+
* @param {object} [opts] - {signal?: AbortSignal}。
|
|
450
|
+
* @returns {Promise<object>}
|
|
451
|
+
*/
|
|
452
|
+
async pull(opts = {}) {
|
|
453
|
+
const selection = await this.probeMode()
|
|
454
|
+
if (selection.mode === BACKEND_MODES.PLAINTEXT) {
|
|
455
|
+
return { ...(await this.#plain.pull(opts)), warnings: this.#warnings }
|
|
456
|
+
}
|
|
457
|
+
return this.#schedule(async () => {
|
|
458
|
+
try {
|
|
459
|
+
this.#requireRemote()
|
|
460
|
+
await fs.mkdir(this.#repoDir, { recursive: true })
|
|
461
|
+
await this.#ensureEncryptedRepo()
|
|
462
|
+
await this.#mirrorOnly()
|
|
463
|
+
await this.#encryptMirror()
|
|
464
|
+
await this.#git.commitAll('dsh-session-sync: local checkpoint before pull (encrypted)')
|
|
465
|
+
return await this.#pullInternal(opts)
|
|
466
|
+
} catch (error) {
|
|
467
|
+
return this.#fail(error)
|
|
468
|
+
}
|
|
469
|
+
})
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* 拉取内部步骤(push 重试路径复用;前置已保证仓库存在且本地已提交)。
|
|
474
|
+
* @param {object} [opts] - {signal?: AbortSignal}。
|
|
475
|
+
* @returns {Promise<object>}
|
|
476
|
+
*/
|
|
477
|
+
async #pullInternal(opts = {}) {
|
|
478
|
+
const fetched = await this.#git.fetch({ signal: opts.signal })
|
|
479
|
+
if (!fetched) {
|
|
480
|
+
this.#reportMeta({ lastPullAt: Date.now() })
|
|
481
|
+
return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0, warnings: this.#warnings }
|
|
482
|
+
}
|
|
483
|
+
const head = await this.#git.headSha()
|
|
484
|
+
const remoteHead = await this.#git.remoteHeadSha()
|
|
485
|
+
if (remoteHead === undefined || head === remoteHead) {
|
|
486
|
+
this.#reportMeta({ lastPullAt: Date.now() })
|
|
487
|
+
return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0, warnings: this.#warnings }
|
|
488
|
+
}
|
|
489
|
+
if (await this.#git.countCommitsSafe(head, remoteHead) === 0) {
|
|
490
|
+
this.#reportMeta({ lastPullAt: Date.now() })
|
|
491
|
+
return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0, warnings: this.#warnings }
|
|
492
|
+
}
|
|
493
|
+
// 三方合并基点:最近一次已调和的远端头(自持引用);首次同步无基点 → 空树
|
|
494
|
+
// (与 git 的 unrelated histories 语义一致:全部为 theirs-only 采纳)。
|
|
495
|
+
const baseHead = (await this.#git.refSha(BASE_REF)) ?? (await this.#git.mergeBaseOf(head, remoteHead))
|
|
496
|
+
const ours = await readTree(path.join(this.#repoDir, MIRROR_DIR))
|
|
497
|
+
const base = baseHead === undefined ? new Map() : await this.#treeAtRev(baseHead)
|
|
498
|
+
const theirs = await this.#treeAtRev(remoteHead)
|
|
499
|
+
const stamp = new Date().toISOString().replace(/[-:T]/gu, '').slice(0, 14)
|
|
500
|
+
const { merged, forks: rawForks, adopted, appended, diverged } = mergeTrees(base, ours, theirs, stamp, this.deviceShort)
|
|
501
|
+
// fork 路径统一加 sessions/ 前缀,与 git 后端的 ls-files 约定一致(handleForks
|
|
502
|
+
// 与展示都依赖该前缀)。
|
|
503
|
+
const forks = rawForks.map(rel => `${MIRROR_DIR}/${rel}`)
|
|
504
|
+
await writeTree(path.join(this.#repoDir, MIRROR_DIR), merged)
|
|
505
|
+
await this.#encryptMirror()
|
|
506
|
+
const newHead = await this.#git.commitAll('dsh-session-sync: pull merge (encrypted)')
|
|
507
|
+
await this.#git.setRef(BASE_REF, remoteHead)
|
|
508
|
+
this.#reportMeta({ lastPullAt: Date.now() })
|
|
509
|
+
this.#logger.info(`sync pull ok (encrypted): merged remote head ${remoteHead} → ${newHead ?? ''} (${appended} appended-both, ${diverged} diverged, ${forks.length} forks)`)
|
|
510
|
+
if (forks.length > 0) this.#onForks(forks)
|
|
511
|
+
return {
|
|
512
|
+
ok: true,
|
|
513
|
+
pulled: true,
|
|
514
|
+
merged: true,
|
|
515
|
+
adopted,
|
|
516
|
+
appended,
|
|
517
|
+
diverged,
|
|
518
|
+
forks,
|
|
519
|
+
head: newHead ?? undefined,
|
|
520
|
+
warnings: this.#warnings,
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
package/lib/errors.mjs
CHANGED
|
@@ -29,14 +29,14 @@ export function badConfig(message) {
|
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
|
-
* 配置的 backend
|
|
32
|
+
* 配置的 backend 尚未实现(对象存储等预留面)。
|
|
33
33
|
* @param {unknown} backend - 配置值。
|
|
34
34
|
* @returns {SyncError} code=BACKEND_UNSUPPORTED。
|
|
35
35
|
*/
|
|
36
36
|
export function backendUnsupported(backend) {
|
|
37
37
|
return new SyncError(
|
|
38
38
|
ERROR_CODES.BACKEND_UNSUPPORTED,
|
|
39
|
-
`sync backend ${JSON.stringify(backend)} is not implemented (
|
|
39
|
+
`sync backend ${JSON.stringify(backend)} is not implemented (available: git, encrypted; reserved: object-storage; keys never enter the repo)`,
|
|
40
40
|
{ backend },
|
|
41
41
|
)
|
|
42
42
|
}
|
|
@@ -70,6 +70,16 @@ export function pushRejected(message) {
|
|
|
70
70
|
return new SyncError(ERROR_CODES.PUSH_REJECTED, `git push rejected (never force-pushed): ${message}`)
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/**
|
|
74
|
+
* age 加解密失败(encrypted 后端操作期错误;resolve 期缺 age 走降级而非抛错)。
|
|
75
|
+
* @param {string} operation - 失败阶段(encrypt|decrypt|detect)。
|
|
76
|
+
* @param {string} message - 失败说明(含 exit code/stderr 摘要)。
|
|
77
|
+
* @returns {SyncError} code=AGE_FAILED。
|
|
78
|
+
*/
|
|
79
|
+
export function ageFailed(operation, message) {
|
|
80
|
+
return new SyncError(ERROR_CODES.AGE_FAILED, `age ${operation} failed: ${message}`, { operation })
|
|
81
|
+
}
|
|
82
|
+
|
|
73
83
|
/**
|
|
74
84
|
* 确认门拒绝/无回答者(失败关闭)。
|
|
75
85
|
* @param {string} reason - 拒绝或不可用原因。
|
package/lib/git.mjs
CHANGED
|
@@ -33,6 +33,8 @@ export const ALLOWED_VERBS = new Set([
|
|
|
33
33
|
'show',
|
|
34
34
|
'checkout',
|
|
35
35
|
'ls-files',
|
|
36
|
+
'ls-tree',
|
|
37
|
+
'update-ref',
|
|
36
38
|
'status',
|
|
37
39
|
])
|
|
38
40
|
|
|
@@ -197,6 +199,18 @@ export class GitBackend {
|
|
|
197
199
|
return sha === '' ? undefined : sha
|
|
198
200
|
}
|
|
199
201
|
|
|
202
|
+
/** 任意引用 sha;不存在为 undefined。 */
|
|
203
|
+
async refSha(ref) {
|
|
204
|
+
const out = await this.#maybe(['rev-parse', '--verify', ref])
|
|
205
|
+
const sha = out === null ? '' : String(out.stdout).trim()
|
|
206
|
+
return sha === '' ? undefined : sha
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** 移动一个引用指向某提交(插件自有 refs/dsh-sync/ 命名空间;不触工作树)。 */
|
|
210
|
+
async setRef(ref, sha) {
|
|
211
|
+
await this.#must(['update-ref', ref, sha])
|
|
212
|
+
}
|
|
213
|
+
|
|
200
214
|
/** 两提交的合并基点 sha;无公共祖先为 undefined。 */
|
|
201
215
|
async mergeBaseOf(left, right) {
|
|
202
216
|
const out = await this.#maybe(['merge-base', left, right])
|
|
@@ -368,6 +382,30 @@ export class GitBackend {
|
|
|
368
382
|
return String(out.stdout).split('\n').filter(line => line.length > 0)
|
|
369
383
|
}
|
|
370
384
|
|
|
385
|
+
/**
|
|
386
|
+
* 某提交下全部已跟踪文件(ls-tree -r --name-only;encrypted 后端读取
|
|
387
|
+
* 远端/基点提交的密文树用)。只读、不触工作树。
|
|
388
|
+
* @param {string} rev - 提交 sha 或引用名。
|
|
389
|
+
* @returns {Promise<string[]>} 仓库相对路径清单(空提交/不可解析为空数组)。
|
|
390
|
+
*/
|
|
391
|
+
async listFilesAtRev(rev) {
|
|
392
|
+
const out = await this.#maybe(['ls-tree', '-r', '--name-only', rev])
|
|
393
|
+
if (out === null) return []
|
|
394
|
+
return String(out.stdout).split('\n').filter(line => line.length > 0)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* 读某提交下单文件 blob 的原始字节(cat-file blob <rev>:<rel>)。
|
|
399
|
+
* @param {string} rev - 提交 sha 或引用名。
|
|
400
|
+
* @param {string} rel - 仓库相对路径。
|
|
401
|
+
* @returns {Promise<Buffer|undefined>} 内容;路径/提交缺失为 undefined。
|
|
402
|
+
*/
|
|
403
|
+
async readFileAtRev(rev, rel) {
|
|
404
|
+
const out = await this.#maybe(['cat-file', 'blob', `${rev}:${rel}`], { binary: true })
|
|
405
|
+
if (out === null) return undefined
|
|
406
|
+
return Buffer.isBuffer(out.stdout) ? out.stdout : Buffer.from(String(out.stdout))
|
|
407
|
+
}
|
|
408
|
+
|
|
371
409
|
/** 两提交的路径差异统计(diff --stat)。 */
|
|
372
410
|
async diffStat(left, right) {
|
|
373
411
|
const out = await this.#maybe(['diff', '--stat', left, right])
|
package/lib/render.mjs
CHANGED
|
@@ -37,6 +37,7 @@ export function renderStatus(status) {
|
|
|
37
37
|
lines.push(` last commits:\n${status.lastCommits.map(line => ` ${line}`).join('\n')}`)
|
|
38
38
|
}
|
|
39
39
|
if (status.error !== undefined) lines.push(` last error: ${status.error}`)
|
|
40
|
+
for (const warning of (status.warnings ?? [])) lines.push(` warning: ${warning}`)
|
|
40
41
|
return lines.join('\n')
|
|
41
42
|
}
|
|
42
43
|
|
|
@@ -61,7 +62,7 @@ export function renderDiff(status) {
|
|
|
61
62
|
|
|
62
63
|
/**
|
|
63
64
|
* pull 结果文本。
|
|
64
|
-
* @param {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string}} result - pull 产物。
|
|
65
|
+
* @param {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string, warnings?: string[]}} result - pull 产物。
|
|
65
66
|
* @returns {string}
|
|
66
67
|
*/
|
|
67
68
|
export function renderPull(result) {
|
|
@@ -77,22 +78,25 @@ export function renderPull(result) {
|
|
|
77
78
|
if ((result.diverged ?? 0) > 0) lines.push(` diverged in ${result.diverged} file(s) (non-append rewrite): local version kept, remote version preserved as fork file(s) — inspect before continuing`)
|
|
78
79
|
for (const fork of (result.forks ?? []).slice(0, 20)) lines.push(` fork ${fork}`)
|
|
79
80
|
if ((result.forks ?? []).length > 20) lines.push(` … ${result.forks.length - 20} more`)
|
|
81
|
+
for (const warning of (result.warnings ?? [])) lines.push(` warning: ${warning}`)
|
|
80
82
|
return lines.join('\n')
|
|
81
83
|
}
|
|
82
84
|
|
|
83
85
|
/**
|
|
84
86
|
* push 结果文本。
|
|
85
|
-
* @param {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string}} result - push 产物。
|
|
87
|
+
* @param {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string, warnings?: string[]}} result - push 产物。
|
|
86
88
|
* @returns {string}
|
|
87
89
|
*/
|
|
88
90
|
export function renderPush(result) {
|
|
89
91
|
if (!result.ok) return `sync: push failed: ${result.error ?? 'unknown error'}`
|
|
90
92
|
if (!result.pushed) return 'sync: push ok — nothing new to push (mirror already committed and remote up to date)'
|
|
91
|
-
|
|
93
|
+
const lines = [
|
|
92
94
|
'sync: push ok',
|
|
93
95
|
` mirrored ${result.mirrored ?? 0} file(s)${(result.deleted ?? 0) > 0 ? `, deleted ${result.deleted} (removed locally)` : ''}`,
|
|
94
96
|
` pushed to ${result.remote ?? 'remote'} → head ${result.head ?? ''}`,
|
|
95
|
-
]
|
|
97
|
+
]
|
|
98
|
+
for (const warning of (result.warnings ?? [])) lines.push(` warning: ${warning}`)
|
|
99
|
+
return lines.join('\n')
|
|
96
100
|
}
|
|
97
101
|
|
|
98
102
|
/**
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-session-sync",
|
|
3
3
|
"description": "Cross-device sync for DeepSeek Harness sessions: a dedicated git mirror of the session store, append-only three-way merge with keep-both + fork conflict resolution, /sync command, sync_pull/sync_push/sync_status tools, and configurable auto push/pull",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/PerryLink/dsh-session-sync.git"
|