omp-config-crypt 0.6.3 → 0.6.5

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.
@@ -0,0 +1,522 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID, createHash } from "node:crypto";
4
+ import {
5
+ assertSafeTarget,
6
+ atomicWriteFile,
7
+ configRoot,
8
+ isPidAlive,
9
+ LOCK_FILE,
10
+ readLockFile,
11
+ RECOVERY_LOCK_FILE,
12
+ withSyncLock,
13
+ } from "./sync-files.js";
14
+ import {
15
+ getSyncPlanTransaction,
16
+ STATE_FILE,
17
+ SENTINEL_DELETED,
18
+ } from "./sync-plan.js";
19
+
20
+ export { LOCK_FILE };
21
+
22
+ function fileSha256(bufOrStr) {
23
+ if (bufOrStr === null || bufOrStr === undefined) return SENTINEL_DELETED;
24
+ return createHash("sha256").update(bufOrStr).digest("hex");
25
+ }
26
+
27
+ function ensureDir(abs) {
28
+ if (!fs.existsSync(abs)) fs.mkdirSync(abs, { recursive: true });
29
+ }
30
+
31
+ function fsyncPath(abs) {
32
+ try {
33
+ const fd = fs.openSync(abs, "r");
34
+ try {
35
+ fs.fsyncSync(fd);
36
+ } finally {
37
+ fs.closeSync(fd);
38
+ }
39
+ } catch {}
40
+ }
41
+
42
+ function writeJournalAtomic(journalPath, journal) {
43
+ atomicWriteFile(journalPath, `${JSON.stringify(journal, null, 2)}\n`, 0o600);
44
+ }
45
+
46
+ function currentHash(abs) {
47
+ if (!fs.existsSync(abs)) return SENTINEL_DELETED;
48
+ const st = fs.lstatSync(abs);
49
+ if (st.isSymbolicLink() || !st.isFile()) {
50
+ throw new Error(`Unsupported target type at '${abs}'`);
51
+ }
52
+ return fileSha256(fs.readFileSync(abs));
53
+ }
54
+
55
+ function currentMode(abs) {
56
+ if (!fs.existsSync(abs)) return null;
57
+ return fs.lstatSync(abs).mode & 0o777;
58
+ }
59
+
60
+ function resolveEntryAbs(root, entry) {
61
+ return assertSafeTarget(root, entry.rel).abs;
62
+ }
63
+
64
+ function allowedHashes(entry) {
65
+ const recovery = entry.recoveryStatus || null;
66
+ if (recovery === "restored") return new Set([entry.origHash]);
67
+ if (recovery === "rollbackIntent") return new Set([entry.origHash, entry.plannedHash]);
68
+ if (entry.status === "pending") return new Set([entry.origHash]);
69
+ if (entry.status === "intent") return new Set([entry.origHash, entry.plannedHash]);
70
+ if (entry.status === "completed") return new Set([entry.plannedHash]);
71
+ throw new Error(`Unsupported journal entry status '${entry.status}'`);
72
+ }
73
+
74
+ function validateJournalStructure(journal) {
75
+ if (!journal || typeof journal !== "object" || Array.isArray(journal)) {
76
+ throw new Error("Invalid journal: root must be an object");
77
+ }
78
+ if (journal.version !== 2) {
79
+ throw new Error("Legacy journal cannot be verified; manual recovery required");
80
+ }
81
+ if (typeof journal.transactionId !== "string" || !journal.transactionId) {
82
+ throw new Error("Invalid journal: missing transactionId");
83
+ }
84
+ if (!Array.isArray(journal.entries) || !Array.isArray(journal.createdDirectories)) {
85
+ throw new Error("Invalid journal: entries/createdDirectories must be arrays");
86
+ }
87
+ return journal;
88
+ }
89
+
90
+ function validateBackupAndTargets(root, backupDir, journal) {
91
+ validateJournalStructure(journal);
92
+
93
+ for (const entry of journal.entries) {
94
+ if (!entry || typeof entry !== "object") throw new Error("Invalid journal entry");
95
+ if (entry.root !== "agent" && entry.root !== "omp") throw new Error("Invalid journal entry root");
96
+ if (typeof entry.rel !== "string" || !entry.rel) throw new Error("Invalid journal entry rel");
97
+
98
+ resolveEntryAbs(root, entry);
99
+
100
+ if (entry.existedBefore) {
101
+ if (typeof entry.backupFile !== "string" || !entry.backupFile.startsWith("files/")) {
102
+ throw new Error(`Missing backup reference for '${entry.rel}'`);
103
+ }
104
+ const backupAbs = path.resolve(backupDir, entry.backupFile);
105
+ if (!backupAbs.startsWith(path.resolve(backupDir) + path.sep)) {
106
+ throw new Error(`Backup path escapes backup directory for '${entry.rel}'`);
107
+ }
108
+ if (!fs.existsSync(backupAbs)) {
109
+ throw new Error(`Missing backup integrity for '${entry.rel}'`);
110
+ }
111
+ const backupHash = fileSha256(fs.readFileSync(backupAbs));
112
+ if (backupHash !== entry.origHash) {
113
+ throw new Error(`Backup integrity mismatch for '${entry.rel}'`);
114
+ }
115
+ } else if (entry.backupFile) {
116
+ throw new Error(`Unexpected backup for new file '${entry.rel}'`);
117
+ }
118
+
119
+ const abs = resolveEntryAbs(root, entry);
120
+ const actual = currentHash(abs);
121
+ if (!allowedHashes(entry).has(actual)) {
122
+ throw new Error(`Target '${entry.rel}' modified after sync; rollback refused`);
123
+ }
124
+ }
125
+
126
+ if (journal.stateGuard) {
127
+ const stateAbs = path.join(root, STATE_FILE);
128
+ const stateEntry = journal.entries.find((entry) => entry.rel === STATE_FILE);
129
+ if (!stateEntry) {
130
+ const existed = fs.existsSync(stateAbs);
131
+ const hash = existed ? fileSha256(fs.readFileSync(stateAbs)) : SENTINEL_DELETED;
132
+ const mode = existed ? currentMode(stateAbs) : null;
133
+ if (
134
+ Boolean(journal.stateGuard.existed) !== existed ||
135
+ journal.stateGuard.hash !== hash ||
136
+ journal.stateGuard.mode !== mode
137
+ ) {
138
+ throw new Error("Sync state baseline modified; rollback refused");
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ function restoreEntry(root, backupDir, entry) {
145
+ const abs = resolveEntryAbs(root, entry);
146
+ ensureDir(path.dirname(abs));
147
+ if (entry.existedBefore) {
148
+ const backupAbs = path.join(backupDir, entry.backupFile);
149
+ atomicWriteFile(abs, fs.readFileSync(backupAbs), entry.origMode ?? 0o600);
150
+ } else if (fs.existsSync(abs)) {
151
+ fs.unlinkSync(abs);
152
+ }
153
+ }
154
+
155
+ function cleanupTempsAndEmptyDirs(root, journal) {
156
+ for (const entry of journal.entries) {
157
+ if (!entry.tempRel) continue;
158
+ try {
159
+ const candidate = path.join(path.dirname(resolveEntryAbs(root, entry)), entry.tempRel);
160
+ if (fs.existsSync(candidate)) fs.unlinkSync(candidate);
161
+ } catch {}
162
+ }
163
+ for (const rel of [...journal.createdDirectories].reverse()) {
164
+ try {
165
+ const abs = assertSafeTarget(root, rel).abs;
166
+ if (fs.existsSync(abs) && fs.readdirSync(abs).length === 0) fs.rmdirSync(abs);
167
+ } catch {}
168
+ }
169
+ }
170
+
171
+ function recoverJournal(root, backupDir, journal, { renameBackup = true } = {}) {
172
+ validateBackupAndTargets(root, backupDir, journal);
173
+ const journalPath = path.join(backupDir, "journal.json");
174
+ journal.status = "rolling_back";
175
+ writeJournalAtomic(journalPath, journal);
176
+
177
+ for (const entry of [...journal.entries].reverse()) {
178
+ entry.recoveryStatus = "rollbackIntent";
179
+ writeJournalAtomic(journalPath, journal);
180
+ restoreEntry(root, backupDir, entry);
181
+ entry.recoveryStatus = "restored";
182
+ writeJournalAtomic(journalPath, journal);
183
+ }
184
+
185
+ cleanupTempsAndEmptyDirs(root, journal);
186
+ journal.status = "rolled_back";
187
+ writeJournalAtomic(journalPath, journal);
188
+
189
+ let rolledBackFrom = backupDir;
190
+ if (renameBackup) {
191
+ const base = path.basename(backupDir).replace(/^\.import-backup-/, "");
192
+ let rolled = path.join(root, `.rolled-back-${base}`);
193
+ if (fs.existsSync(rolled)) rolled = `${rolled}-${randomUUID()}`;
194
+ fs.renameSync(backupDir, rolled);
195
+ rolledBackFrom = rolled;
196
+ }
197
+
198
+ return {
199
+ files: journal.entries.filter((entry) => entry.rel !== STATE_FILE).length,
200
+ rolledBackFrom,
201
+ };
202
+ }
203
+
204
+ function observeStateGuard(readContext, root) {
205
+ const stateAbs = path.join(root, STATE_FILE);
206
+ const bytes = readContext.readFile(stateAbs);
207
+ if (bytes === undefined) {
208
+ return { existed: false, hash: SENTINEL_DELETED, mode: null };
209
+ }
210
+ return {
211
+ existed: true,
212
+ hash: fileSha256(bytes),
213
+ mode: readContext.fileMode(stateAbs),
214
+ };
215
+ }
216
+
217
+ function ensureParents(abs, createdDirectories) {
218
+ const stack = [];
219
+ let probe = path.dirname(abs);
220
+ while (probe && probe !== path.dirname(probe) && !fs.existsSync(probe)) {
221
+ stack.push(probe);
222
+ probe = path.dirname(probe);
223
+ }
224
+ for (const dir of stack.reverse()) {
225
+ fs.mkdirSync(dir);
226
+ createdDirectories.push(dir);
227
+ }
228
+ }
229
+
230
+ export function commitFileTransaction(root, transaction, lock) {
231
+ const agentDir = path.resolve(root);
232
+ const readContext = transaction.readContext;
233
+ const entriesMap = transaction.entries;
234
+ if (!readContext || !entriesMap) {
235
+ throw new Error("Invalid sync transaction: missing rendered entries");
236
+ }
237
+ if (!transaction.needsCommit) {
238
+ return { filesWritten: 0, backupDir: undefined, success: true };
239
+ }
240
+
241
+ readContext.verify();
242
+ const stateGuard = transaction.stateGuard || observeStateGuard(readContext, agentDir);
243
+
244
+ const backupName = `.import-backup-${Date.now()}-${randomUUID()}`;
245
+ const backupDir = path.join(agentDir, backupName);
246
+ const filesDir = path.join(backupDir, "files");
247
+ ensureDir(filesDir);
248
+ const journalPath = path.join(backupDir, "journal.json");
249
+
250
+ const journalEntries = [];
251
+ let backupIndex = 0;
252
+ for (const entry of entriesMap.values()) {
253
+ const abs = entry.abs;
254
+ const existed = fs.existsSync(abs);
255
+ let origHash = SENTINEL_DELETED;
256
+ let origMode = null;
257
+ let backupFile = null;
258
+ if (existed) {
259
+ const bytes = fs.readFileSync(abs);
260
+ origHash = fileSha256(bytes);
261
+ origMode = fs.lstatSync(abs).mode & 0o777;
262
+ backupFile = `files/${backupIndex++}`;
263
+ fs.writeFileSync(path.join(backupDir, backupFile), bytes);
264
+ try {
265
+ fs.chmodSync(path.join(backupDir, backupFile), origMode);
266
+ } catch {}
267
+ fsyncPath(path.join(backupDir, backupFile));
268
+ }
269
+ journalEntries.push({
270
+ root:
271
+ entry.rel.startsWith("plugins/") ||
272
+ entry.rel.startsWith("tools/") ||
273
+ entry.rel.startsWith("hooks/")
274
+ ? "omp"
275
+ : "agent",
276
+ rel: entry.rel,
277
+ backupFile,
278
+ existedBefore: existed,
279
+ origHash,
280
+ origMode,
281
+ plannedHash: entry.operation === "delete" ? SENTINEL_DELETED : fileSha256(entry.content),
282
+ plannedMode: entry.operation === "delete" ? null : entry.mode,
283
+ type: entry.operation,
284
+ status: "pending",
285
+ tempRel: null,
286
+ recoveryStatus: null,
287
+ });
288
+ }
289
+
290
+ const stateAbs = path.join(agentDir, STATE_FILE);
291
+ const stateBytes = Buffer.from(`${JSON.stringify(transaction.nextState, null, 2)}\n`, "utf8");
292
+ const stateExisted = fs.existsSync(stateAbs);
293
+ let stateOrigHash = SENTINEL_DELETED;
294
+ let stateOrigMode = null;
295
+ let stateBackupFile = null;
296
+ if (stateExisted) {
297
+ const prev = fs.readFileSync(stateAbs);
298
+ stateOrigHash = fileSha256(prev);
299
+ stateOrigMode = fs.lstatSync(stateAbs).mode & 0o777;
300
+ stateBackupFile = `files/${backupIndex++}`;
301
+ fs.writeFileSync(path.join(backupDir, stateBackupFile), prev);
302
+ fsyncPath(path.join(backupDir, stateBackupFile));
303
+ }
304
+ journalEntries.push({
305
+ root: "agent",
306
+ rel: STATE_FILE,
307
+ backupFile: stateBackupFile,
308
+ existedBefore: stateExisted,
309
+ origHash: stateOrigHash,
310
+ origMode: stateOrigMode,
311
+ plannedHash: fileSha256(stateBytes),
312
+ plannedMode: stateOrigMode ?? 0o600,
313
+ type: "write",
314
+ status: "pending",
315
+ tempRel: null,
316
+ recoveryStatus: null,
317
+ });
318
+
319
+ const journal = {
320
+ version: 2,
321
+ transactionId: lock.transactionId,
322
+ timestamp: new Date().toISOString(),
323
+ status: "preparing",
324
+ entries: journalEntries,
325
+ createdDirectories: [],
326
+ stateGuard,
327
+ };
328
+ writeJournalAtomic(journalPath, journal);
329
+ lock.setBackupDir(backupName);
330
+ journal.status = "in_progress";
331
+ writeJournalAtomic(journalPath, journal);
332
+
333
+ const createdDirectories = [];
334
+ try {
335
+ for (const entry of journal.entries) {
336
+ const abs = resolveEntryAbs(agentDir, entry);
337
+ if (currentHash(abs) !== entry.origHash) {
338
+ throw new Error(`Concurrent modification detected: '${entry.rel}' changed`);
339
+ }
340
+
341
+ entry.status = "intent";
342
+ writeJournalAtomic(journalPath, journal);
343
+
344
+ if (entry.type === "write") {
345
+ ensureParents(abs, createdDirectories);
346
+ const content =
347
+ entry.rel === STATE_FILE ? stateBytes : entriesMap.get(entry.rel).content;
348
+ const mode = entry.plannedMode ?? 0o600;
349
+ const tempName = `.${path.basename(abs)}.tmp-${randomUUID()}`;
350
+ const tempAbs = path.join(path.dirname(abs), tempName);
351
+ entry.tempRel = tempName;
352
+ writeJournalAtomic(journalPath, journal);
353
+ fs.writeFileSync(tempAbs, content, { mode });
354
+ fsyncPath(tempAbs);
355
+ fs.renameSync(tempAbs, abs);
356
+ try {
357
+ fs.chmodSync(abs, mode);
358
+ } catch {}
359
+ } else if (entry.type === "delete") {
360
+ if (fs.existsSync(abs)) fs.unlinkSync(abs);
361
+ } else {
362
+ throw new Error(`Unsupported entry type '${entry.type}'`);
363
+ }
364
+
365
+ entry.status = "completed";
366
+ entry.tempRel = null;
367
+ writeJournalAtomic(journalPath, journal);
368
+ }
369
+
370
+ journal.createdDirectories = createdDirectories.map((abs) =>
371
+ path.relative(agentDir, abs).replace(/\\/g, "/")
372
+ );
373
+ journal.status = "completed";
374
+ writeJournalAtomic(journalPath, journal);
375
+
376
+ return {
377
+ success: true,
378
+ filesWritten: journal.entries.filter((entry) => entry.rel !== STATE_FILE).length,
379
+ backupDir,
380
+ };
381
+ } catch (error) {
382
+ try {
383
+ recoverJournal(agentDir, backupDir, journal, { renameBackup: true });
384
+ } catch (recoveryError) {
385
+ lock.preserveForRecovery();
386
+ const err = new Error(
387
+ `Sync failed and automatic recovery failed; manual recovery required: ${error.message}; recovery: ${recoveryError.message}`
388
+ );
389
+ err.cause = recoveryError;
390
+ throw err;
391
+ }
392
+ const err = new Error(`Sync failed: ${error.message}`);
393
+ err.cause = error;
394
+ throw err;
395
+ }
396
+ }
397
+
398
+ export function applySyncPlan(plan, root = configRoot()) {
399
+ if (plan.conflicts && plan.conflicts.length > 0) {
400
+ const detail = plan.conflicts
401
+ .map((c) => `${c.id || "(unknown)"}: ${c.reason}`)
402
+ .join("; ");
403
+ const err = new Error(
404
+ `Cannot apply sync plan: ${plan.conflicts.length} conflict(s) detected (${detail}).`
405
+ );
406
+ err.conflicts = plan.conflicts;
407
+ throw err;
408
+ }
409
+ if (plan.blocked && plan.blocked.length > 0) {
410
+ const detail = plan.blocked
411
+ .map((b) => `${b.id || "(unknown)"}: ${b.reason}`)
412
+ .join("; ");
413
+ const err = new Error(
414
+ `Cannot apply sync plan: ${plan.blocked.length} action(s) are blocked (${detail}).`
415
+ );
416
+ err.blocked = plan.blocked;
417
+ throw err;
418
+ }
419
+
420
+ const agentDir = path.resolve(root);
421
+ const transaction = getSyncPlanTransaction(plan, agentDir);
422
+ if (!transaction.needsCommit) {
423
+ return { success: true, filesWritten: 0, backupDir: undefined };
424
+ }
425
+
426
+ return withSyncLock(agentDir, (lock) => commitFileTransaction(agentDir, transaction, lock));
427
+ }
428
+
429
+ function acquireRecoveryLock(root) {
430
+ const recoveryPath = path.join(root, RECOVERY_LOCK_FILE);
431
+ let fd;
432
+ try {
433
+ fd = fs.openSync(recoveryPath, "wx");
434
+ } catch {
435
+ throw new Error(`Sync recovery lock active at ${recoveryPath}; manual recovery required`);
436
+ }
437
+ fs.writeSync(
438
+ fd,
439
+ `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`
440
+ );
441
+ fs.closeSync(fd);
442
+ return () => {
443
+ try {
444
+ fs.unlinkSync(recoveryPath);
445
+ } catch {}
446
+ };
447
+ }
448
+
449
+ function loadLatestJournal(agentDir) {
450
+ const backups = fs
451
+ .readdirSync(agentDir, { withFileTypes: true })
452
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(".import-backup-"))
453
+ .map((entry) => entry.name)
454
+ .sort()
455
+ .reverse();
456
+ if (backups.length === 0) {
457
+ throw new Error("No import backup available to roll back");
458
+ }
459
+ const latest = backups[0];
460
+ const backupDir = path.join(agentDir, latest);
461
+ const journalPath = path.join(backupDir, "journal.json");
462
+ if (!fs.existsSync(journalPath)) {
463
+ throw new Error("Legacy journal cannot be verified; manual recovery required");
464
+ }
465
+ let journal;
466
+ try {
467
+ journal = JSON.parse(fs.readFileSync(journalPath, "utf8"));
468
+ } catch {
469
+ throw new Error("Legacy journal cannot be verified; manual recovery required");
470
+ }
471
+ if (journal.version !== 2) {
472
+ throw new Error("Legacy journal cannot be verified; manual recovery required");
473
+ }
474
+ return { latest, backupDir, journal };
475
+ }
476
+
477
+ export function rollbackSync(root = configRoot()) {
478
+ const agentDir = path.resolve(root);
479
+ if (!fs.existsSync(agentDir)) {
480
+ throw new Error(`Root directory does not exist: ${agentDir}`);
481
+ }
482
+
483
+ const releaseRecovery = acquireRecoveryLock(agentDir);
484
+ try {
485
+ let lock = null;
486
+ try {
487
+ lock = readLockFile(agentDir);
488
+ } catch (error) {
489
+ throw error;
490
+ }
491
+
492
+ if (lock && isPidAlive(lock.content.pid)) {
493
+ throw new Error(
494
+ `Active sync lock is still running (pid ${lock.content.pid}); rollback refused`
495
+ );
496
+ }
497
+
498
+ const { latest, backupDir, journal } = loadLatestJournal(agentDir);
499
+
500
+ if (lock) {
501
+ if (
502
+ lock.content.transactionId !== journal.transactionId ||
503
+ lock.content.backupDir !== latest
504
+ ) {
505
+ throw new Error("Sync lock does not match journal; manual recovery required");
506
+ }
507
+ const result = recoverJournal(agentDir, backupDir, journal, { renameBackup: true });
508
+ try {
509
+ fs.unlinkSync(lock.path);
510
+ } catch {}
511
+ return result;
512
+ }
513
+
514
+ return withSyncLock(
515
+ agentDir,
516
+ () => recoverJournal(agentDir, backupDir, journal, { renameBackup: true }),
517
+ { allowDuringRecovery: true, transactionId: journal.transactionId }
518
+ );
519
+ } finally {
520
+ releaseRecovery();
521
+ }
522
+ }