@twinsearth/timemachine-dsh-plugin 0.0.0-stage → 0.1.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/CHANGELOG.md +64 -0
- package/LICENSE +21 -0
- package/README.md +225 -2
- package/cordis.patch.yml +28 -0
- package/docs/ARCHITECTURE.md +172 -0
- package/docs/REQUIREMENTS.md +82 -0
- package/docs/TESTPLAN.md +164 -0
- package/lib/client.js +913 -0
- package/lib/index.js +5 -0
- package/package.json +48 -4
- package/plugin.json +9 -0
- package/scripts/host-menu-patch.mjs +274 -0
- package/src/archive/tar.mjs +138 -0
- package/src/archive/zstd.mjs +206 -0
- package/src/plugin.mjs +213 -0
- package/src/plugins.mjs +355 -0
- package/src/point.mjs +671 -0
- package/src/registry.mjs +120 -0
- package/src/restore.mjs +777 -0
- package/src/scan.mjs +244 -0
- package/src/service.mjs +448 -0
- package/src/session-log.mjs +123 -0
- package/src/util/fs.mjs +92 -0
- package/src/util/paths.mjs +82 -0
package/src/point.mjs
ADDED
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restore-point archives.
|
|
3
|
+
*
|
|
4
|
+
* A point is one self-contained `.tar.zst`:
|
|
5
|
+
*
|
|
6
|
+
* manifest.json file list, digests, product metadata
|
|
7
|
+
* RESTORE-POINT.json metadata the UI and importer read first
|
|
8
|
+
* README.txt human inspection instructions
|
|
9
|
+
* sessions/<project-key>/<session-id>/session.v4.jsonl.zstd
|
|
10
|
+
* sessions/<project-key>/<session-id>/RESTORE-GUIDE.json
|
|
11
|
+
* sessions/<project-key>/<session-id>/RESTORE-GUIDE.md
|
|
12
|
+
* attachments/<version>/objects/... attachment objects
|
|
13
|
+
* profile/... DSH profile configuration
|
|
14
|
+
* state/... DSH state JSON
|
|
15
|
+
* registry/workspace.json workspace registry snapshot
|
|
16
|
+
* plugin-packages/*.tgz only when the user asks to save them
|
|
17
|
+
*
|
|
18
|
+
* `manual/`, `auto/` and `imported/` are separate stores under the chosen root.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import zlib from 'node:zlib';
|
|
25
|
+
|
|
26
|
+
import { readTar, writeTar } from './archive/tar.mjs';
|
|
27
|
+
import { inspectSessionBuffer } from './session-log.mjs';
|
|
28
|
+
import { scanExclusions, scanHome } from './scan.mjs';
|
|
29
|
+
import { packPluginTarballs, readProfilePlugins, SELF_PLUGIN } from './plugins.mjs';
|
|
30
|
+
import { atomicWriteFile, ensureDir, formatBytes, isSafeArchiveName, readJson, sha256, stamp } from './util/fs.mjs';
|
|
31
|
+
import { encodeSegment, profileDir, projectKey, resolveDshHome } from './util/paths.mjs';
|
|
32
|
+
|
|
33
|
+
export const POINT_SCHEMA = 'twinsearth-timemachine-point/1';
|
|
34
|
+
export const MANIFEST_SCHEMA = 'twinsearth-timemachine-manifest/1';
|
|
35
|
+
export const GUIDE_SCHEMA = 'twinsearth-timemachine-guide/1';
|
|
36
|
+
export const SIDECAR_SCHEMA = 'twinsearth-timemachine-sidecar/1';
|
|
37
|
+
export const POINT_EXT = '.tar.zst';
|
|
38
|
+
export const WINDOWS_DEFAULT_ROOT = 'D:\\ToFuture';
|
|
39
|
+
|
|
40
|
+
export const MAX_SESSION_BYTES = 1024 * 1024 * 1024;
|
|
41
|
+
export const MAX_POINT_BYTES = 2.5 * 1024 * 1024 * 1024;
|
|
42
|
+
export const MAX_ARCHIVE_READ_BYTES = 3 * 1024 * 1024 * 1024;
|
|
43
|
+
|
|
44
|
+
export const CODES = Object.freeze({
|
|
45
|
+
ROOT_REQUIRED: 'TIMEMACHINE_ROOT_REQUIRED',
|
|
46
|
+
ROOT_UNWRITABLE: 'TIMEMACHINE_ROOT_UNWRITABLE',
|
|
47
|
+
NO_SESSION: 'TIMEMACHINE_NO_SESSION',
|
|
48
|
+
FILE_TOO_LARGE: 'TIMEMACHINE_FILE_TOO_LARGE',
|
|
49
|
+
TOTAL_TOO_LARGE: 'TIMEMACHINE_TOTAL_TOO_LARGE',
|
|
50
|
+
WRITE_FAILED: 'TIMEMACHINE_WRITE_FAILED',
|
|
51
|
+
ARCHIVE_INVALID: 'TIMEMACHINE_ARCHIVE_INVALID',
|
|
52
|
+
ARCHIVE_TOO_LARGE: 'TIMEMACHINE_ARCHIVE_TOO_LARGE',
|
|
53
|
+
IMPORT_FAILED: 'TIMEMACHINE_IMPORT_FAILED',
|
|
54
|
+
PROFILE_NOT_FOUND: 'TIMEMACHINE_PROFILE_NOT_FOUND',
|
|
55
|
+
PLUGIN_PACK_FAILED: 'TIMEMACHINE_PLUGIN_PACK_FAILED',
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
export function defaultRoot(platform = process.platform) {
|
|
59
|
+
return platform === 'win32' ? WINDOWS_DEFAULT_ROOT : '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function rootIsDefaultable(platform = process.platform) {
|
|
63
|
+
return platform === 'win32';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `''` means "not chosen"; Windows falls back to D:\ToFuture. */
|
|
67
|
+
export function resolveRoot(value, platform = process.platform) {
|
|
68
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
69
|
+
if (text === '') return defaultRoot(platform);
|
|
70
|
+
return path.resolve(text.replace(/^~(?=$|[\\/])/u, os.homedir()));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function categoryDir(root, kind) {
|
|
74
|
+
const folder = kind === 'auto' ? 'auto' : kind === 'imported' ? 'imported' : 'manual';
|
|
75
|
+
return path.join(root, folder);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function ensureWritableRoot(root) {
|
|
79
|
+
try {
|
|
80
|
+
fs.mkdirSync(root, { recursive: true });
|
|
81
|
+
const probe = path.join(root, `.timemachine-write-${process.pid}-${Date.now()}`);
|
|
82
|
+
fs.writeFileSync(probe, 'ok');
|
|
83
|
+
fs.rmSync(probe, { force: true });
|
|
84
|
+
return null;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return error instanceof Error ? error.message : String(error);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Archived sessions are excluded from the default `active` scope. */
|
|
91
|
+
export function selectSessions(sessions, scope) {
|
|
92
|
+
if (scope === 'all') return [...sessions];
|
|
93
|
+
if (scope === 'archived') return sessions.filter((row) => row.flags?.archived === true);
|
|
94
|
+
return sessions.filter((row) => row.flags?.archived !== true);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function workspaceFor(registry, session) {
|
|
98
|
+
const id = session.session_id;
|
|
99
|
+
for (const workspace of registry?.workspaces ?? []) {
|
|
100
|
+
if (workspace.sessionIds.includes(id)) {
|
|
101
|
+
return { id: workspace.id, path: workspace.path, title: workspace.title };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { id: null, path: session.header?.cwd ?? null, title: null };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function guideFor(input) {
|
|
108
|
+
return {
|
|
109
|
+
schema: GUIDE_SCHEMA,
|
|
110
|
+
session_id: input.session.session_id,
|
|
111
|
+
workspace_slug: input.session.project_key,
|
|
112
|
+
workspace_id: input.workspace.id,
|
|
113
|
+
workspace_path: input.workspace.path,
|
|
114
|
+
workspace_title: input.workspace.title,
|
|
115
|
+
source_machine: input.source_machine,
|
|
116
|
+
source_dsh_home: input.dsh_home,
|
|
117
|
+
created_at: input.created_at,
|
|
118
|
+
session_file: input.session_file,
|
|
119
|
+
size: input.size,
|
|
120
|
+
sha256: input.digest,
|
|
121
|
+
archived: input.session.flags?.archived === true,
|
|
122
|
+
pinned: input.session.flags?.pinned === true,
|
|
123
|
+
header: input.header,
|
|
124
|
+
restore_hint:
|
|
125
|
+
'DSH -> 通用设置 -> DSH 一键还原点(或左侧“时间机器 / 一键还原点”)-> 还原这份。' +
|
|
126
|
+
'还原会把本文件写回 sessions/<project-key>/<Session ID>/,并写入工作区注册表;显示工作区需要重启 DSH 客户端。',
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function guideMarkdown(guide) {
|
|
131
|
+
return [
|
|
132
|
+
`# 会话还原引导:${guide.session_id}`,
|
|
133
|
+
'',
|
|
134
|
+
`- 工作区:${guide.workspace_title ?? '(未命名)'} (${guide.workspace_id ?? '未注册'})`,
|
|
135
|
+
`- 工作区路径:${guide.workspace_path ?? '(未知)'}`,
|
|
136
|
+
`- 会话文件:${guide.session_file}`,
|
|
137
|
+
`- 大小:${formatBytes(guide.size)}`,
|
|
138
|
+
`- SHA-256:${guide.sha256}`,
|
|
139
|
+
`- 已归档:${guide.archived ? '是' : '否'}`,
|
|
140
|
+
`- 已置顶:${guide.pinned ? '是' : '否'}`,
|
|
141
|
+
`- 来源机器:${guide.source_machine}`,
|
|
142
|
+
`- 来源 DSH home:${guide.source_dsh_home}`,
|
|
143
|
+
`- 创建时间:${guide.created_at}`,
|
|
144
|
+
'',
|
|
145
|
+
'## 一键还原',
|
|
146
|
+
'',
|
|
147
|
+
'1. 打开 DSH 客户端,进入 通用设置 -> DSH 一键还原点。',
|
|
148
|
+
'2. 在列表中选择包含本会话的还原点,点击“还原”。',
|
|
149
|
+
'3. 还原完成后按提示重启 DSH 客户端;工作区与会话会自动出现在左侧。',
|
|
150
|
+
'',
|
|
151
|
+
'## 手工还原',
|
|
152
|
+
'',
|
|
153
|
+
'把 `session.v4.jsonl.zstd` 放到:',
|
|
154
|
+
'',
|
|
155
|
+
'```text',
|
|
156
|
+
`<DSH_HOME>/sessions/${guide.workspace_slug}/${encodeSegment(guide.session_id)}/session.v4.jsonl.zstd`,
|
|
157
|
+
'```',
|
|
158
|
+
'',
|
|
159
|
+
'并确保 `storages/workspace.json` 的对应工作区 `sessionIds` 包含本 Session ID。',
|
|
160
|
+
'',
|
|
161
|
+
].join('\n');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function safeReadSession(file) {
|
|
165
|
+
const stat = fs.statSync(file);
|
|
166
|
+
if (!stat.isFile()) return { ok: false, reason: 'not a regular file' };
|
|
167
|
+
if (stat.size > MAX_SESSION_BYTES) return { ok: false, reason: `session is ${stat.size} bytes, over the per-file ceiling`, size: stat.size };
|
|
168
|
+
return { ok: true, buffer: fs.readFileSync(file), size: stat.size };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Create one restore point.
|
|
173
|
+
* @param {{
|
|
174
|
+
* dshHome?: string, root: string, kind?: 'manual'|'auto', profile?: string,
|
|
175
|
+
* sessionScope?: 'active'|'all'|'archived', includeConfig?: boolean,
|
|
176
|
+
* includePlugins?: boolean, includeSessions?: boolean, includePluginPackages?: boolean,
|
|
177
|
+
* keep?: number, now?: Date, sourceMachine?: string, runner?: Function,
|
|
178
|
+
* onProgress?: (event: object) => void,
|
|
179
|
+
* }} input
|
|
180
|
+
*/
|
|
181
|
+
export async function createRestorePoint(input) {
|
|
182
|
+
const now = input.now ?? new Date();
|
|
183
|
+
const dshHome = resolveDshHome(input.dshHome);
|
|
184
|
+
const root = resolveRoot(input.root);
|
|
185
|
+
if (root === '') {
|
|
186
|
+
return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: 'macOS/Linux needs a folder chosen by the user; Windows defaults to D:\\ToFuture' };
|
|
187
|
+
}
|
|
188
|
+
const writable = ensureWritableRoot(root);
|
|
189
|
+
if (writable !== null) return { ok: false, reason_code: CODES.ROOT_UNWRITABLE, detail: `${root}: ${writable}` };
|
|
190
|
+
|
|
191
|
+
const kind = input.kind === 'auto' ? 'auto' : 'manual';
|
|
192
|
+
const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : 'desktop';
|
|
193
|
+
const includeSessions = input.includeSessions !== false;
|
|
194
|
+
const includeConfig = input.includeConfig !== false;
|
|
195
|
+
const includePlugins = input.includePlugins !== false;
|
|
196
|
+
const sessionScope = input.sessionScope === 'all' || input.sessionScope === 'archived' ? input.sessionScope : 'active';
|
|
197
|
+
const keep = Number.isSafeInteger(input.keep) && input.keep > 0 ? input.keep : 2;
|
|
198
|
+
const sourceMachine = input.sourceMachine ?? os.hostname();
|
|
199
|
+
const createdAt = now.toISOString();
|
|
200
|
+
|
|
201
|
+
const scan = scanHome({ dshHome, profile });
|
|
202
|
+
const selected = includeSessions ? selectSessions(scan.sessions, sessionScope) : [];
|
|
203
|
+
if (includeSessions && selected.length === 0) {
|
|
204
|
+
return { ok: false, reason_code: CODES.NO_SESSION, detail: `no ${sessionScope} session under ${dshHome}` };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const entries = [];
|
|
208
|
+
const files = [];
|
|
209
|
+
const guides = [];
|
|
210
|
+
let total = 0;
|
|
211
|
+
const add = (rel, data, mtimeMs, meta = {}) => {
|
|
212
|
+
if (!isSafeArchiveName(rel)) throw new Error(`unsafe archive entry name ${JSON.stringify(rel)}`);
|
|
213
|
+
total += data.length;
|
|
214
|
+
if (total > MAX_POINT_BYTES) {
|
|
215
|
+
const error = new Error(`restore point exceeds ${MAX_POINT_BYTES} bytes`);
|
|
216
|
+
error.code = CODES.TOTAL_TOO_LARGE;
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
entries.push({ name: rel, data, mtimeMs });
|
|
220
|
+
files.push({
|
|
221
|
+
rel,
|
|
222
|
+
kind: meta.kind ?? 'file',
|
|
223
|
+
scope: meta.scope ?? null,
|
|
224
|
+
reason: meta.reason ?? null,
|
|
225
|
+
size: data.length,
|
|
226
|
+
sha256: sha256(data),
|
|
227
|
+
session_id: meta.session_id ?? null,
|
|
228
|
+
attachment_id: meta.attachment_id ?? null,
|
|
229
|
+
flags: meta.flags ?? null,
|
|
230
|
+
mtime_ms: mtimeMs,
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
for (const session of selected) {
|
|
236
|
+
const read = safeReadSession(session.file);
|
|
237
|
+
if (!read.ok) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
reason_code: read.reason?.includes('ceiling') === true ? CODES.FILE_TOO_LARGE : CODES.WRITE_FAILED,
|
|
241
|
+
detail: `${session.rel}: ${read.reason}`,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const inspected = inspectSessionBuffer(read.buffer);
|
|
245
|
+
const header = inspected.header ?? session.header;
|
|
246
|
+
if (!inspected.ok) {
|
|
247
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${session.rel}: ${inspected.reason}` };
|
|
248
|
+
}
|
|
249
|
+
const cwd = typeof header?.cwd === 'string' && header.cwd !== '' ? header.cwd : (session.cwd ?? '');
|
|
250
|
+
if (cwd === '') return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${session.rel}: session header has no cwd` };
|
|
251
|
+
const project = projectKey(cwd);
|
|
252
|
+
const inner = encodeSegment(session.session_id);
|
|
253
|
+
const sessionRel = `sessions/${project}/${inner}/session.v4.jsonl.zstd`;
|
|
254
|
+
const digest = sha256(read.buffer);
|
|
255
|
+
add(sessionRel, read.buffer, session.mtime_ms, {
|
|
256
|
+
kind: 'session',
|
|
257
|
+
scope: 'sessions',
|
|
258
|
+
reason: 'session log selected for the restore point',
|
|
259
|
+
session_id: session.session_id,
|
|
260
|
+
flags: session.flags ?? null,
|
|
261
|
+
});
|
|
262
|
+
const workspace = workspaceFor(scan.registry, session);
|
|
263
|
+
const guide = guideFor({
|
|
264
|
+
session,
|
|
265
|
+
workspace,
|
|
266
|
+
source_machine: sourceMachine,
|
|
267
|
+
dsh_home: dshHome,
|
|
268
|
+
created_at: createdAt,
|
|
269
|
+
session_file: sessionRel,
|
|
270
|
+
size: read.size,
|
|
271
|
+
digest,
|
|
272
|
+
header,
|
|
273
|
+
});
|
|
274
|
+
const guideJsonRel = `sessions/${project}/${inner}/RESTORE-GUIDE.json`;
|
|
275
|
+
const guideMdRel = `sessions/${project}/${inner}/RESTORE-GUIDE.md`;
|
|
276
|
+
add(guideJsonRel, Buffer.from(`${JSON.stringify(guide, null, 2)}\n`, 'utf8'), now.getTime(), {
|
|
277
|
+
kind: 'guide', scope: 'sessions', session_id: session.session_id,
|
|
278
|
+
});
|
|
279
|
+
add(guideMdRel, Buffer.from(guideMarkdown(guide), 'utf8'), now.getTime(), {
|
|
280
|
+
kind: 'guide', scope: 'sessions', session_id: session.session_id,
|
|
281
|
+
});
|
|
282
|
+
guides.push({ session_id: session.session_id, rel: guideJsonRel, markdown: guideMdRel });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (includeSessions && input.includeAttachments !== false) {
|
|
286
|
+
for (const attachment of scan.attachments) {
|
|
287
|
+
if (attachment.size > MAX_SESSION_BYTES) continue;
|
|
288
|
+
const buffer = fs.readFileSync(attachment.file);
|
|
289
|
+
add(attachment.rel, buffer, attachment.mtime_ms, {
|
|
290
|
+
kind: 'attachment',
|
|
291
|
+
scope: 'attachments',
|
|
292
|
+
reason: 'attachment object in the DSH attachment store',
|
|
293
|
+
attachment_id: attachment.attachment_id,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (includeConfig) {
|
|
299
|
+
for (const row of scan.config) {
|
|
300
|
+
const buffer = fs.readFileSync(row.file);
|
|
301
|
+
add(row.rel, buffer, row.mtime_ms, {
|
|
302
|
+
kind: row.kind, scope: row.scope, reason: row.reason,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
if (scan.registry.ok) {
|
|
306
|
+
const registryFile = path.join(dshHome, 'storages', 'workspace.json');
|
|
307
|
+
const buffer = fs.readFileSync(registryFile);
|
|
308
|
+
add('registry/workspace.json', buffer, fs.statSync(registryFile).mtimeMs, {
|
|
309
|
+
kind: 'registry', scope: 'registry', reason: 'workspace and archived-session registry',
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const profileInfo = readProfilePlugins({ dshHome, profile });
|
|
315
|
+
if (!profileInfo.ok) return { ok: false, reason_code: CODES.PROFILE_NOT_FOUND, detail: profileInfo.detail };
|
|
316
|
+
const plugins = includePlugins ? profileInfo.plugins : [];
|
|
317
|
+
const allPlugins = profileInfo.all_plugins.filter((row) => row.kind !== 'self');
|
|
318
|
+
const packages = {};
|
|
319
|
+
if (includePlugins && input.includePluginPackages === true && plugins.length > 0) {
|
|
320
|
+
const temp = path.join(root, `.pack-${process.pid}-${Date.now()}`);
|
|
321
|
+
try {
|
|
322
|
+
const packed = await packPluginTarballs({
|
|
323
|
+
profileDir: profileDir(dshHome, profile),
|
|
324
|
+
plugins,
|
|
325
|
+
destination: temp,
|
|
326
|
+
runner: input.runner,
|
|
327
|
+
});
|
|
328
|
+
for (const file of packed.files) {
|
|
329
|
+
const buffer = fs.readFileSync(file.file);
|
|
330
|
+
const rel = `plugin-packages/${path.basename(file.file)}`;
|
|
331
|
+
add(rel, buffer, now.getTime(), {
|
|
332
|
+
kind: 'plugin_package', scope: 'plugins', reason: `offline package for ${file.name}`,
|
|
333
|
+
});
|
|
334
|
+
packages[file.name] = rel;
|
|
335
|
+
}
|
|
336
|
+
if (!packed.ok && packed.files.length === 0) {
|
|
337
|
+
return { ok: false, reason_code: CODES.PLUGIN_PACK_FAILED, detail: `npm pack failed for ${packed.failed.map((row) => row.name).join(', ')}` };
|
|
338
|
+
}
|
|
339
|
+
} finally {
|
|
340
|
+
fs.rmSync(temp, { recursive: true, force: true });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const counts = {
|
|
345
|
+
sessions: files.filter((file) => file.kind === 'session').length,
|
|
346
|
+
attachments: files.filter((file) => file.kind === 'attachment').length,
|
|
347
|
+
config: files.filter((file) => file.kind === 'config').length,
|
|
348
|
+
state: files.filter((file) => file.kind === 'state').length,
|
|
349
|
+
registry: files.filter((file) => file.kind === 'registry').length,
|
|
350
|
+
plugins: plugins.length,
|
|
351
|
+
guides: guides.length,
|
|
352
|
+
};
|
|
353
|
+
const point = {
|
|
354
|
+
schema: POINT_SCHEMA,
|
|
355
|
+
kind,
|
|
356
|
+
created_at: createdAt,
|
|
357
|
+
source_machine: sourceMachine,
|
|
358
|
+
source_platform: process.platform,
|
|
359
|
+
source_dsh_home: dshHome,
|
|
360
|
+
profile,
|
|
361
|
+
session_scope: sessionScope,
|
|
362
|
+
options: {
|
|
363
|
+
include_config: includeConfig,
|
|
364
|
+
include_plugins: includePlugins,
|
|
365
|
+
include_sessions: includeSessions,
|
|
366
|
+
include_plugin_packages: input.includePluginPackages === true,
|
|
367
|
+
},
|
|
368
|
+
counts,
|
|
369
|
+
plugins,
|
|
370
|
+
all_plugins: allPlugins,
|
|
371
|
+
plugin_packages: Object.keys(packages),
|
|
372
|
+
plugin_package_files: packages,
|
|
373
|
+
workspaces: scan.registry.workspaces,
|
|
374
|
+
sessions: selected.map((session) => ({
|
|
375
|
+
session_id: session.session_id,
|
|
376
|
+
workspace_id: session.workspace_id,
|
|
377
|
+
workspace_path: session.workspace_path ?? session.header?.cwd ?? null,
|
|
378
|
+
workspace_title: session.workspace_title,
|
|
379
|
+
archived: session.flags?.archived === true,
|
|
380
|
+
pinned: session.flags?.pinned === true,
|
|
381
|
+
cwd: session.header?.cwd ?? null,
|
|
382
|
+
size: session.size,
|
|
383
|
+
})),
|
|
384
|
+
guides,
|
|
385
|
+
exclusions: scanExclusions(),
|
|
386
|
+
};
|
|
387
|
+
const manifest = {
|
|
388
|
+
schema: MANIFEST_SCHEMA,
|
|
389
|
+
created_at: createdAt,
|
|
390
|
+
dsh_home: dshHome,
|
|
391
|
+
profile,
|
|
392
|
+
scope: sessionScope,
|
|
393
|
+
counts,
|
|
394
|
+
files,
|
|
395
|
+
notes: [
|
|
396
|
+
'Plaintext tar + zstd. It contains session logs, attachments and DSH configuration.',
|
|
397
|
+
'Credentials and account material are excluded; see point.exclusions.',
|
|
398
|
+
'Extract with: zstd -d <file>.tar.zst && tar -xf <file>.tar',
|
|
399
|
+
'Every file digest is recorded here; restore verifies them before writing.',
|
|
400
|
+
],
|
|
401
|
+
restore_point: point,
|
|
402
|
+
};
|
|
403
|
+
const readme = [
|
|
404
|
+
'DSH 一键还原点 / DSH Time Machine restore point',
|
|
405
|
+
'',
|
|
406
|
+
`created_at : ${createdAt}`,
|
|
407
|
+
`kind : ${kind}`,
|
|
408
|
+
`source : ${sourceMachine} (${process.platform})`,
|
|
409
|
+
`dsh_home : ${dshHome}`,
|
|
410
|
+
`sessions : ${counts.sessions}`,
|
|
411
|
+
`attachments: ${counts.attachments}`,
|
|
412
|
+
`config : ${counts.config}`,
|
|
413
|
+
`state : ${counts.state}`,
|
|
414
|
+
`plugins : ${counts.plugins}`,
|
|
415
|
+
'',
|
|
416
|
+
'每个会话在 sessions/<project-key>/<Session ID>/ 下独立存放,并带有 RESTORE-GUIDE.json / .md。',
|
|
417
|
+
'在 DSH 中打开:通用设置 -> DSH 一键还原点,或左侧「时间机器 / 一键还原点」,选择本文件还原。',
|
|
418
|
+
'',
|
|
419
|
+
'Excluded on purpose:',
|
|
420
|
+
...point.exclusions.map((line) => `- ${line}`),
|
|
421
|
+
'',
|
|
422
|
+
].join('\n');
|
|
423
|
+
|
|
424
|
+
add('manifest.json', Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, 'utf8'), now.getTime(), { kind: 'manifest' });
|
|
425
|
+
add('README.txt', Buffer.from(readme, 'utf8'), now.getTime(), { kind: 'readme' });
|
|
426
|
+
add('RESTORE-POINT.json', Buffer.from(`${JSON.stringify(point, null, 2)}\n`, 'utf8'), now.getTime(), { kind: 'point' });
|
|
427
|
+
|
|
428
|
+
const tar = writeTar(entries);
|
|
429
|
+
const zst = zlib.zstdCompressSync(tar);
|
|
430
|
+
const folder = categoryDir(root, kind);
|
|
431
|
+
ensureDir(folder);
|
|
432
|
+
let file = path.join(folder, `restore-${stamp(now)}${POINT_EXT}`);
|
|
433
|
+
for (let n = 2; fs.existsSync(file); n += 1) {
|
|
434
|
+
file = path.join(folder, `restore-${stamp(now)}-${n}${POINT_EXT}`);
|
|
435
|
+
}
|
|
436
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
437
|
+
fs.writeFileSync(tmp, zst, { flag: 'wx' });
|
|
438
|
+
fs.renameSync(tmp, file);
|
|
439
|
+
const digest = sha256(zst);
|
|
440
|
+
writeSidecar(file, { point, counts, sha256: digest, bytes: zst.length });
|
|
441
|
+
const pruned = pruneCategory(folder, keep, file);
|
|
442
|
+
input.onProgress?.({ phase: 'created', file, bytes: zst.length });
|
|
443
|
+
return { ok: true, file, kind, bytes: zst.length, sha256: digest, point, counts, pruned };
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (error?.code === CODES.TOTAL_TOO_LARGE) return { ok: false, reason_code: error.code, detail: error.message };
|
|
446
|
+
return { ok: false, reason_code: CODES.WRITE_FAILED, detail: error instanceof Error ? error.message : String(error) };
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Keep only the newest `keep` files this module owns. */
|
|
451
|
+
export function pruneCategory(folder, keep, keepFile = null) {
|
|
452
|
+
let names;
|
|
453
|
+
try {
|
|
454
|
+
names = fs.readdirSync(folder).filter((name) => /^restore-.*\.tar\.zst$/u.test(name));
|
|
455
|
+
} catch {
|
|
456
|
+
return [];
|
|
457
|
+
}
|
|
458
|
+
const rows = names
|
|
459
|
+
.map((name) => {
|
|
460
|
+
const file = path.join(folder, name);
|
|
461
|
+
try { return { file, mtime_ms: fs.statSync(file).mtimeMs }; } catch { return null; }
|
|
462
|
+
})
|
|
463
|
+
.filter((row) => row !== null)
|
|
464
|
+
.sort((a, b) => b.mtime_ms - a.mtime_ms);
|
|
465
|
+
const pruned = [];
|
|
466
|
+
for (const row of rows.slice(keep)) {
|
|
467
|
+
if (keepFile !== null && path.resolve(row.file) === path.resolve(keepFile)) continue;
|
|
468
|
+
try {
|
|
469
|
+
fs.rmSync(row.file, { force: true });
|
|
470
|
+
fs.rmSync(sidecarPath(row.file), { force: true });
|
|
471
|
+
pruned.push(row.file);
|
|
472
|
+
} catch { /* a failed prune is reported by the next list */ }
|
|
473
|
+
}
|
|
474
|
+
return pruned;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export function sidecarPath(file) {
|
|
478
|
+
return `${file}.json`;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export function writeSidecar(file, value) {
|
|
482
|
+
const target = sidecarPath(file);
|
|
483
|
+
atomicWriteFile(target, `${JSON.stringify({ schema: SIDECAR_SCHEMA, ...value }, null, 2)}\n`, 0o600);
|
|
484
|
+
return target;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function readSidecar(file) {
|
|
488
|
+
const parsed = readJson(sidecarPath(file), null);
|
|
489
|
+
if (parsed?.schema !== SIDECAR_SCHEMA) return null;
|
|
490
|
+
if (parsed?.point?.schema !== POINT_SCHEMA) return null;
|
|
491
|
+
return parsed;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Read and verify a restore point. All manifest entries must be present, every
|
|
496
|
+
* digest must match, and every name must be relative and traversal-free.
|
|
497
|
+
* @param {string} file
|
|
498
|
+
* @param {{verify?: boolean}} [options]
|
|
499
|
+
*/
|
|
500
|
+
export function readArchive(file, options = {}) {
|
|
501
|
+
const target = path.resolve(file);
|
|
502
|
+
let stat;
|
|
503
|
+
try { stat = fs.statSync(target); } catch { return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${target} does not exist` }; }
|
|
504
|
+
if (!stat.isFile()) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${target} is not a file` };
|
|
505
|
+
if (stat.size > MAX_ARCHIVE_READ_BYTES) {
|
|
506
|
+
return { ok: false, reason_code: CODES.ARCHIVE_TOO_LARGE, detail: `${target} is ${formatBytes(stat.size)}` };
|
|
507
|
+
}
|
|
508
|
+
let raw;
|
|
509
|
+
try { raw = fs.readFileSync(target); } catch (error) {
|
|
510
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${target}: ${error instanceof Error ? error.message : String(error)}` };
|
|
511
|
+
}
|
|
512
|
+
let tar;
|
|
513
|
+
try {
|
|
514
|
+
tar = zlib.zstdDecompressSync(raw);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `zstd: ${error instanceof Error ? error.message : String(error)}` };
|
|
517
|
+
}
|
|
518
|
+
let entries;
|
|
519
|
+
try {
|
|
520
|
+
entries = readTar(tar);
|
|
521
|
+
} catch (error) {
|
|
522
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `tar: ${error instanceof Error ? error.message : String(error)}` };
|
|
523
|
+
}
|
|
524
|
+
const map = new Map();
|
|
525
|
+
for (const entry of entries) {
|
|
526
|
+
if (!isSafeArchiveName(entry.name)) {
|
|
527
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `unsafe entry name ${JSON.stringify(entry.name)}` };
|
|
528
|
+
}
|
|
529
|
+
if (map.has(entry.name)) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `duplicate entry ${entry.name}` };
|
|
530
|
+
map.set(entry.name, entry.data);
|
|
531
|
+
}
|
|
532
|
+
const manifestBuffer = map.get('manifest.json');
|
|
533
|
+
if (manifestBuffer === undefined) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: 'manifest.json is missing' };
|
|
534
|
+
let manifest;
|
|
535
|
+
try { manifest = JSON.parse(manifestBuffer.toString('utf8')); } catch { return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: 'manifest.json is not JSON' }; }
|
|
536
|
+
if (manifest?.schema !== MANIFEST_SCHEMA) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `unknown manifest schema ${JSON.stringify(manifest?.schema)}` };
|
|
537
|
+
if (manifest?.restore_point?.schema !== POINT_SCHEMA) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: 'restore_point metadata is missing or has an unknown schema' };
|
|
538
|
+
if (options.verify !== false) {
|
|
539
|
+
for (const row of manifest.files ?? []) {
|
|
540
|
+
if (!isSafeArchiveName(row.rel)) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `unsafe manifest entry ${JSON.stringify(row.rel)}` };
|
|
541
|
+
const data = map.get(row.rel);
|
|
542
|
+
if (data === undefined) return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `missing entry ${row.rel}` };
|
|
543
|
+
if (typeof row.size === 'number' && row.size !== data.length) {
|
|
544
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${row.rel}: size ${data.length} != manifest ${row.size}` };
|
|
545
|
+
}
|
|
546
|
+
if (typeof row.sha256 === 'string' && sha256(data) !== row.sha256) {
|
|
547
|
+
return { ok: false, reason_code: CODES.ARCHIVE_INVALID, detail: `${row.rel}: sha256 mismatch` };
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return {
|
|
552
|
+
ok: true,
|
|
553
|
+
file: target,
|
|
554
|
+
bytes: stat.size,
|
|
555
|
+
sha256: sha256(raw),
|
|
556
|
+
manifest,
|
|
557
|
+
point: manifest.restore_point,
|
|
558
|
+
entries,
|
|
559
|
+
map,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Metadata only (still verifies every digest). */
|
|
564
|
+
export function readRestorePoint(file) {
|
|
565
|
+
const archive = readArchive(file);
|
|
566
|
+
if (!archive.ok) return archive;
|
|
567
|
+
return {
|
|
568
|
+
ok: true,
|
|
569
|
+
file: archive.file,
|
|
570
|
+
bytes: archive.bytes,
|
|
571
|
+
sha256: archive.sha256,
|
|
572
|
+
point: archive.point,
|
|
573
|
+
counts: archive.manifest.counts ?? archive.point.counts,
|
|
574
|
+
manifest: archive.manifest,
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** List one store, newest first. Unreadable files become `ok:false` rows, not omissions. */
|
|
579
|
+
export function listCategory(root, kind) {
|
|
580
|
+
const folder = categoryDir(root, kind);
|
|
581
|
+
if (!fs.existsSync(folder)) return [];
|
|
582
|
+
return fs.readdirSync(folder)
|
|
583
|
+
.filter((name) => /^restore-.*\.tar\.zst$/u.test(name))
|
|
584
|
+
.map((name) => {
|
|
585
|
+
const file = path.join(folder, name);
|
|
586
|
+
let bytes = 0;
|
|
587
|
+
try { bytes = fs.statSync(file).size; } catch { return { ok: false, kind, file, bytes: 0, error: 'file disappeared' }; }
|
|
588
|
+
const sidecar = readSidecar(file);
|
|
589
|
+
if (sidecar !== null && sidecar.bytes === bytes) {
|
|
590
|
+
return {
|
|
591
|
+
ok: true,
|
|
592
|
+
kind,
|
|
593
|
+
file,
|
|
594
|
+
bytes,
|
|
595
|
+
sha256: sidecar.sha256,
|
|
596
|
+
point: sidecar.point,
|
|
597
|
+
counts: sidecar.counts ?? sidecar.point.counts,
|
|
598
|
+
metadata_source: 'sidecar',
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
const row = readRestorePoint(file);
|
|
602
|
+
if (!row.ok) return { ok: false, kind, file, bytes, error: row.detail };
|
|
603
|
+
try { writeSidecar(file, { point: row.point, counts: row.counts, sha256: row.sha256, bytes: row.bytes }); } catch { /* read-only folder */ }
|
|
604
|
+
return { ...row, kind, metadata_source: 'archive' };
|
|
605
|
+
})
|
|
606
|
+
.sort((a, b) => (b.point?.created_at ?? '').localeCompare(a.point?.created_at ?? ''));
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** Copy a point from another machine into `imported/`; never move the source. */
|
|
610
|
+
export function importRestorePoint(input) {
|
|
611
|
+
const root = resolveRoot(input.root);
|
|
612
|
+
if (root === '') return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: 'choose a restore point folder first' };
|
|
613
|
+
const source = path.resolve(input.file);
|
|
614
|
+
const row = readRestorePoint(source);
|
|
615
|
+
if (!row.ok) return row;
|
|
616
|
+
if (source.startsWith(`${path.resolve(root)}${path.sep}`)) {
|
|
617
|
+
return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: 'the source file is already inside the restore-point root' };
|
|
618
|
+
}
|
|
619
|
+
const writable = ensureWritableRoot(root);
|
|
620
|
+
if (writable !== null) return { ok: false, reason_code: CODES.ROOT_UNWRITABLE, detail: writable };
|
|
621
|
+
const folder = categoryDir(root, 'imported');
|
|
622
|
+
ensureDir(folder);
|
|
623
|
+
const base = path.basename(source).replace(/[^a-z0-9._-]/giu, '_');
|
|
624
|
+
let target = path.join(folder, base.startsWith('restore-') ? base : `restore-imported-${base}`);
|
|
625
|
+
for (let n = 2; fs.existsSync(target); n += 1) {
|
|
626
|
+
target = path.join(folder, `${path.basename(target, POINT_EXT)}-${n}${POINT_EXT}`);
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL);
|
|
630
|
+
writeSidecar(target, { point: row.point, counts: row.counts, sha256: row.sha256, bytes: row.bytes });
|
|
631
|
+
} catch (error) {
|
|
632
|
+
return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: error instanceof Error ? error.message : String(error) };
|
|
633
|
+
}
|
|
634
|
+
return { ok: true, file: target, source, point: row.point, bytes: row.bytes, sha256: row.sha256 };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Estimate what a point will contain, without writing. */
|
|
638
|
+
export function estimateRestorePoint(input) {
|
|
639
|
+
const dshHome = resolveDshHome(input.dshHome);
|
|
640
|
+
const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : 'desktop';
|
|
641
|
+
const scan = scanHome({ dshHome, profile });
|
|
642
|
+
const sessions = selectSessions(scan.sessions, input.sessionScope ?? 'active');
|
|
643
|
+
const plugins = readProfilePlugins({ dshHome, profile });
|
|
644
|
+
return {
|
|
645
|
+
ok: true,
|
|
646
|
+
sessions: sessions.length,
|
|
647
|
+
session_bytes: sessions.reduce((sum, row) => sum + row.size, 0),
|
|
648
|
+
all_sessions: scan.sessions.length,
|
|
649
|
+
archived: scan.sessions.filter((row) => row.flags?.archived === true).length,
|
|
650
|
+
attachments: scan.attachments.length,
|
|
651
|
+
attachment_bytes: scan.attachments.reduce((sum, row) => sum + row.size, 0),
|
|
652
|
+
config_files: scan.config.length,
|
|
653
|
+
plugins: plugins.ok ? plugins.plugins.length : 0,
|
|
654
|
+
plugin_list: plugins.ok ? plugins.all_plugins : [],
|
|
655
|
+
workspace_count: scan.registry.workspaces.length,
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* The client owns the folder/file pickers (`__DSH_DIRECTORY_PICKER__` and an
|
|
661
|
+
* `<input type=file>`); Electron dialogs are not available in the DSH host.
|
|
662
|
+
*/
|
|
663
|
+
export function pickerUnavailable(what) {
|
|
664
|
+
return {
|
|
665
|
+
ok: false,
|
|
666
|
+
reason_code: 'TIMEMACHINE_PICKER_IN_CLIENT',
|
|
667
|
+
detail: `the ${what} picker runs in the DSH client; call it from the panel UI`,
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
export { SELF_PLUGIN };
|