@ddtcorex/dsh-maestro-core 0.15.1 → 0.16.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.
Files changed (117) hide show
  1. package/README.md +7 -7
  2. package/assets/icon.svg +4 -0
  3. package/cordis.patch.yml +0 -12
  4. package/lib/client.js +3 -1744
  5. package/lib/health-poller.js +1 -1
  6. package/lib/self-kill-guard.d.ts +25 -8
  7. package/lib/self-kill-guard.js +81 -27
  8. package/lib/types/client/config/components/BrandMark.d.ts +3 -3
  9. package/lib/types/client/index.d.ts.map +1 -1
  10. package/locale/en.json +6 -0
  11. package/package.json +9 -5
  12. package/src/client/config/components/BrandMark.tsx +3 -3
  13. package/src/client/index.tsx +0 -2
  14. package/src/host/health-poller.ts +1 -1
  15. package/src/host/self-kill-guard.ts +84 -26
  16. package/lib/sync/backup-config.d.ts +0 -55
  17. package/lib/sync/backup-config.js +0 -119
  18. package/lib/sync/backup-service.d.ts +0 -123
  19. package/lib/sync/backup-service.js +0 -486
  20. package/lib/sync/bidirectional.d.ts +0 -39
  21. package/lib/sync/bidirectional.js +0 -25
  22. package/lib/sync/cli.d.ts +0 -38
  23. package/lib/sync/cli.js +0 -528
  24. package/lib/sync/config.d.ts +0 -59
  25. package/lib/sync/config.js +0 -72
  26. package/lib/sync/fingerprint.d.ts +0 -29
  27. package/lib/sync/fingerprint.js +0 -65
  28. package/lib/sync/hashing.d.ts +0 -22
  29. package/lib/sync/hashing.js +0 -77
  30. package/lib/sync/index.d.ts +0 -6
  31. package/lib/sync/index.js +0 -619
  32. package/lib/sync/machine-id.d.ts +0 -29
  33. package/lib/sync/machine-id.js +0 -66
  34. package/lib/sync/merge.d.ts +0 -31
  35. package/lib/sync/merge.js +0 -86
  36. package/lib/sync/peer-host.d.ts +0 -22
  37. package/lib/sync/peer-host.js +0 -62
  38. package/lib/sync/process-runner.d.ts +0 -31
  39. package/lib/sync/process-runner.js +0 -161
  40. package/lib/sync/remote-agent.d.ts +0 -41
  41. package/lib/sync/remote-agent.js +0 -216
  42. package/lib/sync/remote-cache.d.ts +0 -18
  43. package/lib/sync/remote-cache.js +0 -60
  44. package/lib/sync/remote-manifest.d.ts +0 -20
  45. package/lib/sync/remote-manifest.js +0 -86
  46. package/lib/sync/s3-object-store.d.ts +0 -38
  47. package/lib/sync/s3-object-store.js +0 -126
  48. package/lib/sync/session-plan.d.ts +0 -29
  49. package/lib/sync/session-plan.js +0 -213
  50. package/lib/sync/sigv4.d.ts +0 -20
  51. package/lib/sync/sigv4.js +0 -57
  52. package/lib/sync/snapshot.d.ts +0 -16
  53. package/lib/sync/snapshot.js +0 -143
  54. package/lib/sync/ssh-mux.d.ts +0 -12
  55. package/lib/sync/ssh-mux.js +0 -48
  56. package/lib/sync/store-root.d.ts +0 -44
  57. package/lib/sync/store-root.js +0 -67
  58. package/lib/sync/sync-plan.d.ts +0 -24
  59. package/lib/sync/sync-plan.js +0 -366
  60. package/lib/sync/sync-service.d.ts +0 -183
  61. package/lib/sync/sync-service.js +0 -926
  62. package/lib/sync/sync-types.d.ts +0 -87
  63. package/lib/sync/sync-types.js +0 -1
  64. package/lib/sync/transport.d.ts +0 -75
  65. package/lib/sync/transport.js +0 -196
  66. package/lib/sync/tunnel-restore.d.ts +0 -77
  67. package/lib/sync/tunnel-restore.js +0 -142
  68. package/lib/sync/validation.d.ts +0 -12
  69. package/lib/sync/validation.js +0 -96
  70. package/lib/types/client/sync/R2SyncPanel.d.ts +0 -6
  71. package/lib/types/client/sync/R2SyncPanel.d.ts.map +0 -1
  72. package/lib/types/client/sync/SyncPanel.d.ts +0 -12
  73. package/lib/types/client/sync/SyncPanel.d.ts.map +0 -1
  74. package/lib/types/client/sync/confirm-dialog.d.ts +0 -43
  75. package/lib/types/client/sync/confirm-dialog.d.ts.map +0 -1
  76. package/lib/types/client/sync/index.d.ts +0 -10
  77. package/lib/types/client/sync/index.d.ts.map +0 -1
  78. package/lib/types/client/sync/ui.d.ts +0 -75
  79. package/lib/types/client/sync/ui.d.ts.map +0 -1
  80. package/lib/types/client/sync/use-backup.d.ts +0 -50
  81. package/lib/types/client/sync/use-backup.d.ts.map +0 -1
  82. package/lib/types/client/sync/use-sync.d.ts +0 -88
  83. package/lib/types/client/sync/use-sync.d.ts.map +0 -1
  84. package/src/client/sync/R2SyncPanel.tsx +0 -260
  85. package/src/client/sync/SyncPanel.tsx +0 -422
  86. package/src/client/sync/confirm-dialog.tsx +0 -202
  87. package/src/client/sync/index.tsx +0 -286
  88. package/src/client/sync/ui.tsx +0 -297
  89. package/src/client/sync/use-backup.ts +0 -207
  90. package/src/client/sync/use-sync.ts +0 -502
  91. package/src/host/sync/backup-config.ts +0 -158
  92. package/src/host/sync/backup-service.ts +0 -506
  93. package/src/host/sync/bidirectional.ts +0 -66
  94. package/src/host/sync/cli.ts +0 -530
  95. package/src/host/sync/config.ts +0 -96
  96. package/src/host/sync/fingerprint.ts +0 -83
  97. package/src/host/sync/hashing.ts +0 -91
  98. package/src/host/sync/index.ts +0 -697
  99. package/src/host/sync/machine-id.ts +0 -81
  100. package/src/host/sync/merge.ts +0 -99
  101. package/src/host/sync/peer-host.ts +0 -65
  102. package/src/host/sync/process-runner.ts +0 -177
  103. package/src/host/sync/remote-agent.ts +0 -212
  104. package/src/host/sync/remote-cache.ts +0 -68
  105. package/src/host/sync/remote-manifest.ts +0 -91
  106. package/src/host/sync/s3-object-store.ts +0 -144
  107. package/src/host/sync/session-plan.ts +0 -237
  108. package/src/host/sync/sigv4.ts +0 -81
  109. package/src/host/sync/snapshot.ts +0 -132
  110. package/src/host/sync/ssh-mux.ts +0 -55
  111. package/src/host/sync/store-root.ts +0 -83
  112. package/src/host/sync/sync-plan.ts +0 -366
  113. package/src/host/sync/sync-service.ts +0 -960
  114. package/src/host/sync/sync-types.ts +0 -102
  115. package/src/host/sync/transport.ts +0 -256
  116. package/src/host/sync/tunnel-restore.ts +0 -160
  117. package/src/host/sync/validation.ts +0 -104
