omp-config-crypt 0.1.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,33 +1,91 @@
1
- # omp-config-crypt
1
+ # omp-config-crypt (v0.4.0)
2
2
 
3
- Encrypted export/import of omp user config and instruction files. Secrets are
4
- included as-is; the archive itself is the only protection.
3
+ Universal, zero-repair cross-platform configuration encryption and synchronization engine for `omp` (Oh My Pi).
5
4
 
6
- ## Archive
5
+ Supports both **in-OMP slash commands** and an **independent standalone CLI (`omp-sync`)**. Seamlessly synchronizes configurations across Linux (root / non-root), macOS, and Windows WSL with zero manual post-restore adjustments.
7
6
 
8
- - AES-256-GCM, key = scrypt(passphrase, random salt)
9
- - gzip payload, single binary file (`OMPCFG1\0` magic)
10
- - written with mode `0600`
7
+ ---
11
8
 
12
- Included: `config.yml`, `models.yml`, `mcp.json`, `AGENTS.md`, `STYLE.md`,
13
- `RULES.md`, and everything under `memories/`.
9
+ ## Key Features
14
10
 
15
- ## Commands
11
+ 1. **Adaptive Cross-Platform Remapping**:
12
+ - Automatically sanitizes machine-specific home paths (e.g., `/root`, `/home/user`, `/Users/alice`, `C:\Users\bob`) into a portable `{{OMP_HOME}}` placeholder.
13
+ - On import, dynamically remaps placeholders and source paths to the target host's actual `$HOME` and normalizes path separators.
14
+ 2. **Zero OMP Internal Dependency**:
15
+ - Built 100% on native Node.js built-ins (`node:crypto`, `node:fs`, `node:path`, `node:zlib`, `node:os`).
16
+ - Core `omp` binary upgrades never break or affect this tool.
17
+ 3. **Comprehensive Asset Synchronization**:
18
+ - **Core Configs**: `config.yml`, `models.yml`, `mcp.json`, `AGENTS.md`, `STYLE.md`, `RULES.md`.
19
+ - **Credentials & Tokens**: Automatic discovery and encryption of `opc-mcp-token` and `*.token` files.
20
+ - **User Extensions**: Full recursive synchronization of `~/.omp/extensions/**` (e.g. `agy.js`).
21
+ - **Skills & Knowledge**: Recursive sync of `managed-skills/**` and `memories/**`.
22
+ - **Plugins Manifest**: Syncs `plugins/omp-plugins.lock.json` for deterministic plugin tracking.
23
+ - **Strict Blacklist**: Automatically excludes SQLite runtime databases (`*.db`, `*.db-wal`, `*.db-shm`), session logs, and cache folders.
24
+ 4. **Safety & Instant Rollback**:
25
+ - Pre-existing files are automatically backed up to `.import-backup-<timestamp>/` prior to overwriting.
26
+ - One-command instant rollback (`omp-sync rollback` or `/config-rollback`).
27
+ - Non-destructive dry-run preview (`--dry-run`).
16
28
 
29
+ ---
30
+
31
+ ## Standalone CLI (`omp-sync`)
32
+
33
+ Run outside or before starting `omp` (ideal for fresh machine setup, Docker provisioning, and CI/CD):
34
+
35
+ ```bash
36
+ # Export configs locally
37
+ npx omp-config-crypt export my-backup.enc --pass "mysecret"
38
+
39
+ # Import configs locally with dry-run preview
40
+ npx omp-config-crypt import my-backup.enc --pass "mysecret" --dry-run
41
+
42
+ # Import configs locally
43
+ npx omp-config-crypt import my-backup.enc --pass "mysecret"
44
+
45
+ # Cloud Push (GitHub Gist)
46
+ npx omp-config-crypt push gist:new --pass "mysecret" --token "$GITHUB_TOKEN"
47
+
48
+ # Cloud Pull (GitHub Gist)
49
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
50
+
51
+ # Rollback to previous configuration snapshot
52
+ npx omp-config-crypt rollback
17
53
  ```
54
+
55
+ ---
56
+
57
+ ## In-OMP Slash Commands
58
+
59
+ Inside any `omp` session:
60
+
61
+ ```text
18
62
  /config-export [out.enc]
19
- /config-import <file.enc>
63
+ /config-import <file.enc> [--dry-run]
64
+ /config-push gist:new
65
+ /config-push gist:<id>
66
+ /config-push https://…
67
+ /config-pull gist:<id> [--dry-run]
68
+ /config-pull https://… [--dry-run]
69
+ /config-rollback
20
70
  ```
21
71
 
22
- Passphrase: `OMP_CONFIG_PASS`, or the prompt shown by the command.
72
+ ---
23
73
 
24
- Import backs up every overwritten file to `<agent-dir>/.import-backup-<ts>/`
25
- and asks for a restart so settings reload.
74
+ ## Environment Variables
26
75
 
27
- ## Install
76
+ | Variable | Description |
77
+ |---|---|
78
+ | `OMP_CONFIG_PASS` | Encryption/decryption passphrase for headless automation |
79
+ | `OMP_CFG_CLOUD_TOKEN` | Primary Cloud / GitHub API token (gist scope) |
80
+ | `GITHUB_TOKEN` | Fallback GitHub API token |
81
+ | `OMP_CFG_ROOT` | Override path to agent directory (default: `~/.omp/agent`) |
82
+ | `OMP_HOME` | Override path to omp root (default: `~/.omp`) |
28
83
 
29
- ```
30
- omp plugin install /root/omp-config-crypt
31
- ```
84
+ ---
85
+
86
+ ## Security Specification
32
87
 
