@ant.sh/colony 0.1.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +172 -0
  3. package/dist/cjs/cli.js +281 -0
  4. package/dist/cjs/cli.js.map +7 -0
  5. package/dist/cjs/index.js +383 -0
  6. package/dist/cjs/index.js.map +7 -0
  7. package/dist/cjs/package.json +3 -0
  8. package/dist/cjs/parser.js +319 -0
  9. package/dist/cjs/parser.js.map +7 -0
  10. package/dist/cjs/providers/aws.js +115 -0
  11. package/dist/cjs/providers/aws.js.map +7 -0
  12. package/dist/cjs/providers/openbao.js +49 -0
  13. package/dist/cjs/providers/openbao.js.map +7 -0
  14. package/dist/cjs/providers/vault-base.js +98 -0
  15. package/dist/cjs/providers/vault-base.js.map +7 -0
  16. package/dist/cjs/providers/vault.js +49 -0
  17. package/dist/cjs/providers/vault.js.map +7 -0
  18. package/dist/cjs/resolver.js +247 -0
  19. package/dist/cjs/resolver.js.map +7 -0
  20. package/dist/cjs/secrets.js +238 -0
  21. package/dist/cjs/secrets.js.map +7 -0
  22. package/dist/cjs/strings.js +99 -0
  23. package/dist/cjs/strings.js.map +7 -0
  24. package/dist/cjs/util.js +74 -0
  25. package/dist/cjs/util.js.map +7 -0
  26. package/dist/esm/cli.js +281 -0
  27. package/dist/esm/cli.js.map +7 -0
  28. package/dist/esm/index.d.ts +342 -0
  29. package/dist/esm/index.js +347 -0
  30. package/dist/esm/index.js.map +7 -0
  31. package/dist/esm/package.json +3 -0
  32. package/dist/esm/parser.js +286 -0
  33. package/dist/esm/parser.js.map +7 -0
  34. package/dist/esm/providers/aws.js +82 -0
  35. package/dist/esm/providers/aws.js.map +7 -0
  36. package/dist/esm/providers/openbao.js +26 -0
  37. package/dist/esm/providers/openbao.js.map +7 -0
  38. package/dist/esm/providers/vault-base.js +75 -0
  39. package/dist/esm/providers/vault-base.js.map +7 -0
  40. package/dist/esm/providers/vault.js +26 -0
  41. package/dist/esm/providers/vault.js.map +7 -0
  42. package/dist/esm/resolver.js +224 -0
  43. package/dist/esm/resolver.js.map +7 -0
  44. package/dist/esm/secrets.js +209 -0
  45. package/dist/esm/secrets.js.map +7 -0
  46. package/dist/esm/strings.js +75 -0
  47. package/dist/esm/strings.js.map +7 -0
  48. package/dist/esm/util.js +47 -0
  49. package/dist/esm/util.js.map +7 -0
  50. package/package.json +66 -0
  51. package/src/cli.js +353 -0
  52. package/src/index.d.ts +342 -0
  53. package/src/index.js +473 -0
  54. package/src/parser.js +381 -0
  55. package/src/providers/aws.js +112 -0
  56. package/src/providers/openbao.js +32 -0
  57. package/src/providers/vault-base.js +92 -0
  58. package/src/providers/vault.js +31 -0
  59. package/src/resolver.js +286 -0
  60. package/src/secrets.js +313 -0
  61. package/src/strings.js +84 -0
  62. package/src/util.js +49 -0
