@indigoai-us/hq-cli 5.8.6 → 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.
- package/CHANGELOG.md +30 -0
- package/dist/commands/run.d.ts +3 -0
- package/dist/commands/run.js +119 -0
- package/dist/commands/secrets.d.ts +3 -9
- package/dist/commands/secrets.js +5 -56
- package/dist/index.js +5 -2
- package/dist/run/discover-schemas.d.ts +12 -0
- package/dist/run/discover-schemas.js +64 -0
- package/dist/run/hq-plugin.d.ts +26 -0
- package/dist/run/hq-plugin.js +144 -0
- package/dist/utils/vault-api.d.ts +10 -0
- package/dist/utils/vault-api.js +58 -0
- package/package.json +7 -3
- package/src/commands/run.env-local.test.ts +84 -0
- package/src/commands/run.ts +137 -0
- package/src/commands/secrets.ts +4 -88
- package/src/index.ts +4 -0
- package/src/run/__fixtures__/discover-schemas/example.env.schema +4 -0
- package/src/run/discover-schemas.test.ts +153 -0
- package/src/run/discover-schemas.ts +79 -0
- package/src/run/hq-plugin.test.ts +125 -0
- package/src/run/hq-plugin.ts +174 -0
- package/src/run/varlock-shape.test.ts +57 -0
- package/src/utils/vault-api.ts +80 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import { internal } from 'varlock';
|
|
6
|
+
import {
|
|
7
|
+
installHqPlugin,
|
|
8
|
+
prewarmHqSecrets,
|
|
9
|
+
type InstallHqPluginOpts,
|
|
10
|
+
type PluginState,
|
|
11
|
+
} from './hq-plugin.js';
|
|
12
|
+
|
|
13
|
+
// Prevent any test run from writing to ~/.hq/secrets-cache/. Each test uses a
|
|
14
|
+
// unique uid (random suffix) so cross-test contamination in the in-memory store
|
|
15
|
+
// is not possible even without clearing between tests.
|
|
16
|
+
vi.mock('../utils/secrets-cache.js', () => {
|
|
17
|
+
const store = new Map<string, string>();
|
|
18
|
+
return {
|
|
19
|
+
readCache: (uid: string, name: string): string | null =>
|
|
20
|
+
store.get(`${uid}\0${name}`) ?? null,
|
|
21
|
+
writeCache: (uid: string, name: string, value: string): void => {
|
|
22
|
+
store.set(`${uid}\0${name}`, value);
|
|
23
|
+
},
|
|
24
|
+
removeCacheEntry: (): void => {},
|
|
25
|
+
clearAllCache: (): { removed: number } => ({ removed: 0 }),
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
let tmpDir: string;
|
|
30
|
+
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hq-plugin-test-'));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
afterEach(() => {
|
|
36
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
function makeMocks(overrides?: Partial<InstallHqPluginOpts>): InstallHqPluginOpts {
|
|
40
|
+
return {
|
|
41
|
+
resolveCompanyUid: async () => `test-uid-${Math.random().toString(36).slice(2)}`,
|
|
42
|
+
fetchBatch: async () => ({ secrets: [], errors: [] }),
|
|
43
|
+
...overrides,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
describe('hq-plugin', () => {
|
|
48
|
+
it('happy path: resolves hq() vars via batch fetch and cache', async () => {
|
|
49
|
+
const schemaPath = path.join(tmpDir, '.env.schema');
|
|
50
|
+
// Empty line after @hqCompany is required: varlock's env-spec parser only treats
|
|
51
|
+
// a decorator comment as a root (file-level) decorator when it is separated from the
|
|
52
|
+
// first var by a blank line. Without it, the decorator attaches to FOO as an item decorator.
|
|
53
|
+
fs.writeFileSync(schemaPath, `# @hqCompany("test")\n\nFOO=hq()\n`);
|
|
54
|
+
|
|
55
|
+
const uid = `test-uid-${Math.random().toString(36).slice(2)}`;
|
|
56
|
+
const mocks = makeMocks({
|
|
57
|
+
resolveCompanyUid: async () => uid,
|
|
58
|
+
fetchBatch: async (_uid, names) => ({
|
|
59
|
+
secrets: names.map((name) => ({ name, value: 'fixture-value' })),
|
|
60
|
+
errors: [],
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
let state!: PluginState;
|
|
65
|
+
const graph = await internal.loadEnvGraph({
|
|
66
|
+
entryFilePaths: [schemaPath],
|
|
67
|
+
afterInit: async (g) => {
|
|
68
|
+
state = installHqPlugin(g, mocks);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
await prewarmHqSecrets(graph, mocks, state);
|
|
72
|
+
await graph.resolveEnvValues();
|
|
73
|
+
expect(graph.getResolvedEnvObject().FOO).toBe('fixture-value');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('missing-company-error: throws when no @hqCompany and no companyOverride', async () => {
|
|
77
|
+
const schemaPath = path.join(tmpDir, '.env.schema');
|
|
78
|
+
// Schema has hq() resolver but no @hqCompany annotation and no opts.companyOverride
|
|
79
|
+
fs.writeFileSync(schemaPath, `FOO=hq()\n`);
|
|
80
|
+
|
|
81
|
+
const mocks = makeMocks();
|
|
82
|
+
|
|
83
|
+
let state!: PluginState;
|
|
84
|
+
const graph = await internal.loadEnvGraph({
|
|
85
|
+
entryFilePaths: [schemaPath],
|
|
86
|
+
afterInit: async (g) => {
|
|
87
|
+
state = installHqPlugin(g, mocks);
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
await expect(prewarmHqSecrets(graph, mocks, state)).rejects.toThrow(
|
|
91
|
+
'@hqCompany("...") not declared and --company not passed',
|
|
92
|
+
);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('batch-error-passthrough-403: forbidden error is surfaced as ResolutionError', async () => {
|
|
96
|
+
const schemaPath = path.join(tmpDir, '.env.schema');
|
|
97
|
+
// Empty line after @hqCompany is required: varlock's env-spec parser only treats
|
|
98
|
+
// a decorator comment as a root (file-level) decorator when it is separated from the
|
|
99
|
+
// first var by a blank line. Without it, the decorator attaches to FOO as an item decorator.
|
|
100
|
+
fs.writeFileSync(schemaPath, `# @hqCompany("test")\n\nFOO=hq()\n`);
|
|
101
|
+
|
|
102
|
+
const uid = `test-uid-${Math.random().toString(36).slice(2)}`;
|
|
103
|
+
const mocks = makeMocks({
|
|
104
|
+
resolveCompanyUid: async () => uid,
|
|
105
|
+
fetchBatch: async () => ({
|
|
106
|
+
secrets: [],
|
|
107
|
+
errors: [{ name: 'FOO', code: 'forbidden' }],
|
|
108
|
+
}),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
let state!: PluginState;
|
|
112
|
+
const graph = await internal.loadEnvGraph({
|
|
113
|
+
entryFilePaths: [schemaPath],
|
|
114
|
+
afterInit: async (g) => {
|
|
115
|
+
state = installHqPlugin(g, mocks);
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
await prewarmHqSecrets(graph, mocks, state);
|
|
119
|
+
await graph.resolveEnvValues();
|
|
120
|
+
// varlock collects ResolutionErrors on ConfigItem.errors (not re-thrown from resolveEnvValues).
|
|
121
|
+
// We verify the per-item error contains the forbidden diagnostic.
|
|
122
|
+
const fooErrors = (graph as any).configSchema['FOO'].errors as Array<{ message: string }>;
|
|
123
|
+
expect(fooErrors.some((e) => e.message.includes('No read permission for secret "FOO"'))).toBe(true);
|
|
124
|
+
});
|
|
125
|
+
});
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { ResolutionError } from 'varlock/plugin-lib';
|
|
2
|
+
import type { Resolver } from 'varlock/plugin-lib';
|
|
3
|
+
import { readCache, writeCache } from '../utils/secrets-cache.js';
|
|
4
|
+
|
|
5
|
+
export interface InstallHqPluginOpts {
|
|
6
|
+
companyOverride?: string;
|
|
7
|
+
resolveCompanyUid: (slug: string) => Promise<string>;
|
|
8
|
+
fetchBatch: (uid: string, names: string[]) => Promise<{
|
|
9
|
+
secrets: Array<{ name: string; value: string }>;
|
|
10
|
+
errors: Array<{ name: string; code: string; message?: string }>;
|
|
11
|
+
}>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface PluginState {
|
|
15
|
+
schemaCompanySlug: string | null;
|
|
16
|
+
uid: string | null;
|
|
17
|
+
errorsByName: Map<string, { code: string; message?: string }>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function installHqPlugin(graph: any /* EnvGraph */, opts: InstallHqPluginOpts) {
|
|
21
|
+
const pluginState: PluginState = {
|
|
22
|
+
schemaCompanySlug: null,
|
|
23
|
+
uid: null,
|
|
24
|
+
errorsByName: new Map(),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// varlock@1.0.0's plugin-lib.js omits the Resolver export (d.ts/JS mismatch);
|
|
28
|
+
// extract it at runtime from any already-registered built-in resolver's prototype.
|
|
29
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
30
|
+
let RuntimeResolver: any;
|
|
31
|
+
try {
|
|
32
|
+
const fns = graph.registeredResolverFunctions as Record<string, unknown>;
|
|
33
|
+
const first = Object.values(fns)[0];
|
|
34
|
+
if (first == null) throw new Error('registeredResolverFunctions is empty');
|
|
35
|
+
const proto = Object.getPrototypeOf(first) as { prototype?: { process?: unknown } } | null;
|
|
36
|
+
if (proto == null || typeof proto.prototype?.process !== 'function') {
|
|
37
|
+
throw new Error('prototype has no process method');
|
|
38
|
+
}
|
|
39
|
+
RuntimeResolver = proto;
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
'varlock Resolver base class extraction failed — the varlock@1.0.0 d.ts/JS mismatch ' +
|
|
43
|
+
'may have been resolved; switch to `import { Resolver } from "varlock/plugin-lib"`. ' +
|
|
44
|
+
`Underlying: ${e instanceof Error ? e.message : String(e)}`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// HqResolver is declared INSIDE installHqPlugin so its static def.resolve
|
|
49
|
+
// closes over `pluginState`. Module-scope declaration is forbidden — resolve()
|
|
50
|
+
// would hit `ReferenceError: pluginState is not defined`.
|
|
51
|
+
class HqResolver extends RuntimeResolver {
|
|
52
|
+
static def = {
|
|
53
|
+
name: 'hq',
|
|
54
|
+
impliesSensitive: true,
|
|
55
|
+
argsSchema: { type: 'array' as const, arrayMaxLength: 1 },
|
|
56
|
+
resolve: async function (this: HqResolver) {
|
|
57
|
+
// Cache-only read. `pluginState` is captured by this inner-class closure;
|
|
58
|
+
// `prewarmHqSecrets(graph, opts, state)` populates `state.uid` and
|
|
59
|
+
// `state.errorsByName` before `graph.resolveEnvValues()` calls us.
|
|
60
|
+
const explicit = this.arrArgs?.[0]?.staticValue;
|
|
61
|
+
const secretName = (typeof explicit === 'string' && explicit) ? explicit : this._ownerKey;
|
|
62
|
+
if (!secretName) {
|
|
63
|
+
throw new ResolutionError('hq() resolver could not determine secret name (missing owner key)');
|
|
64
|
+
}
|
|
65
|
+
const err = pluginState.errorsByName.get(secretName);
|
|
66
|
+
if (err) {
|
|
67
|
+
if (err.code === 'forbidden') {
|
|
68
|
+
throw new ResolutionError(`No read permission for secret "${secretName}" — ask an admin to share it via \`hq secrets share ${secretName} --with <you> --permission read\``);
|
|
69
|
+
}
|
|
70
|
+
if (err.code === 'not_found') {
|
|
71
|
+
throw new ResolutionError(`Secret "${secretName}" does not exist in company`);
|
|
72
|
+
}
|
|
73
|
+
throw new ResolutionError(`Failed to load secret "${secretName}": ${err.message ?? err.code}`);
|
|
74
|
+
}
|
|
75
|
+
// Sentinel-check style throughout: `readCache` returns `string | null`
|
|
76
|
+
// (verified at `hq/packages/hq-cli/src/utils/secrets-cache.ts:45`); `pluginState.uid`
|
|
77
|
+
// is `string | null` per `PluginState`. Use `== null` (covers null AND undefined defensively)
|
|
78
|
+
// for both — do not mix in truthy checks like `if (!x)`, which would silently swallow a
|
|
79
|
+
// legitimate empty-string value if the contract ever loosened.
|
|
80
|
+
if (pluginState.uid == null) {
|
|
81
|
+
throw new ResolutionError('Internal error: prewarmHqSecrets was not called before resolveEnvValues');
|
|
82
|
+
}
|
|
83
|
+
const cached = readCache(pluginState.uid, secretName); // string | null
|
|
84
|
+
if (cached == null) {
|
|
85
|
+
throw new ResolutionError(`Internal error: pre-warm did not populate cache for "${secretName}"`);
|
|
86
|
+
}
|
|
87
|
+
return cached;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// Captured during process(parent); used by resolve() to fall back to the var key.
|
|
92
|
+
private _ownerKey?: string;
|
|
93
|
+
|
|
94
|
+
process(parent?: Parameters<Resolver['process']>[0]) {
|
|
95
|
+
super.process(parent);
|
|
96
|
+
if (parent != null && typeof (parent as { key?: unknown }).key === 'string') {
|
|
97
|
+
this._ownerKey = (parent as { key: string }).key;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// varlock@1.0.0's env-spec parser rejects dots in decorator names ([a-zA-Z0-9_] only),
|
|
103
|
+
// so `@hq.company` is not valid syntax. We register as `@hqCompany` (camelCase) instead.
|
|
104
|
+
// Schema files must use `# @hqCompany("slug")` followed by a blank line so the parser
|
|
105
|
+
// treats it as a file-level root decorator rather than an item decorator for the next var.
|
|
106
|
+
graph.registerRootDecorator({
|
|
107
|
+
name: 'hqCompany',
|
|
108
|
+
isFunction: true,
|
|
109
|
+
process: (decoratorValue: any) => {
|
|
110
|
+
const slug = decoratorValue.arrArgs?.[0]?.staticValue;
|
|
111
|
+
return typeof slug === 'string' ? slug : null;
|
|
112
|
+
},
|
|
113
|
+
execute: (slug: string | null) => {
|
|
114
|
+
if (slug) pluginState.schemaCompanySlug = slug;
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
graph.registerResolver(HqResolver);
|
|
119
|
+
|
|
120
|
+
// Returned so `prewarmHqSecrets(graph, opts, state)` can read schemaCompanySlug
|
|
121
|
+
// and write `uid` + `errorsByName`. The state is held by the closure; the returned handle
|
|
122
|
+
// is purely for the prewarm helper.
|
|
123
|
+
return pluginState;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function prewarmHqSecrets(
|
|
127
|
+
graph: any /* EnvGraph */,
|
|
128
|
+
opts: InstallHqPluginOpts,
|
|
129
|
+
state: PluginState,
|
|
130
|
+
): Promise<void> {
|
|
131
|
+
const queue: Array<{ key: string; secretName: string }> = [];
|
|
132
|
+
for (const [key, item] of Object.entries(graph.configSchema)) {
|
|
133
|
+
const resolver = (item as any).valueResolver;
|
|
134
|
+
if (resolver?.def?.name === 'hq') {
|
|
135
|
+
const explicit = resolver.arrArgs?.[0]?.staticValue;
|
|
136
|
+
const secretName = (typeof explicit === 'string' && explicit) ? explicit : key;
|
|
137
|
+
queue.push({ key, secretName });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (queue.length === 0) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
let slug: string;
|
|
146
|
+
if (state.schemaCompanySlug) {
|
|
147
|
+
slug = state.schemaCompanySlug;
|
|
148
|
+
} else if (opts.companyOverride) {
|
|
149
|
+
slug = opts.companyOverride;
|
|
150
|
+
} else {
|
|
151
|
+
throw new Error('@hqCompany("...") not declared and --company not passed');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const uid = await opts.resolveCompanyUid(slug);
|
|
155
|
+
|
|
156
|
+
const uniqueNames = [...new Set(queue.map((q) => q.secretName))];
|
|
157
|
+
|
|
158
|
+
if (uniqueNames.length > 100) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`hq run supports at most 100 hq() resolvers per schema; got ${uniqueNames.length}`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const result = await opts.fetchBatch(uid, uniqueNames);
|
|
164
|
+
|
|
165
|
+
for (const s of result.secrets) {
|
|
166
|
+
writeCache(uid, s.name, s.value);
|
|
167
|
+
}
|
|
168
|
+
const errorsByName = new Map<string, { code: string; message?: string }>();
|
|
169
|
+
for (const e of result.errors) {
|
|
170
|
+
errorsByName.set(e.name, { code: e.code, message: e.message });
|
|
171
|
+
}
|
|
172
|
+
state.errorsByName = errorsByName;
|
|
173
|
+
state.uid = uid;
|
|
174
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { beforeAll, describe, expect, it } from 'vitest';
|
|
2
|
+
import { internal } from 'varlock';
|
|
3
|
+
// Resolver is a type-only export in varlock@1.0.0's plugin-lib.js (d.ts/JS mismatch);
|
|
4
|
+
// the value is extracted at runtime from graph.registeredResolverFunctions below.
|
|
5
|
+
import type { Resolver } from 'varlock/plugin-lib';
|
|
6
|
+
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
8
|
+
let RuntimeResolver: typeof Resolver;
|
|
9
|
+
|
|
10
|
+
beforeAll(async () => {
|
|
11
|
+
// Spin up a minimal graph to access built-in resolvers registered by varlock.
|
|
12
|
+
// No schema files are needed — varlock registers built-in resolvers in afterInit.
|
|
13
|
+
await internal.loadEnvGraph({
|
|
14
|
+
entryFilePaths: [],
|
|
15
|
+
afterInit: async (graph) => {
|
|
16
|
+
const fns = (graph as any).registeredResolverFunctions as Record<string, unknown>;
|
|
17
|
+
const firstClass = Object.values(fns)[0];
|
|
18
|
+
if (firstClass == null) throw new Error('registeredResolverFunctions is empty — varlock API shape changed');
|
|
19
|
+
// Each registered class extends Resolver; its prototype chain gives us the base class.
|
|
20
|
+
RuntimeResolver = Object.getPrototypeOf(firstClass) as typeof Resolver;
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe('varlock 1.0.0 API shape smoke test', () => {
|
|
26
|
+
it('internal.loadEnvGraph is a function', () => {
|
|
27
|
+
expect(typeof internal.loadEnvGraph).toBe('function');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('internal.EnvGraph is a function (class)', () => {
|
|
31
|
+
expect(typeof internal.EnvGraph).toBe('function');
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('EnvGraph.prototype.registerRootDecorator exists', () => {
|
|
35
|
+
expect(typeof internal.EnvGraph.prototype.registerRootDecorator).toBe('function');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('EnvGraph.prototype.registerResolver exists', () => {
|
|
39
|
+
expect(typeof internal.EnvGraph.prototype.registerResolver).toBe('function');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('EnvGraph.prototype.registerItemDecorator exists', () => {
|
|
43
|
+
expect(typeof internal.EnvGraph.prototype.registerItemDecorator).toBe('function');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('EnvGraph.prototype.registerDataType exists', () => {
|
|
47
|
+
expect(typeof internal.EnvGraph.prototype.registerDataType).toBe('function');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('Resolver.prototype.process exists', () => {
|
|
51
|
+
expect(typeof RuntimeResolver.prototype.process).toBe('function');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('Resolver.prototype.resolve exists', () => {
|
|
55
|
+
expect(typeof RuntimeResolver.prototype.resolve).toBe('function');
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { DEFAULT_VAULT_API_URL } from './cognito-session.js';
|
|
2
|
+
|
|
3
|
+
export interface VaultApiOptions {
|
|
4
|
+
token: string;
|
|
5
|
+
path: string;
|
|
6
|
+
method?: string;
|
|
7
|
+
body?: Record<string, unknown>;
|
|
8
|
+
query?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function vaultApiFetch(opts: VaultApiOptions): Promise<Response> {
|
|
12
|
+
const url = new URL(opts.path, DEFAULT_VAULT_API_URL);
|
|
13
|
+
if (opts.query) {
|
|
14
|
+
for (const [k, v] of Object.entries(opts.query)) {
|
|
15
|
+
url.searchParams.set(k, v);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return fetch(url.toString(), {
|
|
19
|
+
method: opts.method ?? 'GET',
|
|
20
|
+
headers: {
|
|
21
|
+
Authorization: `Bearer ${opts.token}`,
|
|
22
|
+
'Content-Type': 'application/json',
|
|
23
|
+
},
|
|
24
|
+
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface MembershipEntry {
|
|
29
|
+
companyUid: string;
|
|
30
|
+
role: string;
|
|
31
|
+
status: string;
|
|
32
|
+
membershipKey: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function resolveCompanyUid(token: string, slug: string): Promise<string> {
|
|
36
|
+
const res = await vaultApiFetch({
|
|
37
|
+
token,
|
|
38
|
+
path: `/entity/by-slug/company/${encodeURIComponent(slug)}`,
|
|
39
|
+
});
|
|
40
|
+
if (!res.ok) {
|
|
41
|
+
const body = await res.json().catch(() => ({}));
|
|
42
|
+
throw new Error(
|
|
43
|
+
`Failed to resolve company slug '${slug}': ${(body as Record<string, string>).error ?? res.statusText}`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
const data = (await res.json()) as { entity: { uid: string } };
|
|
47
|
+
return data.entity.uid;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function resolveCompanyFromMemberships(token: string): Promise<string> {
|
|
51
|
+
const res = await vaultApiFetch({
|
|
52
|
+
token,
|
|
53
|
+
path: '/membership/me',
|
|
54
|
+
});
|
|
55
|
+
if (!res.ok) {
|
|
56
|
+
throw new Error("Failed to fetch memberships — run `hq login` and try again");
|
|
57
|
+
}
|
|
58
|
+
const data = (await res.json()) as { memberships: MembershipEntry[] };
|
|
59
|
+
const active = data.memberships.filter((m) => m.status === 'active');
|
|
60
|
+
if (active.length === 0) {
|
|
61
|
+
throw new Error('No active company memberships found. Use --company <slug> to specify.');
|
|
62
|
+
}
|
|
63
|
+
if (active.length === 1) {
|
|
64
|
+
return active[0].companyUid;
|
|
65
|
+
}
|
|
66
|
+
const uids = active.map((m) => m.companyUid).join(', ');
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Multiple companies found (${uids}). Use --company <slug> to specify which one.`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function getCompanyUid(
|
|
73
|
+
token: string,
|
|
74
|
+
companySlug: string | undefined,
|
|
75
|
+
): Promise<string> {
|
|
76
|
+
if (companySlug) {
|
|
77
|
+
return resolveCompanyUid(token, companySlug);
|
|
78
|
+
}
|
|
79
|
+
return resolveCompanyFromMemberships(token);
|
|
80
|
+
}
|