33
- Requires a new session before the commands appear.
88
+ - **Cipher**: AES-256-GCM authenticated encryption.
89
+ - **Key Derivation**: `scrypt` with 16-byte cryptographically secure random salt (`N=16384, r=8, p=1`).
90
+ - **Archive Wire Magic**: `OMPCFG1\0` header + 16B salt + 12B IV + 16B GCM auth tag + gzip payload.
91
+ - **File Mode**: Preserves executable and read/write bits with standard `0600` / `0700` safety.
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Universal Standalone CLI for OMP Config Crypt & Sync Engine
5
+ * Operates independently of OMP runtime; zero external dependencies.
6
+ */
7
+
8
+ import readline from "node:readline";
9
+ import process from "node:process";
10
+ import {
11
+ configRoot,
12
+ exportEncrypted,
13
+ importEncrypted,
14
+ pushGist,
15
+ pullGist,
16
+ pushHttp,
17
+ pullHttp,
18
+ rollback,
19
+ parseSpec,
20
+ rehydratePlugins,
21
+ } from "../index.js";
22
+
23
+ function printHelp() {
24
+ console.log(`
25
+ Universal OMP Configuration Sync & Crypt Engine (Standalone CLI)
26
+
27
+ Usage:
28
+ omp-sync <command> [arguments] [options]
29
+
30
+ Commands:
31
+ export <outFile> Encrypt and export local OMP configs to a file
32
+ import <srcFile> Decrypt and restore OMP configs from an archive
33
+ push <gist:id|url> Encrypt and push configs to GitHub Gist or HTTP URL
34
+ pull <gist:id|url> Download and restore configs from Gist or HTTP URL
35
+ rollback Revert the most recent config restore from its backup
36
+ rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
37
+
38
+ Options:
39
+ -p, --pass <passphrase> Decryption/Encryption passphrase (or OMP_CONFIG_PASS)
40
+ -t, --token <token> Cloud token (or OMP_CFG_CLOUD_TOKEN / GITHUB_TOKEN)
41
+ -r, --root <path> Agent configuration root (default: ~/.omp/agent)
42
+ -d, --dry-run Simulate restore without modifying files
43
+ -h, --help Show this help message
44
+ --no-rehydrate Skip automatic plugin rehydration on import/pull
45
+ --rehydrate Enforce plugin rehydration (default: true)
46
+
47
+ Environment Variables:
48
+ OMP_CONFIG_PASS Passphrase for non-interactive automation
49
+ OMP_CFG_CLOUD_TOKEN Cloud / GitHub API Token
50
+ GITHUB_TOKEN Alternative GitHub API Token
51
+ OMP_CFG_ROOT Override path to ~/.omp/agent
52
+ OMP_HOME Override path to ~/.omp
53
+ `);
54
+ }
55
+
56
+ function parseCliArgs(argv) {
57
+ const args = argv.slice(2);
58
+ const options = {
59
+ command: null,
60
+ target: null,
61
+ pass: process.env.OMP_CONFIG_PASS || null,
62
+ token: process.env.OMP_CFG_CLOUD_TOKEN || process.env.GITHUB_TOKEN || null,
63
+ root: process.env.OMP_CFG_ROOT || null,
64
+ dryRun: false,
65
+ rehydrate: true,
66
+ help: false,
67
+ };
68
+
69
+ const positional = [];
70
+ for (let i = 0; i < args.length; i++) {
71
+ const a = args[i];
72
+ if (a === "-h" || a === "--help" || a === "help") {
73
+ options.help = true;
74
+ } else if (a === "-d" || a === "--dry-run") {
75
+ options.dryRun = true;
76
+ } else if (a === "-p" || a === "--pass") {
77
+ options.pass = args[++i];
78
+ } else if (a === "--no-rehydrate") {
79
+ options.rehydrate = false;
80
+ } else if (a === "--rehydrate") {
81
+ options.rehydrate = true;
82
+ } else if (a === "-t" || a === "--token") {
83
+ options.token = args[++i];
84
+ } else if (a === "-r" || a === "--root") {
85
+ options.root = args[++i];
86
+ } else if (a.startsWith("--pass=")) {
87
+ options.pass = a.slice(7);
88
+ } else if (a.startsWith("--token=")) {
89
+ options.token = a.slice(8);
90
+ } else if (a.startsWith("--root=")) {
91
+ options.root = a.slice(7);
92
+ } else {
93
+ positional.push(a);
94
+ }
95
+ }
96
+
97
+ options.command = positional[0] || null;
98
+ options.target = positional[1] || null;
99
+ return options;
100
+ }
101
+
102
+ async function promptText(query) {
103
+ return new Promise((resolve) => {
104
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
105
+ rl.question(query, (ans) => {
106
+ rl.close();
107
+ resolve(ans.trim());
108
+ });
109
+ });
110
+ }
111
+
112
+ async function resolvePass(pass) {
113
+ if (pass) return pass;
114
+ if (!process.stdin.isTTY) {
115
+ throw new Error("Passphrase required: specify --pass <passphrase> or set OMP_CONFIG_PASS");
116
+ }
117
+ return promptText("Enter passphrase: ");
118
+ }
119
+
120
+ async function resolveToken(token, required) {
121
+ if (token) return token;
122
+ if (!required) return null;
123
+ if (!process.stdin.isTTY) {
124
+ throw new Error("Token required: specify --token <token> or set OMP_CFG_CLOUD_TOKEN / GITHUB_TOKEN");
125
+ }
126
+ return promptText("Enter GitHub/Cloud token: ");
127
+ }
128
+
129
+ async function main() {
130
+ const options = parseCliArgs(process.argv);
131
+ if (options.help || !options.command) {
132
+ printHelp();
133
+ process.exit(options.help ? 0 : 1);
134
+ }
135
+
136
+ const root = options.root || configRoot();
137
+
138
+ try {
139
+ switch (options.command) {
140
+ case "export": {
141
+ if (!options.target) {
142
+ throw new Error("Usage: omp-sync export <outFile> [options]");
143
+ }
144
+ const pass = await resolvePass(options.pass);
145
+ const res = exportEncrypted(options.target, pass, root);
146
+ console.log(`[export] Successfully exported ${res.files} files (${res.bytes} bytes) -> ${res.outFile}`);
147
+ break;
148
+ }
149
+
150
+ case "import": {
151
+ if (!options.target) {
152
+ throw new Error("Usage: omp-sync import <srcFile> [options]");
153
+ }
154
+ const pass = await resolvePass(options.pass);
155
+ const res = importEncrypted(options.target, pass, root, {
156
+ dryRun: options.dryRun,
157
+ rehydrate: options.rehydrate,
158
+ });
159
+ if (options.dryRun) {
160
+ console.log(`[import-dry-run] Would restore ${res.files} files (0 written to disk).`);
161
+ for (const act of res.actions) {
162
+ console.log(` - ${act.path} -> ${act.dest}${act.remapped ? " [path remapped]" : ""}`);
163
+ }
164
+ } else {
165
+ console.log(`[import] Successfully restored ${res.files} files to ${root}.`);
166
+ if (res.backupDir) {
167
+ console.log(`[backup] Pre-existing files backed up to: ${res.backupDir}`);
168
+ }
169
+ if (res.rehydration) {
170
+ console.log(
171
+ `[rehydrate] Plugins processed: ${res.rehydration.rehydrated} rehydrated (installed: ${res.rehydration.npmInstalled.length}, links: ${res.rehydration.linksRepaired.length}).`
172
+ );
173
+ }
174
+ }
175
+ break;
176
+ }
177
+
178
+ case "push": {
179
+ if (!options.target) {
180
+ throw new Error("Usage: omp-sync push <gist:new|gist:<id>|https://...> [options]");
181
+ }
182
+ const target = parseSpec(options.target);
183
+ const pass = await resolvePass(options.pass);
184
+ const token = await resolveToken(options.token, target.kind === "gist");
185
+ const res =
186
+ target.kind === "gist"
187
+ ? await pushGist(target.id, pass, root, token)
188
+ : await pushHttp(target.url, pass, root, token);
189
+ const dest = res.url ? `${res.url} (id: ${res.id})` : res.url;
190
+ console.log(`[push] Pushed ${res.files} files (${res.bytes} bytes) -> ${dest}`);
191
+ break;
192
+ }
193
+
194
+ case "pull": {
195
+ if (!options.target) {
196
+ throw new Error("Usage: omp-sync pull <gist:<id>|https://...> [options]");
197
+ }
198
+ const target = parseSpec(options.target);
199
+ const pass = await resolvePass(options.pass);
200
+ const token = await resolveToken(options.token, target.kind === "gist");
201
+ const res =
202
+ target.kind === "gist"
203
+ ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, rehydrate: options.rehydrate })
204
+ : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, rehydrate: options.rehydrate });
205
+
206
+ if (options.dryRun) {
207
+ console.log(`[pull-dry-run] Would restore ${res.files} files (0 written to disk).`);
208
+ for (const act of res.actions) {
209
+ console.log(` - ${act.path} -> ${act.dest}${act.remapped ? " [path remapped]" : ""}`);
210
+ }
211
+ } else {
212
+ console.log(`[pull] Successfully restored ${res.files} files to ${root}.`);
213
+ if (res.backupDir) {
214
+ console.log(`[backup] Pre-existing files backed up to: ${res.backupDir}`);
215
+ }
216
+ if (res.rehydration) {
217
+ console.log(
218
+ `[rehydrate] Plugins processed: ${res.rehydration.rehydrated} rehydrated (installed: ${res.rehydration.npmInstalled.length}, links: ${res.rehydration.linksRepaired.length}).`
219
+ );
220
+ }
221
+ }
222
+ break;
223
+ }
224
+
225
+ case "rollback": {
226
+ const res = rollback(root);
227
+ console.log(`[rollback] Successfully rolled back ${res.files} files from snapshot ${res.rolledBackFrom}`);
228
+ break;
229
+ }
230
+ case "rehydrate": {
231
+ const res = rehydratePlugins(root, { dryRun: options.dryRun });
232
+ console.log(
233
+ `[rehydrate] Completed. Total rehydrated: ${res.rehydrated} (installed: ${res.npmInstalled.length}, links: ${res.linksRepaired.length}).`
234
+ );
235
+ if (res.errors.length > 0) {
236
+ for (const err of res.errors) {
237
+ console.warn(` [warning] ${err}`);
238
+ }
239
+ }
240
+ break;
241
+ }
242
+
243
+ default:
244
+ console.error(`Unknown command: ${options.command}`);
245
+ printHelp();
246
+ process.exit(1);
247
+ }
248
+ } catch (err) {
249
+ console.error(`[error] ${err.message || err}`);
250
+ process.exit(1);
251
+ }
252
+ }
253
+
254
+ main();
package/index.js CHANGED
@@ -1,54 +1,234 @@
1
1
  /**
2
- * Encrypted portability for omp user config and instruction files.
3
- * Exports a single AES-256-GCM blob (scrypt-derived key); import restores files
4
- * and keeps a backup of whatever it overwrites.
2
+ * Universal, Zero-Repair Cross-Platform OMP Sync & Portability Engine
3
+ * Exports an encrypted AES-256-GCM blob (scrypt-derived key); import restores files,
4
+ * remaps host paths adaptively, and maintains atomic backups for instant rollback.
5
5
  */
