omp-config-crypt 0.6.4 → 0.6.6

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/bin/omp-sync.js CHANGED
@@ -712,7 +712,7 @@ async function main() {
712
712
  process.exit(1);
713
713
  }
714
714
  } catch (err) {
715
- console.error(`[error] ${err.message || err}`);
715
+ console.error(`[error] ${err.stack || err.message || err}`);
716
716
  process.exit(1);
717
717
  }
718
718
  }
package/index.js CHANGED
@@ -146,6 +146,8 @@ export {
146
146
  };
147
147
 
148
148
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
149
+ // Pinned to Node's historical defaults so archives stay decryptable across Node versions.
150
+ const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
149
151
 
150
152
  /**
151
153
  * Collect is now defined strictly as the read-only file projection of public resources.
@@ -286,7 +288,7 @@ export function decryptArchiveBlob(blob, pass) {
286
288
  const iv = blob.subarray(o, (o += 12));
287
289
  const tag = blob.subarray(o, (o += 16));
288
290
  const ct = blob.subarray(o);
289
- const key = scryptSync(pass, salt, 32);
291
+ const key = scryptSync(pass, salt, 32, SCRYPT_PARAMS);
290
292
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
291
293
  decipher.setAuthTag(tag);
292
294
 
@@ -308,7 +310,7 @@ export function encryptArchivePayload(payload, pass) {
308
310
  const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
309
311
  const salt = randomBytes(16);
310
312
  const iv = randomBytes(12);
311
- const key = scryptSync(pass, salt, 32);
313
+ const key = scryptSync(pass, salt, 32, SCRYPT_PARAMS);
312
314
  const cipher = createCipheriv("aes-256-gcm", key, iv);
313
315
  const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
314
316
  return Buffer.concat([MAGIC, salt, iv, cipher.getAuthTag(), ct]);
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
7
10
  "bin": {
8
11
  "omp-sync": "./bin/omp-sync.js"
9
12
  },
@@ -1,7 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
- import { exec, execSync } from "node:child_process";
4
+ import { randomUUID } from "node:crypto";
5
+ import { exec, execSync, execFileSync } from "node:child_process";
5
6
  import { promisify } from "node:util";
6
7
 
7
8
  const execAsync = promisify(exec);
@@ -225,10 +226,20 @@ export function getCronStatus() {
225
226
  }
226
227
  }
227
228
 
229
+ /**
230
+ * A valid cron schedule is exactly 5 whitespace-separated fields of digits, *, -, /, comma.
231
+ */
232
+ export function validateCronSchedule(s) {
233
+ return /^[\d*,\-/]+(?: [\d*,\-/]+){4}$/.test(String(s ?? ""));
234
+ }
235
+
228
236
  /**
229
237
  * Install scheduled maintenance into system crontab.
230
238
  */
