@indigoai-us/hq-cli 5.8.5 → 5.9.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.
@@ -0,0 +1,144 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="01fee323-1f63-5411-bfc9-ff49e241f712")}catch(e){}}();
3
+ import { ResolutionError } from 'varlock/plugin-lib';
4
+ import { readCache, writeCache } from '../utils/secrets-cache.js';
5
+ export function installHqPlugin(graph /* EnvGraph */, opts) {
6
+ const pluginState = {
7
+ schemaCompanySlug: null,
8
+ uid: null,
9
+ errorsByName: new Map(),
10
+ };
11
+ // varlock@1.0.0's plugin-lib.js omits the Resolver export (d.ts/JS mismatch);
12
+ // extract it at runtime from any already-registered built-in resolver's prototype.
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ let RuntimeResolver;
15
+ try {
16
+ const fns = graph.registeredResolverFunctions;
17
+ const first = Object.values(fns)[0];
18
+ if (first == null)
19
+ throw new Error('registeredResolverFunctions is empty');
20
+ const proto = Object.getPrototypeOf(first);
21
+ if (proto == null || typeof proto.prototype?.process !== 'function') {
22
+ throw new Error('prototype has no process method');
23
+ }
24
+ RuntimeResolver = proto;
25
+ }
26
+ catch (e) {
27
+ throw new Error('varlock Resolver base class extraction failed — the varlock@1.0.0 d.ts/JS mismatch ' +
28
+ 'may have been resolved; switch to `import { Resolver } from "varlock/plugin-lib"`. ' +
29
+ `Underlying: ${e instanceof Error ? e.message : String(e)}`);
30
+ }
31
+ // HqResolver is declared INSIDE installHqPlugin so its static def.resolve
32
+ // closes over `pluginState`. Module-scope declaration is forbidden — resolve()
33
+ // would hit `ReferenceError: pluginState is not defined`.
34
+ class HqResolver extends RuntimeResolver {
35
+ static def = {
36
+ name: 'hq',
37
+ impliesSensitive: true,
38
+ argsSchema: { type: 'array', arrayMaxLength: 1 },
39
+ resolve: async function () {
40
+ // Cache-only read. `pluginState` is captured by this inner-class closure;
41
+ // `prewarmHqSecrets(graph, opts, state)` populates `state.uid` and
42
+ // `state.errorsByName` before `graph.resolveEnvValues()` calls us.
43
+ const explicit = this.arrArgs?.[0]?.staticValue;
44
+ const secretName = (typeof explicit === 'string' && explicit) ? explicit : this._ownerKey;
45
+ if (!secretName) {
46
+ throw new ResolutionError('hq() resolver could not determine secret name (missing owner key)');
47
+ }
48
+ const err = pluginState.errorsByName.get(secretName);
49
+ if (err) {
50
+ if (err.code === 'forbidden') {
51
+ throw new ResolutionError(`No read permission for secret "${secretName}" — ask an admin to share it via \`hq secrets share ${secretName} --with <you> --permission read\``);
52
+ }
53
+ if (err.code === 'not_found') {
54
+ throw new ResolutionError(`Secret "${secretName}" does not exist in company`);
55
+ }
56
+ throw new ResolutionError(`Failed to load secret "${secretName}": ${err.message ?? err.code}`);
57
+ }
58
+ // Sentinel-check style throughout: `readCache` returns `string | null`
59
+ // (verified at `hq/packages/hq-cli/src/utils/secrets-cache.ts:45`); `pluginState.uid`
60
+ // is `string | null` per `PluginState`. Use `== null` (covers null AND undefined defensively)
61
+ // for both — do not mix in truthy checks like `if (!x)`, which would silently swallow a
62
+ // legitimate empty-string value if the contract ever loosened.
63
+ if (pluginState.uid == null) {
64
+ throw new ResolutionError('Internal error: prewarmHqSecrets was not called before resolveEnvValues');
65
+ }
66
+ const cached = readCache(pluginState.uid, secretName); // string | null
67
+ if (cached == null) {
68
+ throw new ResolutionError(`Internal error: pre-warm did not populate cache for "${secretName}"`);
69
+ }
70
+ return cached;
71
+ },
72
+ };
73
+ // Captured during process(parent); used by resolve() to fall back to the var key.
74
+ _ownerKey;
75
+ process(parent) {
76
+ super.process(parent);
77
+ if (parent != null && typeof parent.key === 'string') {
78
+ this._ownerKey = parent.key;
79
+ }
80
+ }
81
+ }
82
+ // varlock@1.0.0's env-spec parser rejects dots in decorator names ([a-zA-Z0-9_] only),
83
+ // so `@hq.company` is not valid syntax. We register as `@hqCompany` (camelCase) instead.
84
+ // Schema files must use `# @hqCompany("slug")` followed by a blank line so the parser
85
+ // treats it as a file-level root decorator rather than an item decorator for the next var.
86
+ graph.registerRootDecorator({
87
+ name: 'hqCompany',
88
+ isFunction: true,
89
+ process: (decoratorValue) => {
90
+ const slug = decoratorValue.arrArgs?.[0]?.staticValue;
91
+ return typeof slug === 'string' ? slug : null;
92
+ },
93
+ execute: (slug) => {
94
+ if (slug)
95
+ pluginState.schemaCompanySlug = slug;
96
+ },
97
+ });
98
+ graph.registerResolver(HqResolver);
99
+ // Returned so `prewarmHqSecrets(graph, opts, state)` can read schemaCompanySlug
100
+ // and write `uid` + `errorsByName`. The state is held by the closure; the returned handle
101
+ // is purely for the prewarm helper.
102
+ return pluginState;
103
+ }
104
+ export async function prewarmHqSecrets(graph /* EnvGraph */, opts, state) {
105
+ const queue = [];
106
+ for (const [key, item] of Object.entries(graph.configSchema)) {
107
+ const resolver = item.valueResolver;
108
+ if (resolver?.def?.name === 'hq') {
109
+ const explicit = resolver.arrArgs?.[0]?.staticValue;
110
+ const secretName = (typeof explicit === 'string' && explicit) ? explicit : key;
111
+ queue.push({ key, secretName });
112
+ }
113
+ }
114
+ if (queue.length === 0) {
115
+ return;
116
+ }
117
+ let slug;
118
+ if (state.schemaCompanySlug) {
119
+ slug = state.schemaCompanySlug;
120
+ }
121
+ else if (opts.companyOverride) {
122
+ slug = opts.companyOverride;
123
+ }
124
+ else {
125
+ throw new Error('@hqCompany("...") not declared and --company not passed');
126
+ }
127
+ const uid = await opts.resolveCompanyUid(slug);
128
+ const uniqueNames = [...new Set(queue.map((q) => q.secretName))];
129
+ if (uniqueNames.length > 100) {
130
+ throw new Error(`hq run supports at most 100 hq() resolvers per schema; got ${uniqueNames.length}`);
131
+ }
132
+ const result = await opts.fetchBatch(uid, uniqueNames);
133
+ for (const s of result.secrets) {
134
+ writeCache(uid, s.name, s.value);
135
+ }
136
+ const errorsByName = new Map();
137
+ for (const e of result.errors) {
138
+ errorsByName.set(e.name, { code: e.code, message: e.message });
139
+ }
140
+ state.errorsByName = errorsByName;
141
+ state.uid = uid;
142
+ }
143
+ //# sourceMappingURL=hq-plugin.js.map
144
+ //# debugId=01fee323-1f63-5411-bfc9-ff49e241f712
@@ -0,0 +1,10 @@
1
+ export interface VaultApiOptions {
2
+ token: string;
3
+ path: string;
4
+ method?: string;
5
+ body?: Record<string, unknown>;
6
+ query?: Record<string, string>;
7
+ }
8
+ export declare function vaultApiFetch(opts: VaultApiOptions): Promise<Response>;
9
+ export declare function getCompanyUid(token: string, companySlug: string | undefined): Promise<string>;
10
+ //# sourceMappingURL=vault-api.d.ts.map
@@ -0,0 +1,58 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4e482805-d129-5563-a77b-97b80410154b")}catch(e){}}();
3
+ import { DEFAULT_VAULT_API_URL } from './cognito-session.js';
4
+ export async function vaultApiFetch(opts) {
5
+ const url = new URL(opts.path, DEFAULT_VAULT_API_URL);
6
+ if (opts.query) {
7
+ for (const [k, v] of Object.entries(opts.query)) {
8
+ url.searchParams.set(k, v);
9
+ }
10
+ }
11
+ return fetch(url.toString(), {
12
+ method: opts.method ?? 'GET',
13
+ headers: {
14
+ Authorization: `Bearer ${opts.token}`,
15
+ 'Content-Type': 'application/json',
16
+ },
17
+ body: opts.body ? JSON.stringify(opts.body) : undefined,
18
+ });
19
+ }
20
+ async function resolveCompanyUid(token, slug) {
21
+ const res = await vaultApiFetch({
22
+ token,
23
+ path: `/entity/by-slug/company/${encodeURIComponent(slug)}`,
24
+ });
25
+ if (!res.ok) {
26
+ const body = await res.json().catch(() => ({}));
27
+ throw new Error(`Failed to resolve company slug '${slug}': ${body.error ?? res.statusText}`);
28
+ }
29
+ const data = (await res.json());
30
+ return data.entity.uid;
31
+ }
32
+ async function resolveCompanyFromMemberships(token) {
33
+ const res = await vaultApiFetch({
34
+ token,
35
+ path: '/membership/me',
36
+ });
37
+ if (!res.ok) {
38
+ throw new Error("Failed to fetch memberships — run `hq login` and try again");
39
+ }
40
+ const data = (await res.json());
41
+ const active = data.memberships.filter((m) => m.status === 'active');
42
+ if (active.length === 0) {
43
+ throw new Error('No active company memberships found. Use --company <slug> to specify.');
44
+ }
45
+ if (active.length === 1) {
46
+ return active[0].companyUid;
47
+ }
48
+ const uids = active.map((m) => m.companyUid).join(', ');
49
+ throw new Error(`Multiple companies found (${uids}). Use --company <slug> to specify which one.`);
50
+ }
51
+ export async function getCompanyUid(token, companySlug) {
52
+ if (companySlug) {
53
+ return resolveCompanyUid(token, companySlug);
54
+ }
55
+ return resolveCompanyFromMemberships(token);
56
+ }
57
+ //# sourceMappingURL=vault-api.js.map
58
+ //# debugId=4e482805-d129-5563-a77b-97b80410154b
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.8.5",
3
+ "version": "5.9.0",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -21,7 +21,8 @@
21
21
  "commander": "^12.1.0",