6
6
  import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
7
7
  import { gzipSync, gunzipSync } from "node:zlib";
8
8
  import fs from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
+ import {
12
+ rehydratePlugins,
13
+ getPluginLinks,
14
+ savePluginLinks,
15
+ detectMissingPlugins,
16
+ } from "./src/rehydrator.js";
17
+
18
+ export {
19
+ rehydratePlugins,
20
+ getPluginLinks,
21
+ savePluginLinks,
22
+ detectMissingPlugins,
23
+ };
11
24
 
12
25
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
13
- const FILES = ["config.yml", "models.yml", "mcp.json", "AGENTS.md", "STYLE.md", "RULES.md"];
14
- const DIRS = ["memories"];
26
+ const HOME_PLACEHOLDER = "{{OMP_HOME}}";
27
+
28
+ const FILES = [
29
+ "config.yml",
30
+ "config.yaml",
31
+ "models.yml",
32
+ "models.yaml",
33
+ "mcp.json",
34
+ "AGENTS.md",
35
+ "STYLE.md",
36
+ "RULES.md",
37
+ ];
38
+
39
+ const DIRS = ["memories", "managed-skills"];
40
+
41
+ const BLACKLIST_PATTERNS = [
42
+ /\.db$/,
43
+ /\.db-wal$/,
44
+ /\.db-shm$/,
45
+ /\.corrupt-/,
46
+ /^\.import-backup/,
47
+ /\/\.import-backup/,
48
+ /^\.rolled-back/,
49
+ /\/\.rolled-back/,
50
+ /(^|\/)\.git\//,
51
+ /(^|\/)cache\//,
52
+ /(^|\/)blobs\//,
53
+ /(^|\/)sessions\//,
54
+ /(^|\/)terminal-sessions\//,
55
+ /(^|\/)predict\//,
56
+ /(^|\/)node_modules\//,
57
+ ];
15
58
 
16
59
  /** User agent directory, or OMP_CFG_ROOT for tests. */
17
60
  export function configRoot() {
18
61
  return process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
19
62
  }
20
63
 
64
+ /** Root .omp folder (parent of agent directory). */
65
+ export function ompHome(root = configRoot()) {
66
+ return process.env.OMP_HOME || path.dirname(root);
67
+ }
68
+
69
+ function shouldIgnore(relPath) {
70
+ const norm = relPath.replace(/\\/g, "/");
71
+ return BLACKLIST_PATTERNS.some((rx) => rx.test(norm));
72
+ }
73
+
74
+ function isText(buf) {
75
+ const len = Math.min(buf.length, 1024);
76
+ for (let i = 0; i < len; i++) {
77
+ if (buf[i] === 0) return false;
78
+ }
79
+ return true;
80
+ }
81
+
21
82
  function walk(dir, prefix = "") {
22
83
  const out = [];
84
+ if (!fs.existsSync(dir)) return out;
23
85
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
24
86
  const rel = prefix ? `${prefix}/${ent.name}` : ent.name;
25
- if (ent.isDirectory()) out.push(...walk(path.join(dir, ent.name), rel));
26
- else if (ent.isFile()) out.push(rel);
87
+ const abs = path.join(dir, ent.name);
88
+ if (ent.isDirectory()) {
89
+ if (!shouldIgnore(rel + "/")) {
90
+ out.push(...walk(abs, rel));
91
+ }
92
+ } else if (ent.isFile()) {
93
+ if (!shouldIgnore(rel)) {
94
+ out.push(rel);
95
+ }
96
+ }
27
97
  }