package/src/index.js ADDED
@@ -0,0 +1,473 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import fg from "fast-glob";
4
+ import { parseColony } from "./parser.js";
5
+ import { resolveRules } from "./resolver.js";
6
+ import {
7
+ applySecretsDeep,
8
+ SecretCache,
9
+ hasGlobalProviders,
10
+ registerSecretProvider,
11
+ unregisterSecretProvider,
12
+ clearSecretProviders,
13
+ } from "./secrets.js";
14
+
15
+ // Re-export secrets functions
16
+ export { registerSecretProvider, unregisterSecretProvider, clearSecretProviders };
17
+
18
+ // Re-export providers
19
+ export { AwsSecretsProvider } from "./providers/aws.js";
20
+ export { VaultProvider } from "./providers/vault.js";
21
+ export { OpenBaoProvider } from "./providers/openbao.js";
22
+
23
+ /**
24
+ * @param {object} opts
25
+ * @param {string} opts.entry
26
+ * @param {string[]=} opts.dims
27
+ * @param {Record<string,string>=} opts.ctx
28
+ * @param {Record<string,string>=} opts.vars
29
+ * @param {(cfg: any) => any=} opts.schema // optional validation hook (e.g. zod.parse)
30
+ * @param {object=} opts.sandbox // security options
31
+ * @param {string=} opts.sandbox.basePath // restrict includes to this directory
32
+ * @param {string[]=} opts.sandbox.allowedEnvVars // whitelist of allowed env vars (null = allow all)
33
+ * @param {number=} opts.sandbox.maxIncludeDepth // max depth for includes (default 50)
34
+ * @param {boolean=} opts.warnOnSkippedIncludes // warn when skipping already-visited includes
35
+ * @param {object=} opts.secrets // secrets provider options
36
+ * @param {Array=} opts.secrets.providers // secret providers (e.g. AwsSecretsProvider)
37
+ * @param {string[]=} opts.secrets.allowedSecrets // whitelist of allowed secret patterns
38
+ * @param {object=} opts.secrets.cache // cache options
39
+ * @param {string=} opts.secrets.onNotFound // 'empty' | 'warn' | 'error' (default: 'warn')
40
+ * @returns {Promise<object>}
41
+ */
42
+ export async function loadColony(opts) {
43
+ const entry = opts?.entry;
44
+ if (!entry) throw new Error("loadColony: opts.entry is required");
45
+
46
+ const sandbox = opts.sandbox ?? {};
47
+ const basePath = sandbox.basePath ? path.resolve(sandbox.basePath) : null;
48
+ const maxIncludeDepth = sandbox.maxIncludeDepth ?? 50;
49
+ const maxFileSize = sandbox.maxFileSize ?? null;
50
+ const warnOnSkippedIncludes = opts.warnOnSkippedIncludes ?? false;
51
+
52
+ const visited = new Set();
53
+ const warnings = [];
54
+ const files = await expandIncludes(entry, visited, {
55
+ basePath,
56
+ maxIncludeDepth,
57
+ maxFileSize,
58
+ warnOnSkippedIncludes,
59
+ warnings,
60
+ });
61
+
62
+ const parsed = [];
63
+ for (const file of files) {
64
+ const text = await fs.readFile(file, "utf8");
65
+ parsed.push(parseColony(text, { filePath: file }));
66
+ }
67
+
68
+ const dims =
69
+ (Array.isArray(opts.dims) && opts.dims.length ? opts.dims : null) ??
70
+ parsed.find((p) => p.dims?.length)?.dims ??
71
+ ["env"];
72
+
73
+ // ctx precedence: opts.ctx overrides, else @envDefaults, else sensible defaults
74
+ const envDefaults = mergeEnvDefaults(parsed.map((p) => p.envDefaults ?? {}));
75
+ const ctx = {
76
+ ...envDefaults,
77
+ env: process.env.NODE_ENV ?? "dev",
78
+ ...opts.ctx,
79
+ };
80
+
81
+ const vars = { ROOT: process.cwd(), ...(opts.vars ?? {}) };
82
+
83
+ // Collect requires from all parsed files
84
+ const requires = parsed.flatMap((p) => p.requires ?? []);
85
+
86
+ const allRules = parsed.flatMap((p) => p.rules);
87
+
88
+ const allowedEnvVars = sandbox.allowedEnvVars ?? null;
89
+ const allowedVars = sandbox.allowedVars ?? null;
90
+ let cfg = resolveRules({ rules: allRules, dims, ctx, vars, allowedEnvVars, allowedVars, warnings });
91
+
92
+ // Apply secrets if providers are configured
93
+ const secretsOpts = opts.secrets ?? {};
94
+ if (secretsOpts.providers?.length || hasGlobalProviders()) {
95
+ const cacheOpts = secretsOpts.cache ?? {};
96
+ const cache = cacheOpts.enabled !== false
97
+ ? new SecretCache(cacheOpts.maxSize ?? 100)
98
+ : null;
99
+
100
+ const secretified = await applySecretsDeep(cfg, {
101
+ providers: secretsOpts.providers ?? [],
102
+ allowedSecrets: secretsOpts.allowedSecrets ?? null,
103
+ cache,
104
+ cacheTtl: cacheOpts.ttl ?? 300000,
105
+ onNotFound: secretsOpts.onNotFound ?? "warn",
106
+ warnings,
107
+ });
108
+
109
+ // Copy config methods to new object
110
+ copyConfigMethods(secretified, cfg, warnings);
111
+ cfg = secretified;
112
+ }
113
+
114
+ // Enforce @require after resolution
115
+ const missing = [];
116
+ for (const reqKey of requires) {
117
+ if (cfg.get(reqKey) === undefined) missing.push(reqKey);
118
+ }
119
+ if (missing.length) {
120
+ throw new Error(
121
+ `COLONY @require failed (missing keys):\n` +
122
+ missing.map((k) => ` - ${k}`).join("\n")
123
+ );
124
+ }
125
+
126
+ // Attach warnings as non-enumerable
127
+ Object.defineProperty(cfg, "_warnings", { enumerable: false, value: warnings });
128
+
129
+ // Optional schema validation hook (supports both sync and async)
130
+ if (typeof opts.schema === "function") {
131
+ const result = opts.schema(cfg);
132
+
133
+ // Handle async schema validators (e.g., async Zod, Joi)
134
+ if (result && typeof result.then === "function") {
135
+ const validated = await result;
136
+ if (validated && validated !== cfg) {
137
+ copyConfigMethods(validated, cfg, warnings);
138
+ return validated;
139
+ }
140
+ } else if (result && result !== cfg) {
141
+ copyConfigMethods(result, cfg, warnings);
142
+ return result;
143
+ }
144
+ }
145
+
146
+ return cfg;
147
+ }
148
+
149
+ /**
150
+ * Copy non-enumerable config methods to validated object
151
+ */
152
+ function copyConfigMethods(target, source, warnings) {
153
+ Object.defineProperties(target, {
154
+ get: { enumerable: false, value: source.get },
155
+ explain: { enumerable: false, value: source.explain },
156
+ toJSON: { enumerable: false, value: source.toJSON },
157
+ keys: { enumerable: false, value: source.keys },
158
+ diff: { enumerable: false, value: source.diff },
159
+ _trace: { enumerable: false, value: source._trace },
160
+ _warnings: { enumerable: false, value: warnings },
161
+ });
162
+ }
163
+
164
+ function mergeEnvDefaults(list) {
165
+ const out = {};
166
+ for (const m of list) {
167
+ for (const [k, v] of Object.entries(m)) out[k] = v;
168
+ }
169
+ return out;
170
+ }
171
+
172
+ async function expandIncludes(entry, visited, { basePath, maxIncludeDepth, maxFileSize, warnOnSkippedIncludes, warnings }) {
173
+ const absEntry = path.resolve(entry);
174
+ const out = [];
175
+ await dfs(absEntry, 0);
176
+ return out;
177
+
178
+ async function dfs(file, depth) {
179
+ if (depth > maxIncludeDepth) {
180
+ throw new Error(`COLONY: Max include depth (${maxIncludeDepth}) exceeded at: ${file}`);
181
+ }
182
+
183
+ const abs = path.resolve(file);
184
+
185
+ if (visited.has(abs)) {
186
+ if (warnOnSkippedIncludes) {
187
+ warnings.push({ type: "skipped_include", file: abs, message: `Skipping already-visited include: ${abs}` });
188
+ }
189
+ return;
190
+ }
191
+ visited.add(abs);
192
+
193
+ // Check file size if limit is set
194
+ if (maxFileSize !== null) {
195
+ const stat = await fs.stat(abs);
196
+ if (stat.size > maxFileSize) {
197
+ throw new Error(`COLONY: File size (${stat.size} bytes) exceeds maxFileSize (${maxFileSize} bytes): ${abs}`);
198
+ }
199
+ }
200
+
201
+ const text = await fs.readFile(abs, "utf8");
202
+ const { includes } = parseColony(text, { filePath: abs, parseOnlyDirectives: true });
203
+
204
+ for (const inc of includes) {
205
+ const incAbs = path.resolve(path.dirname(abs), inc);
206
+
207
+ // Security: validate path is within basePath if set
208
+ if (basePath !== null) {
209
+ const normalizedInc = path.normalize(incAbs);
210
+ if (!normalizedInc.startsWith(basePath + path.sep) && normalizedInc !== basePath) {
211
+ throw new Error(
212
+ `COLONY: Path traversal blocked. Include "${inc}" resolves to "${normalizedInc}" which is outside basePath "${basePath}"`
213
+ );
214
+ }
215
+ }
216
+
217
+ const matches = await fg(incAbs.replace(/\\/g, "/"), { dot: true });
218
+ // Sort alphabetically for deterministic ordering across platforms/filesystems
219
+ for (const m of matches.sort((a, b) => a.localeCompare(b))) {
220
+ // Also validate glob matches against basePath
221
+ if (basePath !== null) {
222
+ const normalizedMatch = path.normalize(m);
223
+ if (!normalizedMatch.startsWith(basePath + path.sep) && normalizedMatch !== basePath) {
224
+ throw new Error(
225
+ `COLONY: Path traversal blocked. Glob match "${m}" is outside basePath "${basePath}"`
226
+ );
227
+ }
228
+ }
229
+ await dfs(m, depth + 1);
230
+ }
231
+ }
232
+
233
+ out.push(abs);
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Validate syntax of colony files without resolving
239
+ * @param {string} entry - Entry file path
240
+ * @returns {Promise<{valid: boolean, files: string[], errors: Array<{file: string, error: string}>}>}
241
+ */
242
+ export async function validateColony(entry) {
243
+ const visited = new Set();
244
+ const files = [];
245
+ const errors = [];
246
+
247
+ await validateDfs(path.resolve(entry));
248
+
249
+ return {
250
+ valid: errors.length === 0,
251
+ files,
252
+ errors,
253
+ };
254
+
255
+ async function validateDfs(file) {
256
+ const abs = path.resolve(file);
257
+ if (visited.has(abs)) return;
258
+ visited.add(abs);
259
+
260
+ try {
261
+ const text = await fs.readFile(abs, "utf8");
262
+ const { includes } = parseColony(text, { filePath: abs });
263
+ files.push(abs);
264
+
265
+ for (const inc of includes) {
266
+ const incAbs = path.resolve(path.dirname(abs), inc);
267
+ const matches = await fg(incAbs.replace(/\\/g, "/"), { dot: true });
268
+ for (const m of matches.sort((a, b) => a.localeCompare(b))) {
269
+ await validateDfs(m);
270
+ }
271
+ }
272
+ } catch (e) {
273
+ errors.push({ file: abs, error: e.message });
274
+ }
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Dry-run: list all files that would be included
280
+ * @param {string} entry - Entry file path
281
+ * @returns {Promise<string[]>}
282
+ */
283
+ export async function dryRunIncludes(entry) {
284
+ const visited = new Set();
285
+ const files = [];
286
+ await dryRunDfs(path.resolve(entry));
287
+ return files;
288
+
289
+ async function dryRunDfs(file) {
290
+ const abs = path.resolve(file);
291
+ if (visited.has(abs)) return;
292
+ visited.add(abs);
293
+
294
+ const text = await fs.readFile(abs, "utf8");
295
+ const { includes } = parseColony(text, { filePath: abs, parseOnlyDirectives: true });
296
+
297
+ for (const inc of includes) {
298
+ const incAbs = path.resolve(path.dirname(abs), inc);
299
+ const matches = await fg(incAbs.replace(/\\/g, "/"), { dot: true });
300
+ for (const m of matches.sort((a, b) => a.localeCompare(b))) {
301
+ await dryRunDfs(m);
302
+ }
303
+ }
304
+
305
+ files.push(abs);
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Compare two configs loaded with different contexts
311
+ * @param {object} opts - Same options as loadColony, but with ctx1 and ctx2
312
+ * @param {Record<string,string>} opts.ctx1 - First context
313
+ * @param {Record<string,string>} opts.ctx2 - Second context
314
+ * @returns {Promise<{cfg1: object, cfg2: object, diff: object}>}
315
+ */
316
+ export async function diffColony(opts) {
317
+ const { ctx1, ctx2, ...baseOpts } = opts;
318
+
319
+ if (!ctx1 || !ctx2) {
320
+ throw new Error("diffColony: both ctx1 and ctx2 are required");
321
+ }
322
+
323
+ const cfg1 = await loadColony({ ...baseOpts, ctx: ctx1 });
324
+ const cfg2 = await loadColony({ ...baseOpts, ctx: ctx2 });
325
+
326
+ return {
327
+ cfg1,
328
+ cfg2,
329
+ diff: cfg1.diff(cfg2),
330
+ };
331
+ }
332
+
333
+ /**
334
+ * Lint colony files for potential issues
335
+ * @param {object} opts
336
+ * @param {string} opts.entry - Entry file path
337
+ * @param {string[]=} opts.dims - Dimension names
338
+ * @returns {Promise<{issues: Array<{type: string, severity: string, message: string, file?: string, line?: number}>}>}
339
+ */
340
+ export async function lintColony(opts) {
341
+ const entry = opts?.entry;
342
+ if (!entry) throw new Error("lintColony: opts.entry is required");
343
+
344
+ const issues = [];
345
+ const visited = new Set();
346
+ const allRules = [];
347
+ const allFiles = [];
348
+ let foundDims = null;
349
+
350
+ // Collect all rules from all files
351
+ await collectRules(path.resolve(entry));
352
+
353
+ async function collectRules(file) {
354
+ const abs = path.resolve(file);
355
+ if (visited.has(abs)) return;
356
+ visited.add(abs);
357
+
358
+ try {
359
+ const text = await fs.readFile(abs, "utf8");
360
+ const parsed = parseColony(text, { filePath: abs });
361
+ allFiles.push(abs);
362
+
363
+ // Capture dims from first file that has them
364
+ if (!foundDims && parsed.dims?.length) {
365
+ foundDims = parsed.dims;
366
+ }
367
+
368
+ for (const rule of parsed.rules) {
369
+ allRules.push({ ...rule, filePath: abs });
370
+ }
371
+
372
+ for (const inc of parsed.includes) {
373
+ const incAbs = path.resolve(path.dirname(abs), inc);
374
+ const matches = await fg(incAbs.replace(/\\/g, "/"), { dot: true });
375
+ for (const m of matches.sort((a, b) => a.localeCompare(b))) {
376
+ await collectRules(m);
377
+ }
378
+ }
379
+ } catch (e) {
380
+ issues.push({
381
+ type: "parse_error",
382
+ severity: "error",
383
+ message: e.message,
384
+ file: abs,
385
+ });
386
+ }
387
+ }
388
+
389
+ // Get dims from options, or from parsed files, or default
390
+ const dims = opts.dims ?? foundDims ?? ["env"];
391
+
392
+ // Check for shadowed rules (same key, same scope, different values)
393
+ const rulesByKey = new Map();
394
+ for (const rule of allRules) {
395
+ const scope = rule.keySegments.slice(0, dims.length).join(".");
396
+ const keyPath = rule.keySegments.slice(dims.length).join(".");
397
+ const key = `${scope}|${keyPath}`;
398
+
399
+ if (!rulesByKey.has(key)) {
400
+ rulesByKey.set(key, []);
401
+ }
402
+ rulesByKey.get(key).push(rule);
403
+ }
404
+
405
+ for (const [key, rules] of rulesByKey.entries()) {
406
+ if (rules.length > 1) {
407
+ // Check if they're in different files or same file
408
+ const locations = rules.map((r) => `${r.filePath}:${r.line}`);
409
+ const uniqueLocations = new Set(locations);
410
+
411
+ if (uniqueLocations.size > 1) {
412
+ const [scope, keyPath] = key.split("|");
413
+ issues.push({
414
+ type: "shadowed_rule",
415
+ severity: "warning",
416
+ message: `Rule "${scope}.${keyPath}" is defined ${rules.length} times. Later rule wins.`,
417
+ file: rules[rules.length - 1].filePath,
418
+ line: rules[rules.length - 1].line,
419
+ });
420
+ }
421
+ }
422
+ }
423
+
424
+ // Check for potentially unused wildcard rules
425
+ // (rules with all wildcards that might be overridden by more specific rules)
426
+ for (const rule of allRules) {
427
+ const scope = rule.keySegments.slice(0, dims.length);
428
+ const keyPath = rule.keySegments.slice(dims.length).join(".");
429
+
430
+ if (scope.every((s) => s === "*")) {
431
+ // Check if there are more specific rules for the same key
432
+ const moreSpecific = allRules.filter((r) => {
433
+ const rKeyPath = r.keySegments.slice(dims.length).join(".");
434
+ if (rKeyPath !== keyPath) return false;
435
+ const rScope = r.keySegments.slice(0, dims.length);
436
+ return rScope.some((s) => s !== "*") && r !== rule;
437
+ });
438
+
439
+ if (moreSpecific.length > 0) {
440
+ issues.push({
441
+ type: "overridden_wildcard",
442
+ severity: "info",
443
+ message: `Wildcard rule for "${keyPath}" is overridden by ${moreSpecific.length} more specific rule(s)`,
444
+ file: rule.filePath,
445
+ line: rule.line,
446
+ });
447
+ }
448
+ }
449
+ }
450
+
451
+ // Check for empty includes
452
+ for (const file of allFiles) {
453
+ try {
454
+ const text = await fs.readFile(file, "utf8");
455
+ const parsed = parseColony(text, { filePath: file });
456
+
457
+ for (const inc of parsed.includes) {
458
+ const incAbs = path.resolve(path.dirname(file), inc);
459
+ const matches = await fg(incAbs.replace(/\\/g, "/"), { dot: true });
460
+ if (matches.length === 0) {
461
+ issues.push({
462
+ type: "empty_include",
463
+ severity: "warning",
464
+ message: `Include pattern "${inc}" matches no files`,
465
+ file,
466
+ });
467
+ }
468
+ }
469
+ } catch {}
470
+ }
471
+
472
+ return { issues };
473
+ }