22
22
  "js-yaml": "^4.1.0",
23
23
  "simple-git": "^3.27.0",
24
- "semver": "^7.6.3"
24
+ "semver": "^7.6.3",
25
+ "varlock": "1.0.0"
25
26
  },
26
27
  "devDependencies": {
27
28
  "@types/js-yaml": "^4.0.9",
@@ -42,5 +43,8 @@
42
43
  "cloud"
43
44
  ],
44
45
  "license": "MIT",
45
- "type": "module"
46
+ "type": "module",
47
+ "engines": {
48
+ "node": ">=22.0.0"
49
+ }
46
50
  }
@@ -154,20 +154,35 @@ export function registerFilesCommand(program: Command): void {
154
154
  const companySlug = files.opts().company as string | undefined;
155
155
  const companyUid = await getCompanyUid(token, companySlug);
156
156
 
157
- const res = await vaultApiFetch({
158
- token,
159
- path: `/files/${encodeURIComponent(companyUid)}/acl`,
160
- query: { prefix: canonicalPrefix },
161
- });
157
+ // Fetch the prefix's own ACL row (creator, open flag, effective
158
+ // permission) and the inherited/descendant tree in parallel so the
159
+ // user sees every grant that affects this prefix in one shot.
160
+ const [aclRes, treeRes] = await Promise.all([
161
+ vaultApiFetch({
162
+ token,
163
+ path: `/files/${encodeURIComponent(companyUid)}/acl`,
164
+ query: { prefix: canonicalPrefix },
165
+ }),
166
+ vaultApiFetch({
167
+ token,
168
+ path: `/files/${encodeURIComponent(companyUid)}/acl/tree`,
169
+ query: { prefix: canonicalPrefix },
170
+ }),
171
+ ]);
162
172
 
163
- if (!res.ok) {
164
- const body = await res.json().catch(() => ({})) as Record<string, string>;
173
+ async function readErrorBody(res: Response): Promise<Record<string, string>> {
174
+ return (await res.json().catch(() => ({}))) as Record<string, string>;
175
+ }
176
+
177
+ // Auth/server failures from either call are treated identically — bail
178
+ // out with a single message rather than printing a half-rendered view.
179
+ for (const res of [aclRes, treeRes]) {
180
+ if (res.ok || res.status === 404) continue;
181
+ const body = await readErrorBody(res);
165
182
  if (res.status === 401) {
166
183
  console.error(chalk.red("Not authenticated — please run `hq login`"));
167
184
  } else if (res.status === 403) {
168
185
  console.error(chalk.red("Not authorized to view this file prefix's ACL"));
169
- } else if (res.status === 404) {
170
- console.error(chalk.red(`No ACL record exists for '${canonicalPrefix}'`));
171
186
  } else if (res.status >= 500) {
172
187
  console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
173
188
  } else {
@@ -176,7 +191,14 @@ export function registerFilesCommand(program: Command): void {
176
191
  process.exit(1);
177
192
  }
178
193
 
179
- const data = await res.json() as {
194
+ type AclEntry = {
195
+ granteeType: string;
196
+ granteeId: string;
197
+ permission: string;
198
+ grantedBy: string;
199
+ grantedAt: string;
200
+ };
201
+ type AclResponse = {
180
202
  acl: {
181
203
  itemType: string;
182
204
  companyUid: string;
@@ -186,60 +208,98 @@ export function registerFilesCommand(program: Command): void {
186
208
  prefix?: string;
187
209
  creatorUid: string;
188
210
  open?: boolean;
189
- entries: Array<{
190
- granteeType: string;
191
- granteeId: string;
192
- permission: string;
193
- grantedBy: string;
194
- grantedAt: string;
195
- }>;
211
+ entries: AclEntry[];
196
212
  effectivePermission?: string | null;
197
213
  createdAt: string;
198
214
  updatedAt: string;
199
215
  };
200
216
  };
217
+ type TreeResponse = {
218
+ prefix: string;
219
+ direct: AclEntry[];
220
+ inherited: Array<AclEntry & { sourcePrefix: string }>;
221
+ children: Array<AclEntry & { sourcePrefix: string }>;
222
+ };
223
+
224
+ const acl = aclRes.ok ? (await aclRes.json() as AclResponse).acl : null;
225
+ const tree = treeRes.ok ? (await treeRes.json()) as TreeResponse : null;
226
+
227
+ // No own row AND nothing inherited or granted below — original
228
+ // "no ACL record" exit path.
229
+ if (!acl && (!tree || (tree.inherited.length === 0 && tree.children.length === 0))) {
230
+ console.error(chalk.red(`No ACL record exists for '${canonicalPrefix}'`));
231
+ process.exit(1);
232
+ }
201
233
 
202
- const acl = data.acl;
203
- const aclStatus = acl.open ? "open" : "restricted";
204
- const aclPrefix = acl.path ?? acl.prefix ?? canonicalPrefix;
234
+ const aclPrefix = acl?.path ?? acl?.prefix ?? tree?.prefix ?? canonicalPrefix;
235
+ const aclStatus = acl?.open ? "open" : "restricted";
205
236
 
206
237
  console.log(chalk.green(`ACL for ${aclPrefix} (${aclStatus})`));
207
- console.log(`Creator: ${acl.creatorUid}`);
208
- if (acl.effectivePermission) {
209
- console.log(`Your effective permission: ${acl.effectivePermission}`);
238
+ if (acl) {
239
+ console.log(`Creator: ${acl.creatorUid}`);
240
+ if (acl.effectivePermission) {
241
+ console.log(`Your effective permission: ${acl.effectivePermission}`);
242
+ }
243
+ } else {
244
+ console.log(chalk.gray(
245
+ "No direct ACL row — access flows from the inherited/descendant grants below.",
246
+ ));
210
247
  }
211
248
 
212
- if (acl.entries.length === 0) {
213
- if (acl.open) {
249
+ function printEntryTable(
250
+ rows: Array<AclEntry & { sourcePrefix?: string }>,
251
+ showSource: boolean,
252
+ ): void {
253
+ const TYPE_W = Math.max(4, ...rows.map((e) => e.granteeType.length));
254
+ const GRANTEE_W = Math.max(7, ...rows.map((e) => e.granteeId.length));
255
+ const PERM_W = Math.max(10, ...rows.map((e) => e.permission.length));
256
+ const BY_W = Math.max(10, ...rows.map((e) => e.grantedBy.length));
257
+ const SRC_W = showSource
258
+ ? Math.max(6, ...rows.map((e) => (e.sourcePrefix ?? "").length))
259
+ : 0;
260
+ const headerCols = [
261
+ "TYPE".padEnd(TYPE_W),
262
+ "GRANTEE".padEnd(GRANTEE_W),
263
+ "PERMISSION".padEnd(PERM_W),
264
+ "GRANTED_BY".padEnd(BY_W),
265
+ "GRANTED_AT",
266
+ ];
267
+ if (showSource) headerCols.splice(4, 0, "SOURCE".padEnd(SRC_W));
268
+ console.log(chalk.bold(headerCols.join(" ")));
269
+ for (const e of rows) {
270
+ const grantedAt = e.grantedAt.slice(0, 10);
271
+ const cols = [
272
+ e.granteeType.padEnd(TYPE_W),
273
+ e.granteeId.padEnd(GRANTEE_W),
274
+ e.permission.padEnd(PERM_W),
275
+ e.grantedBy.padEnd(BY_W),
276
+ grantedAt,
277
+ ];
278
+ if (showSource) cols.splice(4, 0, (e.sourcePrefix ?? "").padEnd(SRC_W));
279
+ console.log(cols.join(" "));
280
+ }
281
+ }
282
+
283
+ const directEntries = acl?.entries ?? tree?.direct ?? [];
284
+ if (directEntries.length === 0) {
285
+ if (acl?.open) {
214
286
  console.log(chalk.gray("Open ACL — all active members have read access."));
215
- } else {
216
- console.log(chalk.gray("No explicit grants — only creator has access."));
287
+ } else if (acl) {
288
+ console.log(chalk.gray("No explicit grants on this prefix — only creator has access."));
217
289
  }
218
- return;
290
+ } else {
291
+ console.log("\nDirect entries (granted on this prefix):");
292
+ printEntryTable(directEntries, false);
293
+ }
294
+
295
+ if (tree && tree.inherited.length > 0) {
296
+ console.log("\nInherited (granted on an ancestor prefix):");
297
+ printEntryTable(tree.inherited, true);
219
298
  }
220
299
 
221
- console.log("Entries:");
222
- const TYPE_W = Math.max(4, ...acl.entries.map((e) => e.granteeType.length));
223
- const GRANTEE_W = Math.max(7, ...acl.entries.map((e) => e.granteeId.length));
224
- const PERM_W = Math.max(10, ...acl.entries.map((e) => e.permission.length));
225
- const BY_W = Math.max(10, ...acl.entries.map((e) => e.grantedBy.length));
226
- const tableHeader = [
227
- "TYPE".padEnd(TYPE_W),
228
- "GRANTEE".padEnd(GRANTEE_W),
229
- "PERMISSION".padEnd(PERM_W),
230
- "GRANTED_BY".padEnd(BY_W),
231
- "GRANTED_AT",
232
- ].join(" ");
233
- console.log(chalk.bold(tableHeader));
234
- for (const e of acl.entries) {
235
- const grantedAt = e.grantedAt.slice(0, 10);
236
- console.log([
237
- e.granteeType.padEnd(TYPE_W),
238
- e.granteeId.padEnd(GRANTEE_W),
239
- e.permission.padEnd(PERM_W),
240
- e.grantedBy.padEnd(BY_W),
241
- grantedAt,
242
- ].join(" "));
300
+ if (tree && tree.children.length > 0) {
301
+ console.log("\nGranted on descendant prefixes (do not affect this prefix's access):");
302
+ printEntryTable(tree.children, true);
243
303
  }
244
304
  } catch (err) {
245
305
  console.error(chalk.red("Error:"), err instanceof Error ? err.message : String(err));
@@ -0,0 +1,84 @@
1
+ import { afterEach, beforeEach, expect, test, vi } from 'vitest';
2
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { internal } from 'varlock';
6
+ import { discoverSchemas } from '../run/discover-schemas.js';
7
+ import { installHqPlugin, prewarmHqSecrets, type PluginState } from '../run/hq-plugin.js';
8
+
9
+ vi.mock('../utils/secrets-cache.js', () => {
10
+ const store = new Map<string, string>();
11
+ return {
12
+ readCache: (uid: string, name: string): string | null =>
13
+ store.get(`${uid}\0${name}`) ?? null,
14
+ writeCache: (uid: string, name: string, value: string): void => {
15
+ store.set(`${uid}\0${name}`, value);
16
+ },
17
+ removeCacheEntry: (): void => {},
18
+ clearAllCache: (): { removed: number } => ({ removed: 0 }),
19
+ };
20
+ });
21
+
22
+ let dir: string;
23
+
24
+ beforeEach(() => {
25
+ dir = mkdtempSync(join(tmpdir(), 'hq-run-envlocal-'));
26
+ });
27
+
28
+ afterEach(() => {
29
+ rmSync(dir, { recursive: true, force: true });
30
+ });
31
+
32
+ test('.env.local overrides hq()-resolved value', async () => {
33
+ // Blank line after @hqCompany required: varlock only treats it as a root (file-level)
34
+ // decorator when separated from the first var by a blank line.
35
+ writeFileSync(join(dir, '.env.schema'), '# @hqCompany("indigo")\n\n# @required\nKEY=hq()\n');
36
+ writeFileSync(join(dir, '.env.local'), 'KEY=local-value\n');
37
+
38
+ const result = discoverSchemas(dir);
39
+ expect(result.schemaPaths).toEqual([join(dir, '.env.schema')]);
40
+ expect(result.envLocalPaths).toEqual([join(dir, '.env.local')]);
41
+
42
+ const paths = [...result.schemaPaths, ...result.envLocalPaths];
43
+ const opts = {
44
+ companyOverride: undefined,
45
+ resolveCompanyUid: async () => 'fake-uid',
46
+ // fetchBatch returns "vault-value" — if .env.local is correctly wired,
47
+ // graph resolution should still surface "local-value" because the local
48
+ // file wins precedence.
49
+ fetchBatch: async () => ({ secrets: [{ name: 'KEY', value: 'vault-value' }], errors: [] }),
50
+ };
51
+
52
+ let state!: PluginState;
53
+ const graph = await internal.loadEnvGraph({
54
+ entryFilePaths: paths,
55
+ afterInit: (g) => { state = installHqPlugin(g, opts); },
56
+ });
57
+ await prewarmHqSecrets(graph, opts, state);
58
+ await graph.resolveEnvValues();
59
+ expect(graph.getResolvedEnvObject().KEY).toBe('local-value');
60
+ });
61
+
62
+ test('without .env.local, vault value is returned', async () => {
63
+ writeFileSync(join(dir, '.env.schema'), '# @hqCompany("indigo")\n\n# @required\nKEY=hq()\n');
64
+
65
+ const result = discoverSchemas(dir);
66
+ expect(result.schemaPaths).toEqual([join(dir, '.env.schema')]);
67
+ expect(result.envLocalPaths).toEqual([]);
68
+
69
+ const paths = [...result.schemaPaths, ...result.envLocalPaths];
70
+ const opts = {
71
+ companyOverride: undefined,
72
+ resolveCompanyUid: async () => 'fake-uid',
73
+ fetchBatch: async () => ({ secrets: [{ name: 'KEY', value: 'vault-value' }], errors: [] }),
74
+ };
75
+
76
+ let state!: PluginState;
77
+ const graph = await internal.loadEnvGraph({
78
+ entryFilePaths: paths,
79
+ afterInit: (g) => { state = installHqPlugin(g, opts); },
80
+ });
81
+ await prewarmHqSecrets(graph, opts, state);
82
+ await graph.resolveEnvValues();
83
+ expect(graph.getResolvedEnvObject().KEY).toBe('vault-value');
84
+ });
@@ -0,0 +1,137 @@
1
+ import { Command } from 'commander';
2
+ import { spawn } from 'node:child_process';
3
+ import * as path from 'node:path';
4
+ import * as fs from 'node:fs';
5
+ import { internal } from 'varlock';
6
+ import { ensureCognitoToken } from '../utils/cognito-session.js';
7
+ import { vaultApiFetch, getCompanyUid } from '../utils/vault-api.js';
8
+ import { discoverSchemas } from '../run/discover-schemas.js';
9
+ import { installHqPlugin, prewarmHqSecrets, type PluginState, type InstallHqPluginOpts } from '../run/hq-plugin.js';
10
+
11
+ export function registerRunCommand(program: Command): void {
12
+ program
13
+ .command('run')
14
+ .description('Load secrets from .env.schema and run a command with them injected')
15
+ .option('--company <slug>', 'Company slug (overrides @hqCompany in schema)')
16
+ .option('--schema <path>', 'Explicit schema path (skips walk-up discovery)')
17
+ .option('--check', 'Resolve schema and validate vars without executing the command')
18
+ .allowUnknownOption(true)
19
+ .action(async (opts: { company?: string; schema?: string; check?: boolean }) => {
20
+ try {
21
+ const dashIndex = process.argv.indexOf('--');
22
+ const childArgs = dashIndex !== -1 ? process.argv.slice(dashIndex + 1) : [];
23
+
24
+ if (!opts.check && childArgs.length === 0) {
25
+ throw new Error('no command specified. Usage: hq run [options] -- <command> [args...]');
26
+ }
27
+
28
+ let schemaPaths: string[];
29
+ let envLocalPaths: string[];
30
+ let schemaCompanySlug: string | null;
31
+
32
+ if (opts.schema) {
33
+ const schemaAbs = path.resolve(opts.schema);
34
+ schemaPaths = [schemaAbs];
35
+ const localPath = path.join(path.dirname(schemaAbs), '.env.local');
36
+ envLocalPaths = fs.existsSync(localPath) ? [localPath] : [];
37
+ const content = fs.readFileSync(schemaAbs, 'utf8');
38
+ const m = /^# @hqCompany\("([^"]+)"\)/m.exec(content);
39
+ schemaCompanySlug = m ? m[1] : null;
40
+ } else {
41
+ const discovered = discoverSchemas(process.cwd());
42
+ if (discovered.conflict) {
43
+ throw new Error(
44
+ `conflicting @hqCompany slugs: "${discovered.conflict.slugs[0]}" in ${discovered.conflict.paths[0]} vs "${discovered.conflict.slugs[1]}" in ${discovered.conflict.paths[1]}. Use --company <slug> to override.`,
45
+ );
46
+ }
47
+ if (discovered.schemaPaths.length === 0) {
48
+ throw new Error('no .env.schema found. Create one or use --schema <path>.');
49
+ }
50
+ schemaPaths = discovered.schemaPaths;
51
+ envLocalPaths = discovered.envLocalPaths;
52
+ schemaCompanySlug = discovered.companySlug;
53
+ }
54
+
55
+ const slug = opts.company ?? schemaCompanySlug;
56
+ if (!slug) {
57
+ throw new Error('company slug not set. Add # @hqCompany("slug") to your .env.schema or pass --company <slug>.');
58
+ }
59
+
60
+ const token = await ensureCognitoToken();
61
+ const uid = await getCompanyUid(token, slug);
62
+
63
+ const fetchBatch: InstallHqPluginOpts['fetchBatch'] = async (companyUid, names) => {
64
+ const res = await vaultApiFetch({
65
+ token,
66
+ path: `/secrets/${encodeURIComponent(companyUid)}/load`,
67
+ method: 'POST',
68
+ body: { names },
69
+ });
70
+ if (!res.ok) {
71
+ const body = await res.json().catch(() => ({})) as Record<string, string>;
72
+ throw new Error(`Failed to batch-load secrets: ${body.error ?? res.statusText}`);
73
+ }
74
+ return res.json() as Promise<{
75
+ secrets: Array<{ name: string; value: string }>;
76
+ errors: Array<{ name: string; code: string; message?: string }>;
77
+ }>;
78
+ };
79
+
80
+ const pluginOpts: InstallHqPluginOpts = {
81
+ companyOverride: opts.company,
82
+ resolveCompanyUid: async () => uid,
83
+ fetchBatch,
84
+ };
85
+
86
+ // LAST entry = highest precedence; .env.local files trail .env.schema files so any .env.local beats any schema regardless of depth.
87
+ const paths = [...schemaPaths, ...envLocalPaths];
88
+
89
+ let state!: PluginState;
90
+ const graph = await internal.loadEnvGraph({
91
+ entryFilePaths: paths,
92
+ afterInit: async (g) => { state = installHqPlugin(g, pluginOpts); },
93
+ });
94
+ await prewarmHqSecrets(graph, pluginOpts, state);
95
+ await graph.resolveEnvValues();
96
+
97
+ const schemaErrors = Object.entries(graph.configSchema as Record<string, any>)
98
+ .filter(([, item]) => (item.errors as unknown[])?.length > 0);
99
+ if (schemaErrors.length > 0) {
100
+ const msgs = schemaErrors.flatMap(([k, item]) =>
101
+ (item.errors as Array<{ message?: string }>).map((e) => ` ${k}: ${e.message ?? String(e)}`),
102
+ );
103
+ process.stderr.write(`Error: failed to resolve env vars:\n${msgs.join('\n')}\n`);
104
+ process.exit(1);
105
+ }
106
+
107
+ const resolvedEnv = graph.getResolvedEnvObject() as Record<string, string>;
108
+ const varCount = Object.keys(resolvedEnv).length;
109
+ process.stderr.write(`Loaded ${varCount} env vars from .env.schema (company: ${slug})\n`);
110
+
111
+ if (opts.check) {
112
+ process.exit(0);
113
+ }
114
+
115
+ const [childCmd, ...restArgs] = childArgs;
116
+ const child = spawn(childCmd, restArgs, {
117
+ stdio: 'inherit',
118
+ env: { ...process.env, ...resolvedEnv },
119
+ });
120
+
121
+ child.on('error', (err) => {
122
+ process.stderr.write(`Error: failed to start command '${childCmd}': ${err.message}\n`);
123
+ process.exit(1);
124
+ });
125
+
126
+ child.on('close', (code, signal) => {
127
+ if (signal) {
128
+ process.kill(process.pid, signal);
129
+ }
130
+ process.exit(code ?? 1);
131
+ });
132
+ } catch (err) {
133
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\n`);
134
+ process.exit(1);
135
+ }
136
+ });
137
+ }