28
98
  return out;
29
99
  }
30
100
 
31
- function collect(root) {
101
+ export function collect(root) {
32
102
  const out = [];
33
- for (const f of FILES) {
34
- const p = path.join(root, f);
35
- if (fs.existsSync(p) && fs.statSync(p).isFile()) out.push(f);
103
+ const seen = new Set();
104
+
105
+ function addItem(rel, abs) {
106
+ const norm = rel.replace(/\\/g, "/");
107
+ if (!seen.has(norm) && !shouldIgnore(norm) && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
108
+ seen.add(norm);
109
+ out.push({ rel: norm, abs });
110
+ }
111
+ }
112
+
113
+ // 1. Files directly under root (agent/)
114
+ if (fs.existsSync(root)) {
115
+ for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
116
+ if (ent.isFile()) {
117
+ const name = ent.name;
118
+ const isCore = FILES.includes(name);
119
+ const isToken = name.includes("token");
120
+ const isExtra = name.endsWith(".yml") || name.endsWith(".yaml") || name.endsWith(".json");
121
+ if (isCore || isToken || isExtra) {
122
+ addItem(name, path.join(root, name));
123
+ }
124
+ }
125
+ }
126
+
127
+ // 2. Category directories under root (memories, managed-skills)
128
+ for (const d of DIRS) {
129
+ const base = path.join(root, d);
130
+ if (fs.existsSync(base)) {
131
+ for (const file of walk(base)) {
132
+ addItem(`${d}/${file}`, path.join(base, file));
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ // 3. User extensions under ~/.omp/extensions/ (sibling to agent/)
139
+ const ompDir = ompHome(root);
140
+ const extDir = path.join(ompDir, "extensions");
141
+ if (fs.existsSync(extDir) && fs.statSync(extDir).isDirectory()) {
142
+ for (const file of walk(extDir)) {
143
+ addItem(`extensions/${file}`, path.join(extDir, file));
144
+ }
145
+ }
146
+
147
+ // 4. Installed plugins lockfile & manifest under ~/.omp/plugins/
148
+ const pluginsDir = path.join(ompDir, "plugins");
149
+ const links = getPluginLinks(pluginsDir);
150
+ if (Object.keys(links).length > 0) {
151
+ savePluginLinks(pluginsDir, links);
152
+ }
153
+ const linksFile = path.join(pluginsDir, ".plugin-links.json");
154
+ if (fs.existsSync(linksFile) && fs.statSync(linksFile).isFile()) {
155
+ addItem("plugins/.plugin-links.json", linksFile);
36
156
  }
37
- for (const d of DIRS) {
38
- const base = path.join(root, d);
39
- if (fs.existsSync(base)) for (const rel of walk(base)) out.push(`${d}/${rel}`);
157
+ const lockFile = path.join(pluginsDir, "omp-plugins.lock.json");
158
+ if (fs.existsSync(lockFile) && fs.statSync(lockFile).isFile()) {
159
+ addItem("plugins/omp-plugins.lock.json", lockFile);
40
160
  }
161
+ const pluginPkg = path.join(pluginsDir, "package.json");
162
+ if (fs.existsSync(pluginPkg) && fs.statSync(pluginPkg).isFile()) {
163
+ addItem("plugins/package.json", pluginPkg);
164
+ }
165
+ // 5. Global tools under ~/.omp/tools/
166
+ const toolsDir = path.join(ompDir, "tools");
167
+ if (fs.existsSync(toolsDir) && fs.statSync(toolsDir).isDirectory()) {
168
+ for (const file of walk(toolsDir)) {
169
+ addItem(`tools/${file}`, path.join(toolsDir, file));
170
+ }
171
+ }
172
+
173
+ // 6. Global hooks under ~/.omp/hooks/
174
+ const hooksDir = path.join(ompDir, "hooks");
175
+ if (fs.existsSync(hooksDir) && fs.statSync(hooksDir).isDirectory()) {
176
+ for (const file of walk(hooksDir)) {
177
+ addItem(`hooks/${file}`, path.join(hooksDir, file));
178
+ }
179
+ }
180
+
41
181
  return out;
42
182
  }
43
183
 
44
- /** Write an encrypted archive of the config tree. */
45
- export function exportEncrypted(outFile, pass, root = configRoot()) {
184
+ /** Determine target path for relative archive key. */
185
+ export function resolveDestination(rel, root = configRoot()) {
186
+ const norm = rel.replace(/\\/g, "/");
187
+ if (
188
+ norm.startsWith("extensions/") ||
189
+ norm.startsWith("plugins/") ||
190
+ norm.startsWith("tools/") ||
191
+ norm.startsWith("hooks/")
192
+ ) {
193
+ return path.join(ompHome(root), norm);
194
+ }
195
+ return path.join(root, norm);
196
+ }
197
+
198
+ /** Build the encrypted archive in memory with path sanitization. */
199
+ export function buildArchive(pass, root = configRoot()) {
46
200
  if (!pass) throw new Error("empty passphrase");
47
- const files = collect(root).map((rel) => {
48
- const abs = path.join(root, rel);
49
- return { path: rel, data: fs.readFileSync(abs).toString("base64"), mode: fs.statSync(abs).mode & 0o777 };
201
+ const items = collect(root);
202
+ const home = os.homedir();
203
+ const homePosix = home.replace(/\\/g, "/");
204
+
205
+ const files = items.map(({ rel, abs }) => {
206
+ const raw = fs.readFileSync(abs);
207
+ const mode = fs.statSync(abs).mode & 0o777;
208
+ let data;
209
+ if (isText(raw)) {
210
+ let str = raw.toString("utf8");
211
+ if (home) {
212
+ str = str.split(home).join(HOME_PLACEHOLDER);
213
+ if (homePosix !== home) {
214
+ str = str.split(homePosix).join(HOME_PLACEHOLDER);
215
+ }
216
+ }
217
+ data = Buffer.from(str, "utf8").toString("base64");
218
+ } else {
219
+ data = raw.toString("base64");
220
+ }
221
+ return { path: rel, data, mode };
50
222
  });
51
- const payload = { v: 1, createdAt: new Date().toISOString(), files };
223
+
224
+ const payload = {
225
+ v: 2,
226
+ createdAt: new Date().toISOString(),
227
+ sourceHome: home,
228
+ sourcePlatform: process.platform,
229
+ files,
230
+ };
231
+
52
232
  const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
53
233
  const salt = randomBytes(16);
54
234
  const iv = randomBytes(12);
@@ -56,17 +236,16 @@ export function exportEncrypted(outFile, pass, root = configRoot()) {
56
236
  const cipher = createCipheriv("aes-256-gcm", key, iv);
57
237
  const ct = Buffer.concat([cipher.update(plain), cipher.final()]);
58
238
  const blob = Buffer.concat([MAGIC, salt, iv, cipher.getAuthTag(), ct]);
59
- const abs = path.resolve(outFile);
60
- fs.mkdirSync(path.dirname(abs), { recursive: true });
61
- fs.writeFileSync(abs, blob, { mode: 0o600 });
62
- return { outFile: abs, files: files.length, bytes: blob.length };
239
+ return { blob, files: files.length };
63
240
  }
64
241
 
65
- /** Restore files from an encrypted archive, backing up overwritten ones. */
66
- export function importEncrypted(srcFile, pass, root = configRoot()) {
242
+ /** Restore an encrypted archive buffer into the config tree with adaptive remapping. */
243
+ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
67
244
  if (!pass) throw new Error("empty passphrase");
68
- const blob = fs.readFileSync(srcFile);
69
- if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error("not an omp-config-crypt archive");
245
+ if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) {
246
+ throw new Error("not an omp-config-crypt archive");
247
+ }
248
+
70
249
  let o = MAGIC.length;
71
250
  const salt = blob.subarray(o, (o += 16));
72
251
  const iv = blob.subarray(o, (o += 12));
@@ -75,24 +254,129 @@ export function importEncrypted(srcFile, pass, root = configRoot()) {
75
254
  const key = scryptSync(pass, salt, 32);
76
255
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
77
256
  decipher.setAuthTag(tag);
257
+
78
258
  const payload = JSON.parse(gunzipSync(Buffer.concat([decipher.update(ct), decipher.final()])).toString("utf8"));
79
- if (payload.v !== 1 || !Array.isArray(payload.files)) throw new Error("unsupported archive payload");
259
+ if (![1, 2].includes(payload.v) || !Array.isArray(payload.files)) {
260
+ throw new Error("unsupported archive payload");
261
+ }
262
+
263
+ const dryRun = Boolean(options.dryRun);
264
+ const targetHome = os.homedir();
265
+ const targetHomePosix = targetHome.replace(/\\/g, "/");
266
+ const sourceHome = payload.sourceHome;
80
267
  const backupDir = path.join(root, `.import-backup-${Date.now()}`);
268
+ const actions = [];
81
269
  let restored = 0;
270
+
82
271
  for (const f of payload.files) {
83
- const rel = String(f.path || "");
84
- if (!rel || rel.includes("..") || path.isAbsolute(rel)) throw new Error(`unsafe path in archive: ${rel}`);
85
- const dst = path.join(root, rel);
86
- if (fs.existsSync(dst)) {
87
- const b = path.join(backupDir, rel);
88
- fs.mkdirSync(path.dirname(b), { recursive: true });
89
- fs.copyFileSync(dst, b);
272
+ const rel = String(f.path || "").replace(/\\/g, "/");
273
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
274
+ throw new Error(`unsafe path in archive: ${rel}`);
275
+ }
276
+
277
+ const dst = resolveDestination(rel, root);
278
+ let buf = Buffer.from(f.data, "base64");
279
+ let remapped = false;
280
+
281
+ if (payload.v >= 2 && isText(buf)) {
282
+ let str = buf.toString("utf8");
283
+ const orig = str;
284
+
285
+ const isJsonOrYaml = rel.endsWith(".json") || rel.endsWith(".yml") || rel.endsWith(".yaml");
286
+ const effectiveHome = process.platform === "win32" && isJsonOrYaml ? targetHomePosix : targetHome;
287
+
288
+ str = str.split(HOME_PLACEHOLDER).join(effectiveHome);
289
+ if (sourceHome) {
290
+ str = str.split(sourceHome).join(effectiveHome);
291
+ const sourceHomePosix = sourceHome.replace(/\\/g, "/");
292
+ if (sourceHomePosix !== sourceHome) {
293
+ str = str.split(sourceHomePosix).join(effectiveHome);
294
+ }
295
+ }
296
+
297
+ if (str !== orig) {
298
+ remapped = true;
299
+ buf = Buffer.from(str, "utf8");
300
+ }
90
301
  }
302
+
303
+ const exists = fs.existsSync(dst);
304
+ actions.push({ path: rel, dest: dst, exists, remapped });
305
+
306
+ if (!dryRun) {
307
+ if (exists) {
308
+ const b = path.join(backupDir, rel);
309
+ fs.mkdirSync(path.dirname(b), { recursive: true });
310
+ fs.copyFileSync(dst, b);
311
+ }
312
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
313
+ fs.writeFileSync(dst, buf, { mode: f.mode || 0o600 });
314
+ }
315
+ restored++;
316
+ }
317
+
318
+ let rehydration = null;
319
+ if (options.rehydrate !== false && !dryRun) {
320
+ const hasPluginChanges = actions.some((a) => a.path.startsWith("plugins/"));
321
+ if (hasPluginChanges || options.rehydrate === true) {
322
+ rehydration = rehydratePlugins(root, options);
323
+ }
324
+ }
325
+
326
+ return {
327
+ files: restored,
328
+ dryRun,
329
+ actions,
330
+ backupDir: !dryRun && fs.existsSync(backupDir) ? backupDir : null,
331
+ rehydration,
332
+ };
333
+ }
334
+
335
+ /** Revert the most recent config restore from its backup. */
336
+ export function rollback(root = configRoot()) {
337
+ if (!fs.existsSync(root)) throw new Error(`Root directory does not exist: ${root}`);
338
+ const entries = fs.readdirSync(root, { withFileTypes: true });
339
+ const backups = entries
340
+ .filter((e) => e.isDirectory() && e.name.startsWith(".import-backup-"))
341
+ .map((e) => e.name)
342
+ .sort()
343
+ .reverse();
344
+
345
+ if (backups.length === 0) {
346
+ throw new Error("No import backup found to rollback");
347
+ }
348
+
349
+ const latest = backups[0];
350
+ const backupDir = path.join(root, latest);
351
+ const files = walk(backupDir);
352
+ let restored = 0;
353
+
354
+ for (const rel of files) {
355
+ const src = path.join(backupDir, rel);
356
+ const dst = resolveDestination(rel, root);
91
357
  fs.mkdirSync(path.dirname(dst), { recursive: true });
92
- fs.writeFileSync(dst, Buffer.from(f.data, "base64"), { mode: f.mode || 0o600 });
358
+ fs.copyFileSync(src, dst);
93
359
  restored++;
94
360
  }
95
- return { files: restored, backupDir: fs.existsSync(backupDir) ? backupDir : null };
361
+
362
+ const rolledBackDir = path.join(root, `.rolled-back-${latest.replace(".import-backup-", "")}`);
363
+ fs.renameSync(backupDir, rolledBackDir);
364
+
365
+ return { files: restored, rolledBackFrom: latest };
366
+ }
367
+
368
+ /** Write an encrypted archive of the config tree. */
369
+ export function exportEncrypted(outFile, pass, root = configRoot()) {
370
+ const { blob, files } = buildArchive(pass, root);
371
+ const abs = path.resolve(outFile);
372
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
373
+ fs.writeFileSync(abs, blob, { mode: 0o600 });
374
+ return { outFile: abs, files, bytes: blob.length };
375
+ }
376
+
377
+ /** Restore files from an encrypted archive, backing up overwritten ones. */
378
+ export function importEncrypted(srcFile, pass, root = configRoot(), options = {}) {
379
+ return restoreArchive(fs.readFileSync(srcFile), pass, root, options);
96
380
  }
97
381
 
98
382
  async function askPass(ctx, title) {
@@ -114,7 +398,117 @@ async function askPass(ctx, title) {
114
398
  throw new Error("no passphrase: set OMP_CONFIG_PASS or answer the prompt");
115
399
  }
116
400
 
117
- /** Plugin entry: /config-export and /config-import. */
401
+ function envToken() {
402
+ return process.env.OMP_CFG_CLOUD_TOKEN || process.env.GITHUB_TOKEN || null;
403
+ }
404
+
405
+ async function askToken(ctx, title, required) {
406
+ const fromEnv = envToken();
407
+ if (fromEnv) return fromEnv;
408
+ const input = ctx?.ui?.input;
409
+ if (typeof input === "function") {
410
+ let value;
411
+ try {
412
+ value = await input.call(ctx.ui, {
413
+ title,
414
+ prompt: title,
415
+ placeholder: required ? "token" : "token (empty = none)",
416
+ });
417
+ } catch {
418
+ try {
419
+ value = await input.call(ctx.ui, title);
420
+ } catch {
421
+ value = undefined;
422
+ }
423
+ }
424
+ if (typeof value === "string" && value.trim()) return value.trim();
425
+ if (!required) return null;
426
+ }
427
+ if (required) throw new Error("token required: set OMP_CFG_CLOUD_TOKEN or enter it when asked");
428
+ return null;
429
+ }
430
+
431
+ const GIST_FILE = "omp-config.enc.b64";
432
+
433
+ async function gh(token, pathname, init = {}) {
434
+ const res = await fetch(`https://api.github.com${pathname}`, {
435
+ ...init,
436
+ signal: AbortSignal.timeout(30_000),
437
+ headers: {
438
+ accept: "application/vnd.github+json",
439
+ authorization: `Bearer ${token}`,
440
+ "content-type": "application/json",
441
+ ...(init.headers || {}),
442
+ },
443
+ });
444
+ if (!res.ok) throw new Error(`GitHub API ${res.status}: ${(await res.text()).slice(0, 200)}`);
445
+ return res.json();
446
+ }
447
+
448
+ /** Push the archive to a secret gist; returns its id and URL. */
449
+ export async function pushGist(id, pass, root = configRoot(), token = envToken()) {
450
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
451
+ const { blob, files } = buildArchive(pass, root);
452
+ const content = blob.toString("base64");
453
+ const body = { files: { [GIST_FILE]: { content } } };
454
+ const data =
455
+ id && id !== "new"
456
+ ? await gh(token, `/gists/${id}`, { method: "PATCH", body: JSON.stringify(body) })
457
+ : await gh(token, `/gists`, {
458
+ method: "POST",
459
+ body: JSON.stringify({ description: "omp config (encrypted)", public: false, ...body }),
460
+ });
461
+ return { id: data.id, url: data.html_url, files, bytes: blob.length };
462
+ }
463
+
464
+ /** Pull the archive from a secret gist. */
465
+ export async function pullGist(id, pass, root = configRoot(), token = envToken(), options = {}) {
466
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
467
+ const data = await gh(token, `/gists/${id}`);
468
+ const content = data?.files?.[GIST_FILE]?.content;
469
+ if (!content) throw new Error(`gist ${id} has no ${GIST_FILE}`);
470
+ return restoreArchive(Buffer.from(content, "base64"), pass, root, options);
471
+ }
472
+
473
+ /** Push to any endpoint accepting PUT (presigned S3, WebDAV, custom). */
474
+ export async function pushHttp(url, pass, root = configRoot(), token = envToken()) {
475
+ const { blob, files } = buildArchive(pass, root);
476
+ const headers = { "content-type": "application/octet-stream" };
477
+ if (token) headers.authorization = `Bearer ${token}`;
478
+ const res = await fetch(url, {
479
+ method: "PUT",
480
+ body: blob,
481
+ signal: AbortSignal.timeout(30_000),
482
+ headers,
483
+ });
484
+ if (!res.ok) throw new Error(`PUT ${res.status}: ${(await res.text()).slice(0, 200)}`);
485
+ return { url, files, bytes: blob.length };
486
+ }
487
+
488
+ /** Pull from any endpoint serving the archive. */
489
+ export async function pullHttp(url, pass, root = configRoot(), token = envToken(), options = {}) {
490
+ const res = await fetch(url, {
491
+ signal: AbortSignal.timeout(30_000),
492
+ headers: token ? { authorization: `Bearer ${token}` } : {},
493
+ });
494
+ if (!res.ok) throw new Error(`GET ${res.status}: ${(await res.text()).slice(0, 200)}`);
495
+ return restoreArchive(Buffer.from(await res.arrayBuffer()), pass, root, options);
496
+ }
497
+
498
+ export function parseSpec(spec) {
499
+ const s = spec.trim();
500
+ if (s.startsWith("gist:")) return { kind: "gist", id: s.slice(5) || "new" };
501
+ if (/^https?:\/\//.test(s)) return { kind: "http", url: s };
502
+ throw new Error("expected gist:<id|new> or an https URL");
503
+ }
504
+
505
+ function extractDryRun(str) {
506
+ const dryRun = /\b--dry-run\b/i.test(str);
507
+ const clean = str.replace(/\b--dry-run\b/gi, "").trim();
508
+ return { dryRun, clean };
509
+ }
510
+
511
+ /** Plugin entry: local and cloud config portability. */
118
512
  export default function (pi) {
119
513
  pi.registerCommand("config-export", {
120
514
  description: "Encrypt omp config + instructions to a file",
@@ -131,20 +525,87 @@ export default function (pi) {
131
525
  });
132
526
 
133
527
  pi.registerCommand("config-import", {
134
- description: "Decrypt and restore an omp config archive",
528
+ description: "Decrypt and restore an omp config archive (--dry-run to preview)",
135
529
  handler: async (args, ctx) => {
136
- const src = (args || "").trim();
530
+ const { dryRun, clean: src } = extractDryRun(args || "");
137
531
  if (!src) {
138
- ctx.ui.notify("usage: /config-import <file.enc>", "error");
532
+ ctx.ui.notify("usage: /config-import <file.enc> [--dry-run]", "error");
139
533
  return;
140
534
  }
141
535
  try {
142
536
  const pass = await askPass(ctx, "Import passphrase");
143
- const r = importEncrypted(src, pass);
144
- ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
537
+ const r = importEncrypted(src, pass, configRoot(), { dryRun });
538
+ if (dryRun) {
539
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
540
+ } else {
541
+ ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
542
+ }
145
543
  } catch (error) {
146
544
  ctx.ui.notify(`config-import failed: ${error?.message ?? error}`, "error");
147
545
  }
148
546
  },
149
547
  });
548
+
549
+ pi.registerCommand("config-push", {
550
+ description: "Encrypt and upload config to gist:<id|new> or an https URL",
551
+ handler: async (args, ctx) => {
552
+ const spec = (args || "").trim();
553
+ if (!spec) {
554
+ ctx.ui.notify("usage: /config-push gist:new | gist:<id> | https://…", "error");
555
+ return;
556
+ }
557
+ try {
558
+ const target = parseSpec(spec);
559
+ const pass = await askPass(ctx, "Push passphrase");
560
+ const token = await askToken(ctx, "Cloud token", target.kind === "gist");
561
+ const r = target.kind === "gist"
562
+ ? await pushGist(target.id, pass, configRoot(), token)
563
+ : await pushHttp(target.url, pass, configRoot(), token);
564
+ const where = r.url ? `${r.url} (id ${r.id})` : r.url;
565
+ ctx.ui.notify(`pushed ${r.files} files (${r.bytes} B) → ${where}`, "info");
566
+ } catch (error) {
567
+ ctx.ui.notify(`config-push failed: ${error?.message ?? error}`, "error");
568
+ }
569
+ },
570
+ });
571
+
572
+ pi.registerCommand("config-pull", {
573
+ description: "Download and decrypt config from gist:<id> or an https URL (--dry-run to preview)",
574
+ handler: async (args, ctx) => {
575
+ const { dryRun, clean: spec } = extractDryRun(args || "");
576
+ if (!spec) {
577
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run]", "error");
578
+ return;
579
+ }
580
+ try {
581
+ const target = parseSpec(spec);
582
+ const pass = await askPass(ctx, "Pull passphrase");
583
+ const token = await askToken(ctx, "Cloud token", target.kind === "gist");
584
+ const r = target.kind === "gist"
585
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun })
586
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun });
587
+ if (dryRun) {
588
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
589
+ } else {
590
+ const rehydratedCount = r.rehydration?.rehydrated ?? 0;
591
+ const rehydratedMsg = rehydratedCount > 0 ? `, rehydrated ${rehydratedCount} plugins` : "";
592
+ ctx.ui.notify(`restored ${r.files} files${rehydratedMsg}${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
593
+ }
594
+ } catch (error) {
595
+ ctx.ui.notify(`config-pull failed: ${error?.message ?? error}`, "error");
596
+ }
597
+ },
598
+ });
599
+
600
+ pi.registerCommand("config-rollback", {
601
+ description: "Revert the latest config restore from its backup snapshot",
602
+ handler: async (_args, ctx) => {
603
+ try {
604
+ const r = rollback(configRoot());
605
+ ctx.ui.notify(`rolled back ${r.files} files from ${r.rolledBackFrom}`, "info");
606
+ } catch (error) {
607
+ ctx.ui.notify(`config-rollback failed: ${error?.message ?? error}`, "error");
608
+ }
609
+ },
610
+ });
150
611
  }
package/package.json CHANGED
@@ -1,19 +1,29 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.1.1",
4
- "description": "Encrypted export/import of omp config and instructions",
3
+ "version": "0.4.0",
4
+ "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "bin": {
8
+ "omp-sync": "./bin/omp-sync.js"
9
+ },
10
+ "scripts": {
11
+ "test": "node test/sync-portable.test.mjs"
12
+ },
7
13
  "keywords": [
8
14
  "omp",
9
15
  "oh-my-pi",
10
16
  "plugin",
11
17
  "config",
12
18
  "sync",
13
- "encryption"
19
+ "encryption",
20
+ "cross-platform",
21
+ "portable"
14
22
  ],
15
23
  "files": [
16
24
  "index.js",
25
+ "src",
26
+ "bin",
17
27
  "README.md",
18
28
  "LICENSE"
19
29
  ],
@@ -0,0 +1,220 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { execFileSync } from "node:child_process";
5
+ import { ompHome } from "../index.js";
6
+
7
+ const LINKS_FILE = ".plugin-links.json";
8
+
9
+ /**
10
+ * Scan plugins directory node_modules for symlinks and return a map of name -> targetPath.
11
+ */
12
+ export function getPluginLinks(pluginsDir) {
13
+ const nodeModules = path.join(pluginsDir, "node_modules");
14
+ const links = {};
15
+ if (!fs.existsSync(nodeModules)) return links;
16
+
17
+ function scan(dir, prefix = "") {
18
+ let entries = [];
19
+ try {
20
+ entries = fs.readdirSync(dir, { withFileTypes: true });
21
+ } catch {
22
+ return;
23
+ }
24
+ for (const ent of entries) {
25
+ const full = path.join(dir, ent.name);
26
+ if (ent.isSymbolicLink()) {
27
+ try {
28
+ const target = fs.realpathSync(full);
29
+ const pkgName = prefix ? `${prefix}/${ent.name}` : ent.name;
30
+ links[pkgName] = target;
31
+ } catch {
32
+ try {
33
+ const rawTarget = fs.readlinkSync(full);
34
+ const pkgName = prefix ? `${prefix}/${ent.name}` : ent.name;
35
+ links[pkgName] = path.resolve(dir, rawTarget);
36
+ } catch {}
37
+ }
38
+ } else if (ent.isDirectory() && ent.name.startsWith("@")) {
39
+ scan(full, ent.name);
40
+ }
41
+ }
42
+ }
43
+
44
+ scan(nodeModules);
45
+ return links;
46
+ }
47
+
48
+ /**
49
+ * Persist known plugin links into .plugin-links.json.
50
+ */
51
+ export function savePluginLinks(pluginsDir, links) {
52
+ if (!links || Object.keys(links).length === 0) return;
53
+ const filePath = path.join(pluginsDir, LINKS_FILE);
54
+ try {
55
+ let existing = {};
56
+ if (fs.existsSync(filePath)) {
57
+ try {
58
+ existing = JSON.parse(fs.readFileSync(filePath, "utf8"));
59
+ } catch {}
60
+ }
61
+ const merged = { ...existing, ...links };
62
+ fs.writeFileSync(filePath, JSON.stringify(merged, null, 2), "utf8");
63
+ } catch {}
64
+ }
65
+
66
+ /**
67
+ * Detect missing or broken plugins in plugins directory.
68
+ */
69
+ export function detectMissingPlugins(pluginsDir) {
70
+ const missing = {
71
+ npmDependencies: [],
72
+ linkedPlugins: [],
73
+ };
74
+
75
+ const lockPath = path.join(pluginsDir, "omp-plugins.lock.json");
76
+ const pkgPath = path.join(pluginsDir, "package.json");
77
+ const nodeModules = path.join(pluginsDir, "node_modules");
78
+
79
+ // 1. Check npm dependencies
80
+ if (fs.existsSync(pkgPath)) {
81
+ try {
82
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
83
+ const deps = pkg.dependencies || {};
84
+ for (const dep of Object.keys(deps)) {
85
+ const depPath = path.join(nodeModules, ...dep.split("/"));
86
+ if (!fs.existsSync(depPath)) {
87
+ missing.npmDependencies.push(dep);
88
+ }
89
+ }
90
+ } catch {}
91
+ }
92
+
93
+ // 2. Check locked plugins (including links)
94
+ if (fs.existsSync(lockPath)) {
95
+ try {
96
+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
97
+ const plugins = lock.plugins || {};
98
+ for (const name of Object.keys(plugins)) {
99
+ const pluginPath = path.join(nodeModules, ...name.split("/"));
100
+ let exists = false;
101
+ try {
102
+ exists = fs.existsSync(pluginPath);
103
+ } catch {}
104
+ if (!exists) {
105
+ if (!missing.npmDependencies.includes(name)) {
106
+ missing.linkedPlugins.push(name);
107
+ }
108
+ }
109
+ }
110
+ } catch {}
111
+ }
112
+
113
+ return missing;
114
+ }
115
+
116
+ /**
117
+ * Perform autonomous rehydration: npm install + link repair.
118
+ */
119
+ export function rehydratePlugins(root, options = {}) {
120
+ const pluginsDir = path.join(ompHome(root), "plugins");
121
+ const dryRun = Boolean(options.dryRun);
122
+ const results = {
123
+ rehydrated: 0,
124
+ npmInstalled: [],
125
+ linksRepaired: [],
126
+ errors: [],
127
+ };
128
+
129
+ if (!fs.existsSync(pluginsDir)) {
130
+ return results;
131
+ }
132
+
133
+ const missing = detectMissingPlugins(pluginsDir);
134
+ const pkgPath = path.join(pluginsDir, "package.json");
135
+ const lockLinksPath = path.join(pluginsDir, LINKS_FILE);
136
+
137
+ // 1. Run npm install if npm dependencies are missing or package.json exists without node_modules
138
+ const nodeModules = path.join(pluginsDir, "node_modules");
139
+ const needsNpmInstall =
140
+ fs.existsSync(pkgPath) &&
141
+ (missing.npmDependencies.length > 0 || !fs.existsSync(nodeModules));
142
+
143
+ if (needsNpmInstall) {
144
+ if (dryRun) {
145
+ results.npmInstalled.push(...missing.npmDependencies);
146
+ } else {
147
+ try {
148
+ execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund"], {
149
+ cwd: pluginsDir,
150
+ stdio: "pipe",
151
+ timeout: 60000,
152
+ });
153
+ results.npmInstalled.push(...missing.npmDependencies);
154
+ } catch (err) {
155
+ results.errors.push(`npm install failed: ${err.message}`);
156
+ }
157
+ }
158
+ }
159
+
160
+ // 2. Load stored link targets
161
+ let storedLinks = {};
162
+ if (fs.existsSync(lockLinksPath)) {
163
+ try {
164
+ storedLinks = JSON.parse(fs.readFileSync(lockLinksPath, "utf8"));
165
+ } catch {}
166
+ }
167
+
168
+ // Known candidate fallback directories for common local plugins
169
+ 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")],
172
+ };
173
+
174
+ // 3. Resolve and repair linked plugins
175
+ const pluginsToLink = Array.from(
176
+ new Set([...missing.linkedPlugins, ...Object.keys(storedLinks)])
177
+ );
178
+
179
+ for (const name of pluginsToLink) {
180
+ const linkPath = path.join(nodeModules, ...name.split("/"));
181
+ let isHealthy = false;
182
+ try {
183
+ if (fs.existsSync(linkPath)) {
184
+ isHealthy = true;
185
+ }
186
+ } catch {}
187
+
188
+ if (isHealthy) continue;
189
+
190
+ // Find candidate target path
191
+ let targetDir = storedLinks[name];
192
+ if (!targetDir || !fs.existsSync(targetDir)) {
193
+ const candidates = candidateDirs[name] || [];
194
+ targetDir = candidates.find((c) => fs.existsSync(c)) || null;
195
+ }
196
+
197
+ if (!targetDir || !fs.existsSync(targetDir)) {
198
+ results.errors.push(`Target directory for plugin ${name} not found`);
199
+ continue;
200
+ }
201
+
202
+ if (dryRun) {
203
+ results.linksRepaired.push({ name, target: targetDir });
204
+ } else {
205
+ try {
206
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
207
+ try {
208
+ fs.rmSync(linkPath, { force: true, recursive: true });
209
+ } catch {}
210
+ fs.symlinkSync(targetDir, linkPath, "dir");
211
+ results.linksRepaired.push({ name, target: targetDir });
212
+ } catch (err) {
213
+ results.errors.push(`Failed to link ${name} -> ${targetDir}: ${err.message}`);
214
+ }
215
+ }
216
+ }
217
+
218
+ results.rehydrated = results.npmInstalled.length + results.linksRepaired.length;
219
+ return results;
220
+ }