@@ -1,158 +0,0 @@
1
- // src/host/backup-config.ts — backup target config + secret resolution.
2
- //
3
- // Non-secret config comes from the shared settings store (domains.sync.r2.*);
4
- // secret material never lives in settings, never is logged, and never crosses
5
- // RPC/tools — resolution order: environment first, then a private 0600 sidecar
6
- // in the plugin's own runtime directory (outside the eligible data boundary,
7
- // so the merge CLI never reads or syncs it). Status surfaces only the source
8
- // label, the bucket, the prefix and the provider.
9
- import { createHash } from 'node:crypto';
10
- import * as os from 'node:os';
11
- import * as nodeFs from 'node:fs';
12
- import * as nodePath from 'node:path';
13
-
14
- export interface BackupProviderConfig {
15
- provider: 'r2' | 'aws';
16
- endpoint: string;
17
- region: string;
18
- bucket: string;
19
- prefix: string;
20
- }
21
-
22
- export interface BackupSecrets {
23
- accessKeyId: string;
24
- secretAccessKey: string;
25
- }
26
-
27
- export interface BackupTarget {
28
- provider: 'r2' | 'aws';
29
- bucket: string;
30
- prefix: string;
31
- hostId: string;
32
- }
33
-
34
- export type SecretSource = 'env' | 'file' | 'none';
35
-
36
- export const BACKUP_SIDECAR_REL = 'dsh-maestro-sync/backup-secrets.json';
37
-
38
- export function describeSecretSource(env: Record<string, string | undefined>, sidecarPath: string): SecretSource {
39
- if ((env.R2_ACCESS_KEY_ID && env.R2_SECRET_ACCESS_KEY) || (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY)) return 'env';
40
- try {
41
- if (nodeFs.existsSync(sidecarPath)) return 'file';
42
- } catch {}
43
- return 'none';
44
- }
45
-
46
- export async function resolveBackupTarget(
47
- doc: { domains?: { sync?: { r2?: Record<string, unknown> } } } = {},
48
- env: Record<string, string | undefined> = process.env as any,
49
- dshHome: string = process.env.DSH_HOME || nodePath.join(os.homedir(), '.dsh'),
50
- ): Promise<{ config: BackupProviderConfig; secrets: BackupSecrets; source: SecretSource }> {
51
- const sync = doc.domains?.sync as Record<string, any> | undefined;
52
- const r2 = (sync?.r2 ?? {}) as Record<string, any>;
53
- const provider = (r2.provider as string | undefined) === 'aws' ? 'aws' : 'r2';
54
- const accountId = (r2.accountId as string | undefined) ?? '';
55
- const bucket = (r2.bucket as string | undefined) ?? 'maestro-backup';
56
- const hostId = createHash('sha256').update(os.hostname()).digest('hex').slice(0, 12);
57
- const prefix = (r2.prefix as string | undefined) ?? `v1/hosts/${hostId}/`;
58
- const region = (r2.region as string | undefined) ?? (provider === 'r2' ? 'auto' : '');
59
- const endpoint = (r2.endpoint as string | undefined) ?? (provider === 'r2' ? `https://${accountId}.r2.cloudflarestorage.com` : '');
60
-
61
- const sidecar = nodePath.join(dshHome, BACKUP_SIDECAR_REL);
62
- let secrets: BackupSecrets | null = null;
63
- let source: SecretSource = 'none';
64
- if (env.R2_ACCESS_KEY_ID && env.R2_SECRET_ACCESS_KEY) {
65
- secrets = { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY };
66
- source = 'env';
67
- } else if (env.AWS_ACCESS_KEY_ID && env.AWS_SECRET_ACCESS_KEY) {
68
- secrets = { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY };
69
- source = 'env';
70
- } else {
71
- try {
72
- const raw = nodeFs.readFileSync(sidecar, 'utf-8') as string;
73
- const parsed = JSON.parse(raw) as { accessKeyId?: string; secretAccessKey?: string };
74
- if (parsed.accessKeyId && parsed.secretAccessKey) {
75
- secrets = { accessKeyId: parsed.accessKeyId, secretAccessKey: parsed.secretAccessKey };
76
- source = 'file';
77
- }
78
- } catch {}
79
- }
80
- if (!secrets) {
81
- throw Object.assign(
82
- new Error(
83
- 'backup requires access key secret material: set R2_ACCESS_KEY_ID + R2_SECRET_ACCESS_KEY '
84
- + '(or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY) in the environment, '
85
- + `or write a 0600 ${sidecar}`,
86
- ),
87
- {
88
- phase: 'validate',
89
- code: 'MISSING_BACKUP_SECRETS',
90
- },
91
- );
92
- }
93
- return { config: { provider, endpoint, region, bucket, prefix }, secrets, source };
94
- }
95
-
96
- export interface R2ConfigInput {
97
- provider?: unknown;
98
- accountId?: unknown;
99
- endpoint?: unknown;
100
- region?: unknown;
101
- bucket?: unknown;
102
- prefix?: unknown;
103
- }
104
-
105
- export interface NormalizedR2Config {
106
- provider: 'r2' | 'aws';
107
- accountId: string;
108
- endpoint: string;
109
- region: string;
110
- bucket: string;
111
- prefix: string;
112
- }
113
-
114
- const SHELL_META_RE = /[;`$|&><*?'"\\(){}!\s=]/;
115
- const BUCKET_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;
116
- const REGION_RE = /^[A-Za-z0-9-]{1,32}$/;
117
- const ACCOUNT_RE = /^[0-9a-f]{32}$/i;
118
- const PREFIX_SEG_RE = /^[A-Za-z0-9._-]{1,64}$/;
119
-
120
- /**
121
- * Validate + normalize non-secret R2/S3 config from the Settings UI.
122
- * Fail-closed: throws on the first invalid field. Empty strings mean
123
- * "use the default" and are stripped so built-in fallbacks keep working.
124
- * Secret material is never accepted here — keys live in env or the 0600
125
- * sidecar only.
126
- */
127
- export function validateR2ConfigInput(input: R2ConfigInput): NormalizedR2Config {
128
- const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '');
129
- const provider = str(input.provider) || 'r2';
130
- if (provider !== 'r2' && provider !== 'aws') throw new Error(`invalid provider: ${JSON.stringify(provider)} (want 'r2'|'aws')`);
131
- const accountId = str(input.accountId);
132
- if (accountId && !ACCOUNT_RE.test(accountId)) throw new Error('invalid accountId: want 32 hex chars');
133
- if (provider === 'aws' && accountId) throw new Error('invalid accountId: only meaningful for provider r2');
134
- const endpoint = str(input.endpoint);
135
- if (endpoint) {
136
- if (SHELL_META_RE.test(endpoint) || endpoint.length > 256) throw new Error('invalid endpoint: illegal characters');
137
- if (!/^https:\/\/[A-Za-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=-]*)?$/.test(endpoint)) {
138
- throw new Error('invalid endpoint: want an https:// URL');
139
- }
140
- }
141
- const region = str(input.region);
142
- if (region && !REGION_RE.test(region)) throw new Error(`invalid region: ${JSON.stringify(region)}`);
143
- const bucket = str(input.bucket);
144
- if (!bucket) throw new Error('bucket is required');
145
- if (!BUCKET_RE.test(bucket)) throw new Error(`invalid bucket: ${JSON.stringify(bucket)} (3-63 lowercase letters/digits/dots/hyphens)`);
146
- let prefix = str(input.prefix);
147
- if (!prefix) throw new Error('prefix is required');
148
- if (prefix.startsWith('/') || prefix.includes('\\') || prefix.includes('..') || /[\u0000-\u001f\u007f]/.test(prefix)) {
149
- throw new Error(`invalid prefix: ${JSON.stringify(prefix)}`);
150
- }
151
- if (!prefix.endsWith('/')) prefix += '/';
152
- const segs = prefix.split('/').filter((s) => s.length > 0);
153
- if (segs.length === 0 || segs.length > 8 || !segs.every((s) => PREFIX_SEG_RE.test(s))) {
154
- throw new Error(`invalid prefix: ${JSON.stringify(prefix)}`);
155
- }
156
- if (prefix.length > 200) throw new Error('invalid prefix: too long');
157
- return { provider, accountId, endpoint, region, bucket, prefix };
158
- }
@@ -1,506 +0,0 @@
1
- // src/host/backup-service.ts — R2/S3 backup engine (spec §5.4–§5.6, decision C).
2
- //
3
- // Layout: blobs/sha256/<sha> (immutable, content-addressed) + manifests/<ts>-<id>
4
- // (immutable snapshot) + HEAD (CAS pointer). preview() is READ-ONLY: it compares
5
- // the current eligible local hashes against the HEAD manifest (no object
6
- // download, no upload). apply() is the only bucket-mutation route: PUT missing
7
- // blobs (idempotent by sha) → PUT a fresh immutable manifest → CAS-advance HEAD.
8
- // Restore and GC arrive in later tasks of the same module.
9
- import * as nodeFs from 'node:fs';
10
- import * as path from 'node:path';
11
- import { randomBytes, createHash } from 'node:crypto';
12
- import { normalizeEligiblePath } from './validation.js';
13
- import { hashFiles, hashWirePaths } from './hashing.js';
14
- import { localPathForWirePath, resolveStoreRoot } from './store-root.js';
15
- import { loadIndex, saveIndex, probeIndex, matchesStat, statFingerprint } from './fingerprint.js';
16
- import type { S3ObjectStore } from './s3-object-store.js';
17
- import type { BackupTarget } from './backup-config.js';
18
-
19
- export interface BackupManifestFile {
20
- path: string;
21
- sha256: string;
22
- size: number;
23
- blobKey: string;
24
- }
25
-
26
- export interface BackupManifest {
27
- schema: 1;
28
- hostId: string;
29
- createdAt: string;
30
- files: BackupManifestFile[];
31
- }
32
-
33
- export interface BackupPreview {
34
- previewId: string;
35
- revision: string;
36
- expiresAt: string;
37
- summary: { identical: number; missing: number; addedBytes: number };
38
- }
39
-
40
- export interface BackupApplyResult {
41
- ok: boolean;
42
- revision: string;
43
- committed: string[];
44
- failures: SyncFailureLike[];
45
- }
46
-
47
- // Minimal failure shape (mirrors SyncFailure without importing the sync module graph).
48
- export interface SyncFailureLike {
49
- phase: string;
50
- code: string;
51
- detail: string;
52
- path?: string;
53
- }
54
-
55
- const TTL_MS = 60_000;
56
-
57
- export class BackupService {
58
- constructor(private readonly opts: { localDsh: string; storeRoot?: string; store: S3ObjectStore; target: BackupTarget; previewDir: string; cacheDir: string; fs?: any }) {}
59
-
60
- /**
61
- * The store may live outside the DSH home. Reads and writes of memory content map
62
- * through the resolved root; sessions and sync state stay under the DSH home.
63
- */
64
- private resolveStoreRoot(): string {
65
- return (
66
- this.opts.storeRoot ??
67
- resolveStoreRoot({ env: { ...process.env, DSH_HOME: this.opts.localDsh } }).root
68
- );
69
- }
70
-
71
- private localPathForWirePath(wirePath: string): string {
72
- return localPathForWirePath(wirePath, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh });
73
- }
74
-
75
- blobKey(sha: string): string {
76
- return `blobs/sha256/${sha}`;
77
- }
78
-
79
- /**
80
- * A backup taken in the core-first release window would walk a root that does not
81
- * exist yet, record zero memory files, and report `ok: true`. Refuse instead, with
82
- * the same sentinel sync uses.
83
- */
84
- assertStoreMigrated(): void {
85
- const fsMod = this.opts.fs ?? nodeFs;
86
- if (typeof fsMod.existsSync !== 'function') return;
87
- const storeRoot = this.resolveStoreRoot();
88
- const exists = (p: string) => {
89
- try {
90
- return fsMod.existsSync(p);
91
- } catch {
92
- return false;
93
- }
94
- };
95
- if (!exists(storeRoot) && exists(path.join(this.opts.localDsh, 'maestro-memory'))) {
96
- const error: any = new Error(
97
- `local store is still at ${path.join(this.opts.localDsh, 'maestro-memory')}; install the current build (its boot migration moves it to ${storeRoot}) before backing up`,
98
- );
99
- error.code = 'STORE_NOT_MIGRATED';
100
- throw error;
101
- }
102
- }
103
-
104
- listEligibleFiles(): string[] {
105
- this.assertStoreMigrated();
106
- const root = this.opts.localDsh;
107
- const storeRoot = this.resolveStoreRoot();
108
- const fsMod = this.opts.fs ?? nodeFs;
109
- const out: string[] = [];
110
- // `prefix` is the wire prefix of the directory being walked, so a store outside the
111
- // DSH home still reports `maestro-memory/...` and passes normalization.
112
- const walk = (dir: string, prefix = '') => {
113
- let ents: any[];
114
- try {
115
- ents = fsMod.readdirSync(dir, { withFileTypes: true });
116
- } catch {
117
- return;
118
- }
119
- for (const ent of ents) {
120
- const full = path.join(dir, ent.name);
121
- if (typeof ent.isDirectory === 'function' && ent.isDirectory()) {
122
- if (!['node_modules', '.git', '.supervisor', 'profiles'].includes(ent.name)) {
123
- walk(full, prefix ? `${prefix}/${ent.name}` : ent.name);
124
- }
125
- } else {
126
- const rel = (prefix ? `${prefix}/${ent.name}` : ent.name).split(path.sep).join('/');
127
- try {
128
- normalizeEligiblePath(rel);
129
- out.push(rel);
130
- } catch {}
131
- }
132
- }
133
- };
134
- try {
135
- walk(storeRoot, 'maestro-memory');
136
- // When the store sits inside the DSH home its files were already collected above,
137
- // so sessions alone are walked from there.
138
- walk(path.join(root, 'sessions'), 'sessions');
139
- } catch {}
140
- return out.sort();
141
- }
142
-
143
- async readHeadManifest(): Promise<{ key: string; manifest: BackupManifest } | null> {
144
- const headKey = `${this.opts.target.prefix}HEAD`;
145
- const head = await this.opts.store.head(this.opts.target.bucket, headKey);
146
- if (!head) return null;
147
- const tmp = path.join(require('node:os').tmpdir(), `bk-head-${randomBytes(4).toString('hex')}`);
148
- nodeFs.mkdirSync(tmp, { recursive: true });
149
- try {
150
- await this.opts.store.get(this.opts.target.bucket, headKey, tmp);
151
- const headBody = JSON.parse(nodeFs.readFileSync(path.join(tmp, headKey), 'utf-8')) as { manifestKey: string };
152
- await this.opts.store.get(this.opts.target.bucket, headBody.manifestKey, tmp);
153
- const manifest = JSON.parse(nodeFs.readFileSync(path.join(tmp, headBody.manifestKey), 'utf-8')) as BackupManifest;
154
- return { key: headBody.manifestKey, manifest };
155
- } finally {
156
- try {
157
- nodeFs.rmSync(tmp, { recursive: true, force: true });
158
- } catch {}
159
- }
160
- }
161
-
162
- private async localHashes(): Promise<{ path: string; sha256: string; size: number }[]> {
163
- const fsMod = this.opts.fs ?? nodeFs;
164
- const paths = this.listEligibleFiles();
165
- const index = loadIndex(this.opts.cacheDir);
166
- const stale: string[] = [];
167
- const local: { path: string; sha256: string; size: number }[] = [];
168
- for (const rel of paths) {
169
- const full = this.localPathForWirePath(rel);
170
- try {
171
- const st = fsMod.statSync(full, { bigint: true } as any);
172
- const e = probeIndex(rel, index);
173
- if (e && matchesStat(e, st)) local.push({ path: rel, sha256: e.sha256, size: e.size });
174
- else stale.push(rel);
175
- } catch {
176
- stale.push(rel);
177
- }
178
- }
179
- const hashed = await hashWirePaths(fsMod, { storeRoot: this.resolveStoreRoot(), localDsh: this.opts.localDsh }, stale);
180
- for (const f of hashed) {
181
- local.push({ path: f.path, sha256: f.sha256, size: f.size });
182
- try {
183
- const st = fsMod.statSync(this.localPathForWirePath(f.path), { bigint: true } as any);
184
- index.entries[f.path] = { ...statFingerprint(st), sha256: f.sha256 };
185
- } catch {}
186
- }
187
- if (hashed.length > 0) saveIndex(this.opts.cacheDir, index);
188
- return local.sort((a, b) => a.path.localeCompare(b.path));
189
- }
190
-
191
- async preview(fileList?: { path: string; sha256: string; size: number }[]): Promise<BackupPreview> {
192
- // fileList override exists for tests; production uses the fresh local hashes.
193
- const local = fileList ?? (await this.localHashes());
194
- const prev = await this.readHeadManifest();
195
- const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
196
- let identical = 0;
197
- let missing = 0;
198
- let addedBytes = 0;
199
- for (const f of local) {
200
- const p = prevByPath.get(f.path);
201
- if (p && p.sha256 === f.sha256) identical++;
202
- else {
203
- missing++;
204
- addedBytes += f.size;
205
- }
206
- }
207
- const previewId = randomBytes(16).toString('hex');
208
- const preview: BackupPreview = {
209
- previewId,
210
- revision: createHash('sha256').update(JSON.stringify(local)).digest('hex').slice(0, 16),
211
- expiresAt: new Date(Date.now() + TTL_MS).toISOString(),
212
- summary: { identical, missing, addedBytes },
213
- };
214
- nodeFs.mkdirSync(this.opts.previewDir, { recursive: true, mode: 0o700 });
215
- nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.backup.json`), JSON.stringify(preview), 'utf-8');
216
- return preview;
217
- }
218
-
219
- /**
220
- * Backup apply — the ONLY bucket-mutation route (spec §5.5):
221
- * 1. load the persisted preview (single-use, 60s TTL);
222
- * 2. re-hash local (freshest) and compare against the current HEAD manifest;
223
- * 3. PUT missing blobs (putIfAbsent — idempotent by content-addressing);
224
- * 4. PUT a new immutable manifest (unique key);
225
- * 5. CAS-advance HEAD (If-Match old etag / If-None-Match when absent).
226
- * ok:true only after HEAD advances; blob PUTs are retry-safe.
227
- */
228
- async apply(req: { previewId: string; confirm: true }): Promise<BackupApplyResult> {
229
- if (req.confirm !== true) {
230
- throw Object.assign(new Error('backup apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
231
- }
232
- const pvPath = path.join(this.opts.previewDir, `${req.previewId}.backup.json`);
233
- let saved: BackupPreview;
234
- try {
235
- saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as BackupPreview;
236
- } catch {
237
- throw Object.assign(new Error('backup preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
238
- }
239
- if (new Date(saved.expiresAt).getTime() <= Date.now()) {
240
- try {
241
- nodeFs.rmSync(pvPath, { force: true });
242
- } catch {}
243
- throw Object.assign(new Error('backup preview expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
244
- }
245
-
246
- const failures: SyncFailureLike[] = [];
247
- const committed: string[] = [];
248
- let fresh: BackupPreview;
249
- try {
250
- fresh = await this.preview();
251
- } catch (e: any) {
252
- // The store is unreachable/broken: fail closed with a structured journal —
253
- // apply must never throw a raw network error after the preview gate.
254
- try {
255
- nodeFs.rmSync(pvPath, { force: true });
256
- } catch {}
257
- return { ok: false, revision: saved.revision, committed: [], failures: [{ phase: 'backup', code: 'PREVIEW_REFRESH_FAILED', detail: e?.message ?? String(e) }] };
258
- }
259
- const prev = await this.readHeadManifest();
260
- const prevByPath = new Map((prev?.manifest.files ?? []).map((f) => [f.path, f]));
261
- const localPaths = this.listEligibleFiles();
262
- const files: BackupManifestFile[] = [];
263
- const fsMod = this.opts.fs ?? nodeFs;
264
- for (const rel of localPaths) {
265
- const prevFile = prevByPath.get(rel);
266
- // Fast path: bytes already backed up under the same sha — reuse, skip read+PUT.
267
- const index = loadIndex(this.opts.cacheDir);
268
- const entry = probeIndex(rel, index);
269
- let sha: string | null = null;
270
- let size = 0;
271
- if (entry && prevFile && entry.sha256 === prevFile.sha256) {
272
- sha = entry.sha256;
273
- size = entry.size;
274
- }
275
- if (sha === null) {
276
- try {
277
- const buf = fsMod.readFileSync(this.localPathForWirePath(rel));
278
- const b = Buffer.isBuffer(buf) ? buf : Buffer.from(String(buf), 'utf-8');
279
- sha = createHash('sha256').update(b).digest('hex');
280
- size = b.length;
281
- const key = `${this.opts.target.prefix}${this.blobKey(sha)}`;
282
- try {
283
- await this.opts.store.putIfAbsent(this.opts.target.bucket, key, b);
284
- } catch (e: any) {
285
- failures.push({ phase: 'backup', code: 'UPLOAD_FAILED', detail: e?.message ?? String(e), path: rel });
286
- continue;
287
- }
288
- } catch (e: any) {
289
- failures.push({ phase: 'backup', code: 'READ_FAILED', detail: e?.message ?? String(e), path: rel });
290
- continue;
291
- }
292
- }
293
- files.push({ path: rel, sha256: sha, size, blobKey: this.blobKey(sha) });
294
- }
295
- void fresh;
296
-
297
- if (failures.length === 0) {
298
- const ts = new Date().toISOString().replace(/[:.]/g, '-');
299
- const manifest: BackupManifest = { schema: 1, hostId: this.opts.target.hostId, createdAt: new Date().toISOString(), files };
300
- const manifestKey = `${this.opts.target.prefix}manifests/${ts}-${randomBytes(4).toString('hex')}.json`;
301
- try {
302
- await this.opts.store.putIfAbsent(this.opts.target.bucket, manifestKey, Buffer.from(JSON.stringify(manifest)));
303
- } catch (e: any) {
304
- failures.push({ phase: 'backup', code: 'MANIFEST_PUT_FAILED', detail: e?.message ?? String(e), path: manifestKey });
305
- }
306
- if (failures.length === 0) {
307
- const headKey = `${this.opts.target.prefix}HEAD`;
308
- const old = await this.opts.store.head(this.opts.target.bucket, headKey);
309
- try {
310
- await this.opts.store.putConditional(this.opts.target.bucket, headKey, Buffer.from(JSON.stringify({ manifestKey })), old ? { ifMatch: old.etag } : { ifNoneMatch: true });
311
- committed.push(...files.map((f) => f.path));
312
- } catch (e: any) {
313
- failures.push({ phase: 'backup', code: e?.code === 'CONCURRENT_MODIFICATION' ? 'CONCURRENT_MODIFICATION' : 'HEAD_UPDATE_FAILED', detail: e?.message ?? String(e), path: headKey });
314
- }
315
- }
316
- }
317
- try {
318
- nodeFs.rmSync(pvPath, { force: true });
319
- } catch {}
320
- return { ok: failures.length === 0, revision: saved.revision, committed, failures };
321
- }
322
-
323
- // ---- restore (spec §5.6): preview read-only; apply is the only mutation ----
324
-
325
- async restorePreview(opts: { mode: 'new-dir' | 'in-place' }): Promise<{ previewId: string; expiresAt: string; mode: 'new-dir' | 'in-place'; summary: { copied: number; merged: number; skipped: number; conflicts: number } }> {
326
- const head = await this.readHeadManifest();
327
- if (!head) throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
328
- const fsMod = this.opts.fs ?? nodeFs;
329
- let copied = 0;
330
- let merged = 0;
331
- let skipped = 0;
332
- let conflicts = 0;
333
- for (const f of head.manifest.files) {
334
- if (opts.mode === 'new-dir') {
335
- copied++;
336
- continue;
337
- }
338
- const full = this.localPathForWirePath(f.path);
339
- let cur: string | null = null;
340
- try {
341
- cur = createHash('sha256').update(fsMod.readFileSync(full)).digest('hex');
342
- } catch {}
343
- if (cur === f.sha256) skipped++;
344
- else if (cur === null) copied++;
345
- else merged++;
346
- }
347
- const previewId = randomBytes(16).toString('hex');
348
- const preview = { previewId, expiresAt: new Date(Date.now() + TTL_MS).toISOString(), mode: opts.mode, summary: { copied, merged, skipped, conflicts } };
349
- nodeFs.writeFileSync(path.join(this.opts.previewDir, `${previewId}.restore.json`), JSON.stringify(preview), 'utf-8');
350
- return preview;
351
- }
352
-
353
- async restoreApply(req: { previewId: string; mode: 'new-dir' | 'in-place'; destDir?: string; confirm: true }): Promise<BackupApplyResult> {
354
- if (req.confirm !== true) throw Object.assign(new Error('restore apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
355
- const pvPath = path.join(this.opts.previewDir, `${req.previewId}.restore.json`);
356
- let saved: { mode: 'new-dir' | 'in-place' };
357
- try {
358
- saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as { mode: 'new-dir' | 'in-place' };
359
- } catch {
360
- throw Object.assign(new Error('restore preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
361
- }
362
- if (saved.mode !== req.mode) throw Object.assign(new Error('restore preview mode mismatch'), { phase: 'validate', code: 'DIRECTION_MISMATCH' });
363
- const head = await this.readHeadManifest();
364
- if (!head) throw Object.assign(new Error('no backup to restore (no HEAD)'), { phase: 'restore', code: 'NO_BACKUP' });
365
- const fsMod = this.opts.fs ?? nodeFs;
366
- const tmp = path.join(require('node:os').tmpdir(), `restore-${randomBytes(4).toString('hex')}`);
367
- nodeFs.mkdirSync(tmp, { recursive: true });
368
- const failures: SyncFailureLike[] = [];
369
- const committed: string[] = [];
370
- try {
371
- for (const f of head.manifest.files) {
372
- try {
373
- // In place means "into the live store", which is the resolved root, not the
374
- // DSH home. Getting this wrong recreates the legacy directory on restore.
375
- const outFull =
376
- req.mode === 'new-dir'
377
- ? path.join(req.destDir ?? path.join(this.opts.localDsh, 'restored'), f.path)
378
- : this.localPathForWirePath(f.path);
379
- if (req.mode === 'in-place') {
380
- try {
381
- const cur = createHash('sha256').update(fsMod.readFileSync(outFull)).digest('hex');
382
- if (cur === f.sha256) continue; // byte-identical: skip
383
- } catch {}
384
- }
385
- const fullKey = `${this.opts.target.prefix}${f.blobKey}`;
386
- await this.opts.store.get(this.opts.target.bucket, fullKey, tmp);
387
- const staged = path.join(tmp, fullKey);
388
- const buf = fsMod.readFileSync(staged);
389
- if (createHash('sha256').update(buf).digest('hex') !== f.sha256) {
390
- throw Object.assign(new Error('blob checksum mismatch'), { phase: 'restore', code: 'CHECKSUM_MISMATCH' });
391
- }
392
- // In-place: keep a timestamped backup of the target before overwrite.
393
- if (req.mode === 'in-place' && fsMod.existsSync(outFull)) {
394
- const bak = `${outFull}.bak.${Date.now()}.${randomBytes(4).toString('hex')}`;
395
- fsMod.writeFileSync(bak, fsMod.readFileSync(outFull));
396
- }
397
- fsMod.mkdirSync(path.dirname(outFull), { recursive: true });
398
- const tmpFile = `${outFull}.tmp.${randomBytes(4).toString('hex')}`;
399
- fsMod.writeFileSync(tmpFile, buf);
400
- try {
401
- const fd = fsMod.openSync(tmpFile, 'r');
402
- try {
403
- fsMod.fsyncSync(fd);
404
- } finally {
405
- fsMod.closeSync(fd);
406
- }
407
- } catch {}
408
- fsMod.renameSync(tmpFile, outFull);
409
- committed.push(f.path);
410
- } catch (e: any) {
411
- failures.push({ phase: 'restore', code: e?.code ?? 'RESTORE_FAILED', detail: e?.message ?? String(e), path: f.path });
412
- }
413
- }
414
- } finally {
415
- try {
416
- nodeFs.rmSync(tmp, { recursive: true, force: true });
417
- } catch {}
418
- }
419
- try {
420
- nodeFs.rmSync(pvPath, { force: true });
421
- } catch {}
422
- return { ok: failures.length === 0, revision: '', committed, failures };
423
- }
424
-
425
- // ---- retention GC (spec §5.7): preview read-only; apply deletes unreachable blobs ----
426
-
427
- async gcPreview(opts: { keepDaily?: number; keepMonthly?: number } = {}): Promise<{
428
- retainedManifests: number;
429
- trashManifests: number;
430
- deletableBlobs: string[];
431
- freedBytes: number;
432
- previewId: string;
433
- }> {
434
- const prefix = this.opts.target.prefix;
435
- const all = (await this.opts.store.list(this.opts.target.bucket, `${prefix}manifests/`)).map((e) => e.key);
436
- const byDay = new Map<string, string>();
437
- const byMonth = new Map<string, string>();
438
- for (const key of all) {
439
- const head = await this.readManifestKey(key);
440
- const d = head.createdAt;
441
- const day = d.slice(0, 10);
442
- const month = d.slice(0, 7);
443
- const curDay = byDay.get(day);
444
- if (!curDay || key > curDay) byDay.set(day, key);
445
- const curMonth = byMonth.get(month);
446
- if (!curMonth || key > curMonth) byMonth.set(month, key);
447
- }
448
- const keepDaily = opts.keepDaily ?? 30;
449
- const keepMonthly = opts.keepMonthly ?? 12;
450
- const days = [...byDay.keys()].sort().slice(-keepDaily);
451
- const months = [...byMonth.keys()].sort().slice(-keepMonthly);
452
- const retained = new Set<string>();
453
- for (const d of days) retained.add(byDay.get(d)!);
454
- for (const m of months) retained.add(byMonth.get(m)!);
455
-
456
- const reachable = new Set<string>();
457
- for (const key of retained) {
458
- const m = await this.readManifestKey(key);
459
- for (const f of m.files) reachable.add(this.blobKey(f.sha256));
460
- }
461
- const allBlobs = (await this.opts.store.list(this.opts.target.bucket, `${prefix}blobs/`)).map((e) => e.key.replace(prefix, ''));
462
- const deletable = allBlobs.filter((k) => !reachable.has(k));
463
- let freedBytes = 0;
464
- for (const k of deletable) {
465
- const head = await this.opts.store.head(this.opts.target.bucket, `${prefix}${k}`);
466
- freedBytes += head?.size ?? 0;
467
- }
468
- const previewId = randomBytes(16).toString('hex');
469
- nodeFs.writeFileSync(
470
- path.join(this.opts.previewDir, `${previewId}.gc.json`),
471
- JSON.stringify({ previewId, deletable, freedBytes, ts: Date.now() }),
472
- 'utf-8',
473
- );
474
- return { retainedManifests: retained.size, trashManifests: all.length - retained.size, deletableBlobs: deletable, freedBytes, previewId };
475
- }
476
-
477
- async gcApply(req: { previewId: string; confirm: true }): Promise<{ ok: boolean; deleted: number; freedBytes: number }> {
478
- if (req.confirm !== true) throw Object.assign(new Error('gc apply requires confirm:true'), { phase: 'validate', code: 'CONFIRM_REQUIRED' });
479
- const pvPath = path.join(this.opts.previewDir, `${req.previewId}.gc.json`);
480
- let saved: { deletable: string[]; freedBytes: number };
481
- try {
482
- saved = JSON.parse(nodeFs.readFileSync(pvPath, 'utf-8')) as { deletable: string[]; freedBytes: number };
483
- } catch {
484
- throw Object.assign(new Error('gc preview not found or expired'), { phase: 'validate', code: 'STALE_PREVIEW' });
485
- }
486
- const prefix = this.opts.target.prefix;
487
- await this.opts.store.deleteKeys(this.opts.target.bucket, saved.deletable.map((k) => `${prefix}${k}`));
488
- try {
489
- nodeFs.rmSync(pvPath, { force: true });
490
- } catch {}
491
- return { ok: true, deleted: saved.deletable.length, freedBytes: saved.freedBytes };
492
- }
493
-
494
- private async readManifestKey(key: string): Promise<BackupManifest> {
495
- const tmp = path.join(require('node:os').tmpdir(), `bk-mf-${randomBytes(4).toString('hex')}`);
496
- nodeFs.mkdirSync(tmp, { recursive: true });
497
- try {
498
- await this.opts.store.get(this.opts.target.bucket, key, tmp);
499
- return JSON.parse(nodeFs.readFileSync(path.join(tmp, key), 'utf-8')) as BackupManifest;
500
- } finally {
501
- try {
502
- nodeFs.rmSync(tmp, { recursive: true, force: true });
503
- } catch {}
504
- }
505
- }
506
- }