231
239
  export function installCron(schedule = "0 3 * * *", command = null) {
240
+ if (!validateCronSchedule(schedule)) {
241
+ throw new Error("invalid cron schedule: expected 5 fields of digits, *, -, /, comma");
242
+ }
232
243
  try {
233
244
  let current = "";
234
245
  try {
@@ -239,7 +250,15 @@ export function installCron(schedule = "0 3 * * *", command = null) {
239
250
  const cmd = command || "npx -y omp-config-crypt maint --force > /dev/null 2>&1";
240
251
  lines.push(`${schedule} ${cmd} ${CRON_TAG}`);
241
252
 
242
- execSync(`(echo "${lines.join("\n")}") | crontab -`);
253
+ const tmp = path.join(os.tmpdir(), `omp-crontab-${randomUUID()}`);
254
+ fs.writeFileSync(tmp, `${lines.join("\n")}\n`, { mode: 0o600 });
255
+ try {
256
+ execFileSync("crontab", [tmp], { stdio: "pipe" });
257
+ } finally {
258
+ try {
259
+ fs.unlinkSync(tmp);
260
+ } catch {}
261
+ }
243
262
  return { success: true, schedule, command: cmd };
244
263
  } catch (err) {
245
264
  return { success: false, error: err.message };
@@ -258,7 +277,15 @@ export function removeCron() {
258
277
 
259
278
  const lines = current.split("\n").filter((l) => !l.includes(CRON_TAG) && l.trim().length > 0);
260
279
  if (lines.length > 0) {
261
- execSync(`(echo "${lines.join("\n")}") | crontab -`);
280
+ const tmp = path.join(os.tmpdir(), `omp-crontab-${randomUUID()}`);
281
+ fs.writeFileSync(tmp, `${lines.join("\n")}\n`, { mode: 0o600 });
282
+ try {
283
+ execFileSync("crontab", [tmp], { stdio: "pipe" });
284
+ } finally {
285
+ try {
286
+ fs.unlinkSync(tmp);
287
+ } catch {}
288
+ }
262
289
  } else {
263
290
  execSync("crontab -r 2>/dev/null || true");
264
291
  }
package/src/rehydrator.js CHANGED
@@ -6,6 +6,16 @@ import { ompHome } from "./sync-files.js";
6
6
 
7
7
  const LINKS_FILE = ".plugin-links.json";
8
8
 
9
+ /**
10
+ * npm on Windows is npm.cmd; spawning .cmd files requires shell:true (Node CVE-2024-27980).
11
+ * Args are validated snapshot-derived constants, so no shell metacharacters can appear.
12
+ */
13
+ export function resolveNpmCommand() {
14
+ return process.platform === "win32"
15
+ ? { file: "npm.cmd", shell: true }
16
+ : { file: "npm", shell: false };
17
+ }
18
+
9
19
  /**
10
20
  * Scan plugins directory node_modules for symlinks and return a map of name -> targetPath.
11
21
  */
@@ -145,10 +155,12 @@ export function rehydratePlugins(root, options = {}) {
145
155
  results.npmInstalled.push(...missing.npmDependencies);
146
156
  } else {
147
157
  try {
148
- execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund"], {
158
+ const npmCmd = resolveNpmCommand();
159
+ execFileSync(npmCmd.file, ["install", "--omit=dev", "--no-audit", "--no-fund"], {
149
160
  cwd: pluginsDir,
150
161
  stdio: "pipe",
151
162
  timeout: 60000,
163
+ shell: npmCmd.shell,
152
164
  });
153
165
  results.npmInstalled.push(...missing.npmDependencies);
154
166
  } catch (err) {
@@ -165,11 +177,18 @@ export function rehydratePlugins(root, options = {}) {
165
177
  } catch {}
166
178
  }
167
179
 
168
- // Known candidate fallback directories for common local plugins
180
+ // Known candidate fallback directories for common local plugins.
181
+ // Extra dev roots come from OMP_PLUGIN_DEV_DIRS (path.delimiter-separated); no host-specific paths.
182
+ const devRoots = (process.env.OMP_PLUGIN_DEV_DIRS || "")
183
+ .split(path.delimiter)
184
+ .filter(Boolean);
169
185
  const candidateDirs = {
170
- "@omp/plugin-rsi": ["/opt/project/omp-rsi", path.join(os.homedir(), "omp-rsi")],
171
- "omp-config-crypt": ["/root/omp-config-crypt", path.join(os.homedir(), "omp-config-crypt")],
186
+ "@omp/plugin-rsi": [path.join(os.homedir(), "omp-rsi")],
187
+ "omp-config-crypt": [path.join(os.homedir(), "omp-config-crypt")],
172
188
  };
189
+ for (const [name, dirs] of Object.entries(candidateDirs)) {
190
+ for (const root of devRoots) dirs.push(path.join(root, name));
191
+ }
173
192
 
174
193
  // 3. Resolve and repair linked plugins
175
194
  const pluginsToLink = Array.from(
@@ -197,10 +216,12 @@ export function rehydratePlugins(root, options = {}) {
197
216
  if (!targetDir || !fs.existsSync(targetDir)) {
198
217
  if (!dryRun) {
199
218
  try {
200
- execFileSync("npm", ["install", `${name}@latest`, "--omit=dev", "--no-audit", "--no-fund"], {
219
+ const npmCmd = resolveNpmCommand();
220
+ execFileSync(npmCmd.file, ["install", `${name}@latest`, "--omit=dev", "--no-audit", "--no-fund"], {
201
221
  cwd: pluginsDir,
202
222
  stdio: "pipe",
203
223
  timeout: 60000,
224
+ shell: npmCmd.shell,
204
225
  });
205
226
  results.npmInstalled.push(name);
206
227
  continue;
package/src/sync-files.js CHANGED
@@ -510,6 +510,32 @@ export function isPidAlive(pid) {
510
510
  }
511
511
  }
512
512
 
513
+ const TERMINAL_JOURNAL_STATUSES = new Set(["completed", "rolled_back"]);
514
+
515
+ /**
516
+ * True when any .import-backup-* dir holds a journal that is missing, unreadable,
517
+ * or non-terminal — i.e. a crashed transaction that still needs rollback, not lock removal.
518
+ */
519
+ function hasUnfinishedJournal(agentDir) {
520
+ let entries;
521
+ try {
522
+ entries = fs.readdirSync(agentDir, { withFileTypes: true });
523
+ } catch {
524
+ return false;
525
+ }
526
+ for (const entry of entries) {
527
+ if (!entry.isDirectory() || !entry.name.startsWith(".import-backup-")) continue;
528
+ let journal;
529
+ try {
530
+ journal = JSON.parse(fs.readFileSync(path.join(agentDir, entry.name, "journal.json"), "utf8"));
531
+ } catch {
532
+ return true;
533
+ }
534
+ if (!TERMINAL_JOURNAL_STATUSES.has(journal.status)) return true;
535
+ }
536
+ return false;
537
+ }
538
+
513
539
  export function withSyncLock(root, operation, options = {}) {
514
540
  const agentDir = path.resolve(root);
515
541
  if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true });
@@ -529,9 +555,28 @@ export function withSyncLock(root, operation, options = {}) {
529
555
  `Sync lock could not be created at ${lockPath}: permission denied (${error.code}). Check directory ACL/permissions; manual recovery may be required.`
530
556
  );
531
557
  }
532
- throw new Error(
533
- `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
534
- );
558
+ // EEXIST (usual case): recover from a stale lock left behind by an exited process,
559
+ // but only when no unfinished transaction journal exists (crash recovery stays manual).
560
+ let stale = false;
561
+ try {
562
+ const record = JSON.parse(fs.readFileSync(lockPath, "utf8"));
563
+ if (record && record.pid != null && !isPidAlive(record.pid) && !hasUnfinishedJournal(agentDir)) {
564
+ stale = true;
565
+ }
566
+ } catch {}
567
+ if (!stale) {
568
+ throw new Error(
569
+ `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
570
+ );
571
+ }
572
+ try {
573
+ fs.unlinkSync(lockPath);
574
+ fd = fs.openSync(lockPath, "wx");
575
+ } catch {
576
+ throw new Error(
577
+ `Sync lock active at ${lockPath}. Another sync may be running, or a previous sync failed. Run rollback or remove lock if stale.`
578
+ );
579
+ }
535
580
  }
536
581
 
537
582
  const content = {
package/src/sync-plan.js CHANGED
@@ -738,11 +738,12 @@ export function planSync(snapshot, root = configRoot()) {
738
738
  try {
739
739
  localNamespace = resolveSyncNamespace(policy, state);
740
740
  } catch (error) {
741
- blocked.push({ reason: error.message });
741
+ blocked.push({ id: "namespace", reason: error.message });
742
742
  return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
743
743
  }
744
744
  if (localNamespace && localNamespace !== validSnapshot.namespace) {
745
745
  blocked.push({
746
+ id: "namespace",
746
747
  reason: `Namespace mismatch: remote is '${validSnapshot.namespace}', local is '${localNamespace}'. Cannot take over different configuration set.`,
747
748
  });
748
749
  return { namespace: validSnapshot.namespace, actions: [], conflicts: [], blocked, prerequisites: [], writes: {} };
@@ -25,7 +25,7 @@ function fileSha256(bufOrStr) {
25
25
  }
26
26
 
27
27
  function ensureDir(abs) {
28
- if (!fs.existsSync(abs)) fs.mkdirSync(abs, { recursive: true });
28
+ if (!fs.existsSync(abs)) fs.mkdirSync(abs, { recursive: true, mode: 0o700 });
29
29
  }
30
30
 
31
31
  function fsyncPath(abs) {
@@ -222,7 +222,7 @@ function ensureParents(abs, createdDirectories) {
222
222
  probe = path.dirname(probe);
223
223
  }
224
224
  for (const dir of stack.reverse()) {
225
- fs.mkdirSync(dir);
225
+ fs.mkdirSync(dir, { mode: 0o700 });
226
226
  createdDirectories.push(dir);
227
227
  }
228
228
  }
@@ -373,6 +373,10 @@ export function commitFileTransaction(root, transaction, lock) {
373
373
  journal.status = "completed";
374
374
  writeJournalAtomic(journalPath, journal);
375
375
 
376
+ try {
377
+ pruneBackups(agentDir);
378
+ } catch {}
379
+
376
380
  return {
377
381
  success: true,
378
382
  filesWritten: journal.entries.filter((entry) => entry.rel !== STATE_FILE).length,
@@ -397,15 +401,21 @@ export function commitFileTransaction(root, transaction, lock) {
397
401
 
398
402
  export function applySyncPlan(plan, root = configRoot()) {
399
403
  if (plan.conflicts && plan.conflicts.length > 0) {
404
+ const detail = plan.conflicts
405
+ .map((c) => `${c.id || "(unknown)"}: ${c.reason}`)
406
+ .join("; ");
400
407
  const err = new Error(
401
- `Cannot apply sync plan: ${plan.conflicts.length} conflict(s) detected.`
408
+ `Cannot apply sync plan: ${plan.conflicts.length} conflict(s) detected (${detail}).`
402
409
  );
403
410
  err.conflicts = plan.conflicts;
404
411
  throw err;
405
412
  }
406
413
  if (plan.blocked && plan.blocked.length > 0) {
414
+ const detail = plan.blocked
415
+ .map((b) => `${b.id || "(unknown)"}: ${b.reason}`)
416
+ .join("; ");
407
417
  const err = new Error(
408
- `Cannot apply sync plan: ${plan.blocked.length} action(s) are blocked.`
418
+ `Cannot apply sync plan: ${plan.blocked.length} action(s) are blocked (${detail}).`
409
419
  );
410
420
  err.blocked = plan.blocked;
411
421
  throw err;
@@ -440,6 +450,20 @@ function acquireRecoveryLock(root) {
440
450
  };
441
451
  }
442
452
 
453
+ /**
454
+ * Removes all but the newest `keep` .import-backup-* directories (name-sorted, oldest first).
455
+ */
456
+ export function pruneBackups(agentDir, keep = 3) {
457
+ const backups = fs
458
+ .readdirSync(agentDir, { withFileTypes: true })
459
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith(".import-backup-"))
460
+ .map((entry) => entry.name)
461
+ .sort();
462
+ for (const name of backups.slice(0, Math.max(0, backups.length - keep))) {
463
+ fs.rmSync(path.join(agentDir, name), { recursive: true, force: true });
464
+ }
465
+ }
466
+
443
467
  function loadLatestJournal(agentDir) {
444
468
  const backups = fs
445
469
  .readdirSync(agentDir, { withFileTypes: true })