omp-config-crypt 0.6.3 → 0.6.4

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,322 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { pointerToTokens, validatePortablePath } from "./sync-files.js";
5
+
6
+ export const POLICY_FILE = "sync-policy.local.json";
7
+ export const VALID_SCOPES = new Set(["public", "private"]);
8
+ export const VALID_RESOURCE_PREFIXES = new Set([
9
+ "provider",
10
+ "mcp",
11
+ "setting",
12
+ "plugin",
13
+ "asset",
14
+ ]);
15
+
16
+ export function isExactSemver(version) {
17
+ return typeof version === "string" && /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/.test(version);
18
+ }
19
+
20
+ export function resolveSyncNamespace(policy, state) {
21
+ const policyNamespace = policy?.namespace;
22
+ const stateNamespace = state?.namespace;
23
+ if (policyNamespace && stateNamespace && policyNamespace !== stateNamespace) {
24
+ throw new Error("Sync policy and sync state namespaces differ; refusing to mix configuration sets");
25
+ }
26
+ return policyNamespace || stateNamespace || null;
27
+ }
28
+
29
+ /**
30
+ * Validates a resource ID format.
31
+ * provider:<name>
32
+ * mcp:<name>
33
+ * setting:<JSON-pointer>
34
+ * plugin:<npm-name>
35
+ * asset:<archive-relative-root>
36
+ */
37
+ export function validateResourceId(id) {
38
+ if (typeof id !== "string" || !id.includes(":")) {
39
+ throw new Error(
40
+ `Invalid resource ID '${id}': must be in format <type>:<name> (provider, mcp, setting, plugin, asset)`
41
+ );
42
+ }
43
+ const colonIdx = id.indexOf(":");
44
+ const prefix = id.slice(0, colonIdx);
45
+ const name = id.slice(colonIdx + 1);
46
+
47
+ if (!VALID_RESOURCE_PREFIXES.has(prefix)) {
48
+ throw new Error(
49
+ `Invalid resource ID prefix '${prefix}': must be one of ${Array.from(
50
+ VALID_RESOURCE_PREFIXES
51
+ ).join(", ")}`
52
+ );
53
+ }
54
+ if (!name) {
55
+ throw new Error(`Invalid resource ID '${id}': name cannot be empty`);
56
+ }
57
+
58
+ if (prefix === "provider" || prefix === "mcp") {
59
+ if (/[\/\\\s\x00-\x1f\x7f]/.test(name)) {
60
+ throw new Error(
61
+ `Invalid ${prefix} resource ID '${id}': name cannot contain slashes, whitespace, or control characters`
62
+ );
63
+ }
64
+ } else if (prefix === "plugin") {
65
+ const npmName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
66
+ if (name.length > 214 || !npmName.test(name)) {
67
+ throw new Error(
68
+ `Invalid plugin resource ID '${id}': name must be a valid unscoped or @scope/name package`
69
+ );
70
+ }
71
+ } else if (prefix === "setting") {
72
+ if (!name.startsWith("/")) {
73
+ throw new Error(
74
+ `Invalid setting resource ID '${id}': JSON pointer must start with '/'`
75
+ );
76
+ }
77
+ if (name.length > 1 && name.endsWith("/")) {
78
+ throw new Error(
79
+ `Invalid setting resource ID '${id}': JSON pointer cannot end with trailing slash`
80
+ );
81
+ }
82
+ const tokens = pointerToTokens(name);
83
+ if (tokens.some((token) => /^(?:0|[1-9]\d*)$/.test(token))) {
84
+ throw new Error(`Invalid setting resource ID '${id}': arrays are leaf values; array elements cannot be settings`);
85
+ }
86
+ } else if (prefix === "asset") {
87
+ validateAssetPath(name);
88
+ }
89
+
90
+ return { prefix, name };
91
+ }
92
+
93
+ /**
94
+ * Validates asset path conventions.
95
+ * Must start with skills/, managed-skills/, extensions/, tools/, hooks/, or be AGENTS.md, STYLE.md, RULES.md.
96
+ * No backslashes, empty segments, dot segments, or traversal.
97
+ */
98
+ export function validateAssetPath(relPath) {
99
+ const parts = validatePortablePath(relPath);
100
+ const allowedFiles = new Set(["AGENTS.md", "STYLE.md", "RULES.md"]);
101
+ const directoryAsset = /^(?:skills|managed-skills|extensions|tools|hooks)\/[^/]+$/;
102
+ if (!directoryAsset.test(relPath) && !allowedFiles.has(relPath)) {
103
+ throw new Error(
104
+ `Invalid asset root for '${relPath}': expected one named entry under skills/, managed-skills/, extensions/, tools/, hooks/, or a supported top-level document`
105
+ );
106
+ }
107
+ return parts;
108
+ }
109
+
110
+ /**
111
+ * Checks that setting JSON pointers do not overlap (ancestor/descendant).
112
+ * IDs should be array of setting:<pointer>.
113
+ */
114
+ export function checkSettingOverlap(settingIds) {
115
+ const pointers = settingIds.map((id) => {
116
+ const { name } = validateResourceId(id);
117
+ return { id, tokens: pointerToTokens(name) };
118
+ });
119
+ const isAncestor = (a, b) => a.length < b.length && a.every((token, i) => token === b[i]);
120
+
121
+ for (let i = 0; i < pointers.length; i++) {
122
+ for (let j = i + 1; j < pointers.length; j++) {
123
+ const a = pointers[i];
124
+ const b = pointers[j];
125
+ if (a.tokens.length === b.tokens.length && a.tokens.every((token, k) => token === b.tokens[k])) {
126
+ throw new Error(`Duplicate setting ID: '${a.id}'`);
127
+ }
128
+ if (isAncestor(a.tokens, b.tokens) || isAncestor(b.tokens, a.tokens)) {
129
+ throw new Error(`Setting pointers overlap: '${a.id}' and '${b.id}'`);
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Reads and strictly validates sync-policy.local.json from root.
137
+ * Returns { version: 1, namespace?: string, resources: Record<string, "public" | "private"> }
138
+ */
139
+ export function readSyncPolicy(root) {
140
+ const filePath = path.join(root, POLICY_FILE);
141
+ if (!fs.existsSync(filePath)) {
142
+ return { version: 1, resources: {} };
143
+ }
144
+
145
+ let raw;
146
+ try {
147
+ raw = fs.readFileSync(filePath, "utf8");
148
+ } catch (err) {
149
+ throw new Error(`Failed to read ${POLICY_FILE}: ${err.message}`);
150
+ }
151
+
152
+ let parsed;
153
+ try {
154
+ parsed = JSON.parse(raw);
155
+ } catch (err) {
156
+ throw new Error(
157
+ `Invalid JSON in ${POLICY_FILE}: ${err.message}. Manual correction required; will not auto-overwrite.`
158
+ );
159
+ }
160
+
161
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
162
+ throw new Error(
163
+ `Invalid ${POLICY_FILE}: root must be a JSON object. Manual correction required.`
164
+ );
165
+ }
166
+
167
+ if (parsed.version !== 1) {
168
+ throw new Error(
169
+ `Invalid ${POLICY_FILE}: unsupported version ${parsed.version}; expected 1.`
170
+ );
171
+ }
172
+
173
+ if (
174
+ parsed.namespace !== undefined &&
175
+ (typeof parsed.namespace !== "string" || !parsed.namespace.trim())
176
+ ) {
177
+ throw new Error(
178
+ `Invalid ${POLICY_FILE}: namespace must be a non-empty string if provided.`
179
+ );
180
+ }
181
+
182
+ if (
183
+ !parsed.resources ||
184
+ typeof parsed.resources !== "object" ||
185
+ Array.isArray(parsed.resources)
186
+ ) {
187
+ throw new Error(
188
+ `Invalid ${POLICY_FILE}: 'resources' field must be an object.`
189
+ );
190
+ }
191
+
192
+ const settingIds = [];
193
+ for (const [id, scope] of Object.entries(parsed.resources)) {
194
+ validateResourceId(id);
195
+ if (!VALID_SCOPES.has(scope)) {
196
+ throw new Error(
197
+ `Invalid scope '${scope}' for resource '${id}' in ${POLICY_FILE}; must be 'public' or 'private'.`
198
+ );
199
+ }
200
+ if (id.startsWith("setting:")) {
201
+ settingIds.push(id);
202
+ }
203
+ }
204
+
205
+ checkSettingOverlap(settingIds);
206
+
207
+ return {
208
+ version: 1,
209
+ namespace: parsed.namespace ? parsed.namespace.trim() : undefined,
210
+ resources: { ...parsed.resources },
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Writes sync-policy.local.json atomically using temp file + rename.
216
+ */
217
+ function writeSyncPolicyAtomic(root, policy) {
218
+ if (!fs.existsSync(root)) {
219
+ fs.mkdirSync(root, { recursive: true });
220
+ }
221
+ const target = path.join(root, POLICY_FILE);
222
+ const tmp = path.join(root, `.${POLICY_FILE}.tmp-${randomUUID()}`);
223
+ const data = JSON.stringify(policy, null, 2) + "\n";
224
+ fs.writeFileSync(tmp, data, "utf8");
225
+ fs.renameSync(tmp, target);
226
+ }
227
+
228
+ /**
229
+ * Sets scope ("public" | "private") for a resource in sync-policy.local.json.
230
+ * Validates that resource exists in inventory.
231
+ * If setting to public and provider has private: true in models.yml or exists in models.local.json,
232
+ * throws error preventing accidental override.
233
+ */
234
+ export async function setResourceScope(root, id, scope, options = {}) {
235
+ if (!VALID_SCOPES.has(scope)) {
236
+ throw new Error(
237
+ `Invalid scope '${scope}': must be 'public' or 'private'`
238
+ );
239
+ }
240
+ validateResourceId(id);
241
+
242
+ // Lazy import inventoryResources to avoid circular dependency
243
+ const { inventoryResources } = await import("./sync-resources.js");
244
+ const inventory = inventoryResources(root);
245
+ const item = inventory.find((r) => r.id === id);
246
+ if (!item) {
247
+ throw new Error(
248
+ `Resource '${id}' not found in current configuration inventory. Cannot set scope.`
249
+ );
250
+ }
251
+
252
+ if (scope === "public" && id.startsWith("provider:")) {
253
+ if (item.isPrivate) {
254
+ throw new Error(
255
+ `Provider '${item.name}' is marked private in models.yml or models.local.json. ` +
256
+ `Use existing provider management command to change it to public before setting sync scope.`
257
+ );
258
+ }
259
+ }
260
+
261
+ const { withSyncLock } = await import("./sync-files.js");
262
+ const { readSyncState } = await import("./sync-plan.js");
263
+ return withSyncLock(root, () => {
264
+ const policy = readSyncPolicy(root);
265
+ const lockedNamespace = resolveSyncNamespace(policy, readSyncState(root));
266
+
267
+ if (id.startsWith("setting:")) {
268
+ const existingSettings = Object.keys(policy.resources).filter(
269
+ (k) => k.startsWith("setting:") && k !== id
270
+ );
271
+ existingSettings.push(id);
272
+ checkSettingOverlap(existingSettings);
273
+ }
274
+
275
+ let warning = null;
276
+ if (scope === "public") {
277
+ if (!policy.namespace) policy.namespace = lockedNamespace || randomUUID();
278
+ warning =
279
+ `Notice: Resource '${id}' credentials and configuration will be encrypted into the public sync bundle.`;
280
+ }
281
+
282
+ policy.resources[id] = scope;
283
+ writeSyncPolicyAtomic(root, policy);
284
+
285
+ return {
286
+ id,
287
+ scope,
288
+ namespace: policy.namespace,
289
+ warning,
290
+ };
291
+ });
292
+ }
293
+
294
+ /**
295
+ * Resolves the effective scope of a resource given policy, baseline state, and inventory item.
296
+ * Explicit private > provider private flag > explicit public > managed baseline > unclassified private.
297
+ */
298
+ export function resolveResourceScope(id, policy, state, inventoryItem) {
299
+ // 1. Explicit private policy takes absolute precedence
300
+ if (policy?.resources?.[id] === "private") {
301
+ return { scope: "private", reason: "explicit-private-policy" };
302
+ }
303
+
304
+ // 2. Provider with private flag or local storage is forced private
305
+ if (id.startsWith("provider:") && inventoryItem?.isPrivate) {
306
+ return { scope: "private", reason: "provider-private-flag" };
307
+ }
308
+
309
+ // 3. Explicit public policy
310
+ if (policy?.resources?.[id] === "public") {
311
+ return { scope: "public", reason: "explicit-public-policy" };
312
+ }
313
+
314
+ // 4. Managed by local baseline state (already synchronized previously)
315
+ const baseline = state?.resources?.[id];
316
+ if (baseline && baseline.hash && baseline.hash !== "__OMP_SENTINEL_DELETED__") {
317
+ return { scope: "public", reason: "managed-by-baseline" };
318
+ }
319
+
320
+ // 5. Default local unclassified (retained locally, not exported; on import: adopt if absent or identical, conflict if different)
321
+ return { scope: "unclassified", reason: "unclassified-default-local" };
322
+ }