@indigoai-us/hq-cli 5.8.6 → 5.10.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 +44 -0
- package/dist/commands/cloud-demote.d.ts +90 -0
- package/dist/commands/cloud-demote.js +193 -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 +7 -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/cloud-demote.test.ts +401 -0
- package/src/commands/cloud-demote.ts +277 -0
- 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 +6 -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
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [5.10.0] — 2026-05-04
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **`hq cloud demote company <slug>` subcommand** — inverse of
|
|
8
|
+
`hq cloud provision company`. Converts a cloud-backed company back to local-only
|
|
9
|
+
after its entity has been soft-tombstoned in hq-console (Settings → Delete company).
|
|
10
|
+
Removes `companies/<slug>/.hq/config.json`, flips `cloud: true → false` in
|
|
11
|
+
`companies/<slug>/company.yaml`, and strips `cloud_uid` + `bucket_name` from
|
|
12
|
+
`companies/manifest.yaml`. Default safety check verifies the cloud entity is
|
|
13
|
+
`deleted=true`; `--force` skips the check (used by AppBar HQ Sync's Path A after
|
|
14
|
+
it has already verified). All side-effects atomic + idempotent. Exit codes mirror
|
|
15
|
+
`cloud provision` (0 ok, 1 vault HTTP, 2 validation).
|
|
16
|
+
|
|
17
|
+
## [5.9.0] — 2026-05-04
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- **`hq run` command** — schema-driven dev workflow. Place a `.env.schema` file in
|
|
22
|
+
your repo (annotated with `# @hqCompany("your-slug")` and `VARNAME=hq()` resolvers),
|
|
23
|
+
then run `hq run -- npm run dev` to inject all declared secrets into the child
|
|
24
|
+
process's environment without ever printing them to stdout/stderr. Discovers schemas
|
|
25
|
+
by walking up from cwd to the repo root; merges multiple schemas; respects sibling
|
|
26
|
+
`.env.local` files for local overrides. Supports `--check` for a dry-run summary,
|
|
27
|
+
`--company` to override the slug, and `--schema` to pin an explicit schema path.
|
|
28
|
+
|
|
29
|
+
- **Batch secrets endpoint** — `POST /secrets/{companyUid}/load` on the vault API
|
|
30
|
+
reduces N parallel single-secret fetches to chunked `ssm:GetParameters` calls
|
|
31
|
+
(up to 10 names per batch), cutting `hq run` latency for schemas with many vars.
|
|
32
|
+
Responses include both `secrets` (allowed) and `errors` (denied/not-found) per name.
|
|
33
|
+
Each revealed secret is audit-logged individually (same trail as `hq secrets get`).
|
|
34
|
+
|
|
35
|
+
- **`varlock` dependency** (`1.0.0`, exact pin) — used as an internal library to
|
|
36
|
+
parse `.env.schema` files and drive the resolver graph. The `hq()` resolver is
|
|
37
|
+
implemented as a varlock plugin registered at runtime; varlock is not exposed as a
|
|
38
|
+
public API surface.
|
|
39
|
+
|
|
40
|
+
### Changed
|
|
41
|
+
|
|
42
|
+
- **Node minimum raised to `>=22.0.0`** — required by `varlock@1.0.0` (ESM-only,
|
|
43
|
+
`node>=22`). The previous minimum was unset; this makes the requirement explicit
|
|
44
|
+
in `engines.node`.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq cloud demote company <slug>` — convert a cloud-backed company back to
|
|
3
|
+
* local-only after hq-pro has soft-tombstoned its entity (Settings → Delete
|
|
4
|
+
* company in hq-console).
|
|
5
|
+
*
|
|
6
|
+
* Inverse of `hq cloud provision company <slug>`. Both commands live here in
|
|
7
|
+
* hq-cli so the file-touching contract (manifest patch + per-folder config
|
|
8
|
+
* write + company.yaml mutation) is single-sourced. AppBar HQ Sync's Path A
|
|
9
|
+
* shells out to this command on the `deleted=true` branch instead of
|
|
10
|
+
* re-implementing the file mutations in Rust.
|
|
11
|
+
*
|
|
12
|
+
* Side-effects (all atomic + idempotent):
|
|
13
|
+
* 1. Remove `companies/<slug>/.hq/config.json`.
|
|
14
|
+
* 2. Flip `cloud: true → false` in `companies/<slug>/company.yaml`. Without
|
|
15
|
+
* this flip the next `provisionCompany` would re-mint a fresh cloud
|
|
16
|
+
* company — exactly what the user just deleted.
|
|
17
|
+
* 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
|
|
18
|
+
* `companies.<slug>` entry. The slug entry + other fields stay.
|
|
19
|
+
*
|
|
20
|
+
* Safety check (default on): `findCompanyBySlug` MUST return an entity with
|
|
21
|
+
* `deleted: true`. A live entity, or no entity at all, refuses with code 2.
|
|
22
|
+
* `--force` skips the network call (AppBar passes it because Path A just
|
|
23
|
+
* checked).
|
|
24
|
+
*
|
|
25
|
+
* Exit codes (mirrors cloud-provision):
|
|
26
|
+
* 0 — success or idempotent no-op.
|
|
27
|
+
* 1 — vault HTTP failure during the safety check.
|
|
28
|
+
* 2 — validation (bad slug, missing dir/manifest, cloud not deleted).
|
|
29
|
+
*/
|
|
30
|
+
import { Command } from "commander";
|
|
31
|
+
import { type VaultClient } from "./cloud-provision.js";
|
|
32
|
+
/** Final stdout JSON shape. AppBar parses this. */
|
|
33
|
+
export interface DemoteResult {
|
|
34
|
+
ok: boolean;
|
|
35
|
+
company_slug: string;
|
|
36
|
+
/** True if `.hq/config.json` was actually deleted (false if absent). */
|
|
37
|
+
config_removed: boolean;
|
|
38
|
+
/** True if `company.yaml`'s `cloud` was changed (true→false or absent→false). */
|
|
39
|
+
yaml_flipped: boolean;
|
|
40
|
+
/** True if manifest had `cloud_uid` / `bucket_name` to strip. */
|
|
41
|
+
manifest_stripped: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* `true` when the cloud entity verified as `deleted=true`. `null` when
|
|
44
|
+
* `--force` was used and the verify was skipped. (`false` is unreachable —
|
|
45
|
+
* a non-deleted entity throws code 2 before reaching the result.)
|
|
46
|
+
*/
|
|
47
|
+
cloud_was_deleted: boolean | null;
|
|
48
|
+
}
|
|
49
|
+
export interface DemoteCompanyOptions {
|
|
50
|
+
slug: string;
|
|
51
|
+
hqRoot: string;
|
|
52
|
+
vaultApiUrl: string;
|
|
53
|
+
/** Skip the `findCompanyBySlug` safety check. AppBar uses this. */
|
|
54
|
+
force?: boolean;
|
|
55
|
+
/** Injected vault HTTP client (override for tests). */
|
|
56
|
+
vaultClient?: VaultClient;
|
|
57
|
+
/** Injected access-token resolver (override for tests). */
|
|
58
|
+
resolveAccessToken?: () => Promise<string>;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Flip `cloud: true → false` in `companies/<slug>/company.yaml`. All other
|
|
62
|
+
* keys + ordering preserved (js-yaml round-trip). Atomic (tmp + rename).
|
|
63
|
+
*
|
|
64
|
+
* Returns true if the file was changed, false if no-op (file missing, or
|
|
65
|
+
* `cloud` was already `false`).
|
|
66
|
+
*
|
|
67
|
+
* NOTE: js-yaml doesn't preserve comments, but this matches what
|
|
68
|
+
* `patchManifest` already does — accepted trade-off.
|
|
69
|
+
*/
|
|
70
|
+
export declare function flipCompanyYamlCloudOff(hqRoot: string, slug: string): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Remove `cloud_uid` + `bucket_name` from `companies.<slug>` in
|
|
73
|
+
* `companies/manifest.yaml`. The slug entry is preserved (other fields like
|
|
74
|
+
* `name`/`status`/`path` stay). Atomic (tmp + rename).
|
|
75
|
+
*
|
|
76
|
+
* Returns true if the file was changed, false if no-op (manifest missing,
|
|
77
|
+
* slug missing, or both fields already absent).
|
|
78
|
+
*/
|
|
79
|
+
export declare function stripManifestCloudForSlug(hqRoot: string, slug: string): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Run the full demote flow. Returns a `DemoteResult` on success; throws
|
|
82
|
+
* `ProvisionError` (codes 1 or 2) on any failure.
|
|
83
|
+
*/
|
|
84
|
+
export declare function demoteCompany(options: DemoteCompanyOptions): Promise<DemoteResult>;
|
|
85
|
+
/**
|
|
86
|
+
* Register `demote company <slug>` under the `cloud` command group. Wired in
|
|
87
|
+
* `src/index.ts` alongside `registerCloudProvisionCommands(cloudCmd)`.
|
|
88
|
+
*/
|
|
89
|
+
export declare function registerCloudDemoteCommands(program: Command): void;
|
|
90
|
+
//# sourceMappingURL=cloud-demote.d.ts.map
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `hq cloud demote company <slug>` — convert a cloud-backed company back to
|
|
3
|
+
* local-only after hq-pro has soft-tombstoned its entity (Settings → Delete
|
|
4
|
+
* company in hq-console).
|
|
5
|
+
*
|
|
6
|
+
* Inverse of `hq cloud provision company <slug>`. Both commands live here in
|
|
7
|
+
* hq-cli so the file-touching contract (manifest patch + per-folder config
|
|
8
|
+
* write + company.yaml mutation) is single-sourced. AppBar HQ Sync's Path A
|
|
9
|
+
* shells out to this command on the `deleted=true` branch instead of
|
|
10
|
+
* re-implementing the file mutations in Rust.
|
|
11
|
+
*
|
|
12
|
+
* Side-effects (all atomic + idempotent):
|
|
13
|
+
* 1. Remove `companies/<slug>/.hq/config.json`.
|
|
14
|
+
* 2. Flip `cloud: true → false` in `companies/<slug>/company.yaml`. Without
|
|
15
|
+
* this flip the next `provisionCompany` would re-mint a fresh cloud
|
|
16
|
+
* company — exactly what the user just deleted.
|
|
17
|
+
* 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
|
|
18
|
+
* `companies.<slug>` entry. The slug entry + other fields stay.
|
|
19
|
+
*
|
|
20
|
+
* Safety check (default on): `findCompanyBySlug` MUST return an entity with
|
|
21
|
+
* `deleted: true`. A live entity, or no entity at all, refuses with code 2.
|
|
22
|
+
* `--force` skips the network call (AppBar passes it because Path A just
|
|
23
|
+
* checked).
|
|
24
|
+
*
|
|
25
|
+
* Exit codes (mirrors cloud-provision):
|
|
26
|
+
* 0 — success or idempotent no-op.
|
|
27
|
+
* 1 — vault HTTP failure during the safety check.
|
|
28
|
+
* 2 — validation (bad slug, missing dir/manifest, cloud not deleted).
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
!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]="6b5cd717-bba0-5dd4-a743-a070e8a62a6b")}catch(e){}}();
|
|
32
|
+
import * as fs from "node:fs";
|
|
33
|
+
import * as path from "node:path";
|
|
34
|
+
import * as yaml from "js-yaml";
|
|
35
|
+
import chalk from "chalk";
|
|
36
|
+
import { ProvisionError, companyConfigPath, companyDirPath, createDefaultVaultClient, manifestPath, validateManifestAndDir, validateSlug, } from "./cloud-provision.js";
|
|
37
|
+
import { DEFAULT_HQ_ROOT, DEFAULT_VAULT_API_URL, ensureCognitoToken, } from "../utils/cognito-session.js";
|
|
38
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
39
|
+
/**
|
|
40
|
+
* Flip `cloud: true → false` in `companies/<slug>/company.yaml`. All other
|
|
41
|
+
* keys + ordering preserved (js-yaml round-trip). Atomic (tmp + rename).
|
|
42
|
+
*
|
|
43
|
+
* Returns true if the file was changed, false if no-op (file missing, or
|
|
44
|
+
* `cloud` was already `false`).
|
|
45
|
+
*
|
|
46
|
+
* NOTE: js-yaml doesn't preserve comments, but this matches what
|
|
47
|
+
* `patchManifest` already does — accepted trade-off.
|
|
48
|
+
*/
|
|
49
|
+
export function flipCompanyYamlCloudOff(hqRoot, slug) {
|
|
50
|
+
const yPath = path.join(companyDirPath(hqRoot, slug), "company.yaml");
|
|
51
|
+
if (!fs.existsSync(yPath))
|
|
52
|
+
return false;
|
|
53
|
+
const raw = fs.readFileSync(yPath, "utf-8");
|
|
54
|
+
const parsed = yaml.load(raw) ?? {};
|
|
55
|
+
if (parsed.cloud === false)
|
|
56
|
+
return false;
|
|
57
|
+
parsed.cloud = false;
|
|
58
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
59
|
+
const tmp = `${yPath}.tmp.${process.pid}`;
|
|
60
|
+
fs.writeFileSync(tmp, dump);
|
|
61
|
+
fs.renameSync(tmp, yPath);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Remove `cloud_uid` + `bucket_name` from `companies.<slug>` in
|
|
66
|
+
* `companies/manifest.yaml`. The slug entry is preserved (other fields like
|
|
67
|
+
* `name`/`status`/`path` stay). Atomic (tmp + rename).
|
|
68
|
+
*
|
|
69
|
+
* Returns true if the file was changed, false if no-op (manifest missing,
|
|
70
|
+
* slug missing, or both fields already absent).
|
|
71
|
+
*/
|
|
72
|
+
export function stripManifestCloudForSlug(hqRoot, slug) {
|
|
73
|
+
const mPath = manifestPath(hqRoot);
|
|
74
|
+
if (!fs.existsSync(mPath))
|
|
75
|
+
return false;
|
|
76
|
+
const raw = fs.readFileSync(mPath, "utf-8");
|
|
77
|
+
const parsed = yaml.load(raw) ?? {};
|
|
78
|
+
const companies = parsed.companies;
|
|
79
|
+
if (!companies || !(slug in companies))
|
|
80
|
+
return false;
|
|
81
|
+
const entry = companies[slug];
|
|
82
|
+
if (!entry || typeof entry !== "object")
|
|
83
|
+
return false;
|
|
84
|
+
const obj = entry;
|
|
85
|
+
const hadCloudUid = "cloud_uid" in obj;
|
|
86
|
+
const hadBucketName = "bucket_name" in obj;
|
|
87
|
+
if (!hadCloudUid && !hadBucketName)
|
|
88
|
+
return false;
|
|
89
|
+
delete obj.cloud_uid;
|
|
90
|
+
delete obj.bucket_name;
|
|
91
|
+
const dump = yaml.dump(parsed, { lineWidth: -1, noRefs: true });
|
|
92
|
+
const tmp = `${mPath}.tmp.${process.pid}`;
|
|
93
|
+
fs.writeFileSync(tmp, dump);
|
|
94
|
+
fs.renameSync(tmp, mPath);
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
// ── Orchestrator ─────────────────────────────────────────────────────────────
|
|
98
|
+
/**
|
|
99
|
+
* Run the full demote flow. Returns a `DemoteResult` on success; throws
|
|
100
|
+
* `ProvisionError` (codes 1 or 2) on any failure.
|
|
101
|
+
*/
|
|
102
|
+
export async function demoteCompany(options) {
|
|
103
|
+
validateSlug(options.slug);
|
|
104
|
+
// Fails with code 2 if the manifest is missing/malformed, the slug is not
|
|
105
|
+
// present under `.companies`, or `companies/<slug>/` doesn't exist on disk.
|
|
106
|
+
// Without this, a `--force` demote against a missing or renamed slug would
|
|
107
|
+
// be a silent no-op (all helpers return false but we'd still report ok=true).
|
|
108
|
+
validateManifestAndDir(options.hqRoot, options.slug);
|
|
109
|
+
let cloudWasDeleted = null;
|
|
110
|
+
if (!options.force) {
|
|
111
|
+
const accessToken = options.resolveAccessToken
|
|
112
|
+
? await options.resolveAccessToken()
|
|
113
|
+
: await ensureCognitoToken();
|
|
114
|
+
const client = options.vaultClient ??
|
|
115
|
+
createDefaultVaultClient(options.vaultApiUrl, accessToken);
|
|
116
|
+
let entity;
|
|
117
|
+
try {
|
|
118
|
+
entity = await client.findCompanyBySlug(options.slug);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
if (err instanceof ProvisionError)
|
|
122
|
+
throw err;
|
|
123
|
+
throw new ProvisionError(1, `Vault GET by-slug failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
124
|
+
}
|
|
125
|
+
if (!entity) {
|
|
126
|
+
throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found. Pass --force to demote anyway.`);
|
|
127
|
+
}
|
|
128
|
+
// `deleted` is added by hq-pro and isn't in the static VaultEntity type.
|
|
129
|
+
const deleted = entity.deleted === true;
|
|
130
|
+
if (!deleted) {
|
|
131
|
+
throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
|
|
132
|
+
}
|
|
133
|
+
cloudWasDeleted = true;
|
|
134
|
+
}
|
|
135
|
+
const cPath = companyConfigPath(options.hqRoot, options.slug);
|
|
136
|
+
let configRemoved = false;
|
|
137
|
+
if (fs.existsSync(cPath)) {
|
|
138
|
+
fs.rmSync(cPath);
|
|
139
|
+
configRemoved = true;
|
|
140
|
+
}
|
|
141
|
+
const yamlFlipped = flipCompanyYamlCloudOff(options.hqRoot, options.slug);
|
|
142
|
+
const manifestStripped = stripManifestCloudForSlug(options.hqRoot, options.slug);
|
|
143
|
+
return {
|
|
144
|
+
ok: true,
|
|
145
|
+
company_slug: options.slug,
|
|
146
|
+
config_removed: configRemoved,
|
|
147
|
+
yaml_flipped: yamlFlipped,
|
|
148
|
+
manifest_stripped: manifestStripped,
|
|
149
|
+
cloud_was_deleted: cloudWasDeleted,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
// ── Commander wiring ─────────────────────────────────────────────────────────
|
|
153
|
+
/**
|
|
154
|
+
* Register `demote company <slug>` under the `cloud` command group. Wired in
|
|
155
|
+
* `src/index.ts` alongside `registerCloudProvisionCommands(cloudCmd)`.
|
|
156
|
+
*/
|
|
157
|
+
export function registerCloudDemoteCommands(program) {
|
|
158
|
+
const demoteCmd = program
|
|
159
|
+
.command("demote")
|
|
160
|
+
.description("Demote a cloud-backed entity back to local-only");
|
|
161
|
+
demoteCmd
|
|
162
|
+
.command("company")
|
|
163
|
+
.description("Demote a cloud-backed company to local-only after the cloud entity " +
|
|
164
|
+
"has been soft-tombstoned in hq-console. Removes .hq/config.json, " +
|
|
165
|
+
"flips company.yaml `cloud: false`, and strips the manifest cloud refs.")
|
|
166
|
+
.argument("<slug>", "Company slug")
|
|
167
|
+
.option("--hq-root <path>", `Local HQ tree root (default: ${DEFAULT_HQ_ROOT})`, DEFAULT_HQ_ROOT)
|
|
168
|
+
.option("--vault-api-url <url>", `Vault API URL (default: ${DEFAULT_VAULT_API_URL})`, DEFAULT_VAULT_API_URL)
|
|
169
|
+
.option("--force", "Skip the safety check that the cloud entity is actually deleted=true. " +
|
|
170
|
+
"AppBar HQ Sync passes this because its Path A just verified.")
|
|
171
|
+
.action(async (slug, options) => {
|
|
172
|
+
try {
|
|
173
|
+
const result = await demoteCompany({
|
|
174
|
+
slug,
|
|
175
|
+
hqRoot: options.hqRoot,
|
|
176
|
+
vaultApiUrl: options.vaultApiUrl,
|
|
177
|
+
force: options.force,
|
|
178
|
+
});
|
|
179
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
180
|
+
process.exit(0);
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
if (err instanceof ProvisionError) {
|
|
184
|
+
process.stderr.write(chalk.red(`[hq cloud demote] ${err.message}\n`));
|
|
185
|
+
process.exit(err.code);
|
|
186
|
+
}
|
|
187
|
+
process.stderr.write(chalk.red(`[hq cloud demote] Unexpected error: ${err instanceof Error ? err.message : String(err)}\n`));
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=cloud-demote.js.map
|
|
193
|
+
//# debugId=6b5cd717-bba0-5dd4-a743-a070e8a62a6b
|
|
@@ -0,0 +1,119 @@
|
|
|
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]="a1b39bbf-1f26-59e7-af70-6ecf01f2ce7e")}catch(e){}}();
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import * as fs from 'node:fs';
|
|
6
|
+
import { internal } from 'varlock';
|
|
7
|
+
import { ensureCognitoToken } from '../utils/cognito-session.js';
|
|
8
|
+
import { vaultApiFetch, getCompanyUid } from '../utils/vault-api.js';
|
|
9
|
+
import { discoverSchemas } from '../run/discover-schemas.js';
|
|
10
|
+
import { installHqPlugin, prewarmHqSecrets } from '../run/hq-plugin.js';
|
|
11
|
+
export function registerRunCommand(program) {
|
|
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) => {
|
|
20
|
+
try {
|
|
21
|
+
const dashIndex = process.argv.indexOf('--');
|
|
22
|
+
const childArgs = dashIndex !== -1 ? process.argv.slice(dashIndex + 1) : [];
|
|
23
|
+
if (!opts.check && childArgs.length === 0) {
|
|
24
|
+
throw new Error('no command specified. Usage: hq run [options] -- <command> [args...]');
|
|
25
|
+
}
|
|
26
|
+
let schemaPaths;
|
|
27
|
+
let envLocalPaths;
|
|
28
|
+
let schemaCompanySlug;
|
|
29
|
+
if (opts.schema) {
|
|
30
|
+
const schemaAbs = path.resolve(opts.schema);
|
|
31
|
+
schemaPaths = [schemaAbs];
|
|
32
|
+
const localPath = path.join(path.dirname(schemaAbs), '.env.local');
|
|
33
|
+
envLocalPaths = fs.existsSync(localPath) ? [localPath] : [];
|
|
34
|
+
const content = fs.readFileSync(schemaAbs, 'utf8');
|
|
35
|
+
const m = /^# @hqCompany\("([^"]+)"\)/m.exec(content);
|
|
36
|
+
schemaCompanySlug = m ? m[1] : null;
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
const discovered = discoverSchemas(process.cwd());
|
|
40
|
+
if (discovered.conflict) {
|
|
41
|
+
throw new Error(`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.`);
|
|
42
|
+
}
|
|
43
|
+
if (discovered.schemaPaths.length === 0) {
|
|
44
|
+
throw new Error('no .env.schema found. Create one or use --schema <path>.');
|
|
45
|
+
}
|
|
46
|
+
schemaPaths = discovered.schemaPaths;
|
|
47
|
+
envLocalPaths = discovered.envLocalPaths;
|
|
48
|
+
schemaCompanySlug = discovered.companySlug;
|
|
49
|
+
}
|
|
50
|
+
const slug = opts.company ?? schemaCompanySlug;
|
|
51
|
+
if (!slug) {
|
|
52
|
+
throw new Error('company slug not set. Add # @hqCompany("slug") to your .env.schema or pass --company <slug>.');
|
|
53
|
+
}
|
|
54
|
+
const token = await ensureCognitoToken();
|
|
55
|
+
const uid = await getCompanyUid(token, slug);
|
|
56
|
+
const fetchBatch = async (companyUid, names) => {
|
|
57
|
+
const res = await vaultApiFetch({
|
|
58
|
+
token,
|
|
59
|
+
path: `/secrets/${encodeURIComponent(companyUid)}/load`,
|
|
60
|
+
method: 'POST',
|
|
61
|
+
body: { names },
|
|
62
|
+
});
|
|
63
|
+
if (!res.ok) {
|
|
64
|
+
const body = await res.json().catch(() => ({}));
|
|
65
|
+
throw new Error(`Failed to batch-load secrets: ${body.error ?? res.statusText}`);
|
|
66
|
+
}
|
|
67
|
+
return res.json();
|
|
68
|
+
};
|
|
69
|
+
const pluginOpts = {
|
|
70
|
+
companyOverride: opts.company,
|
|
71
|
+
resolveCompanyUid: async () => uid,
|
|
72
|
+
fetchBatch,
|
|
73
|
+
};
|
|
74
|
+
// LAST entry = highest precedence; .env.local files trail .env.schema files so any .env.local beats any schema regardless of depth.
|
|
75
|
+
const paths = [...schemaPaths, ...envLocalPaths];
|
|
76
|
+
let state;
|
|
77
|
+
const graph = await internal.loadEnvGraph({
|
|
78
|
+
entryFilePaths: paths,
|
|
79
|
+
afterInit: async (g) => { state = installHqPlugin(g, pluginOpts); },
|
|
80
|
+
});
|
|
81
|
+
await prewarmHqSecrets(graph, pluginOpts, state);
|
|
82
|
+
await graph.resolveEnvValues();
|
|
83
|
+
const schemaErrors = Object.entries(graph.configSchema)
|
|
84
|
+
.filter(([, item]) => item.errors?.length > 0);
|
|
85
|
+
if (schemaErrors.length > 0) {
|
|
86
|
+
const msgs = schemaErrors.flatMap(([k, item]) => item.errors.map((e) => ` ${k}: ${e.message ?? String(e)}`));
|
|
87
|
+
process.stderr.write(`Error: failed to resolve env vars:\n${msgs.join('\n')}\n`);
|
|
88
|
+
process.exit(1);
|
|
89
|
+
}
|
|
90
|
+
const resolvedEnv = graph.getResolvedEnvObject();
|
|
91
|
+
const varCount = Object.keys(resolvedEnv).length;
|
|
92
|
+
process.stderr.write(`Loaded ${varCount} env vars from .env.schema (company: ${slug})\n`);
|
|
93
|
+
if (opts.check) {
|
|
94
|
+
process.exit(0);
|
|
95
|
+
}
|
|
96
|
+
const [childCmd, ...restArgs] = childArgs;
|
|
97
|
+
const child = spawn(childCmd, restArgs, {
|
|
98
|
+
stdio: 'inherit',
|
|
99
|
+
env: { ...process.env, ...resolvedEnv },
|
|
100
|
+
});
|
|
101
|
+
child.on('error', (err) => {
|
|
102
|
+
process.stderr.write(`Error: failed to start command '${childCmd}': ${err.message}\n`);
|
|
103
|
+
process.exit(1);
|
|
104
|
+
});
|
|
105
|
+
child.on('close', (code, signal) => {
|
|
106
|
+
if (signal) {
|
|
107
|
+
process.kill(process.pid, signal);
|
|
108
|
+
}
|
|
109
|
+
process.exit(code ?? 1);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=run.js.map
|
|
119
|
+
//# debugId=a1b39bbf-1f26-59e7-af70-6ecf01f2ce7e
|
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
method?: string;
|
|
6
|
-
body?: Record<string, unknown>;
|
|
7
|
-
query?: Record<string, string>;
|
|
8
|
-
}
|
|
9
|
-
export declare function vaultApiFetch(opts: VaultApiOptions): Promise<Response>;
|
|
10
|
-
export declare function getCompanyUid(token: string, companySlug: string | undefined): Promise<string>;
|
|
2
|
+
import { vaultApiFetch, getCompanyUid } from "../utils/vault-api.js";
|
|
3
|
+
export type { VaultApiOptions } from "../utils/vault-api.js";
|
|
4
|
+
export { vaultApiFetch, getCompanyUid };
|
|
11
5
|
export declare function registerSecretsCommand(program: Command): void;
|
|
12
6
|
//# sourceMappingURL=secrets.d.ts.map
|
package/dist/commands/secrets.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
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]="
|
|
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]="0239c476-98b8-53c0-9458-1c82dc0d26a9")}catch(e){}}();
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import * as readline from "node:readline";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
6
|
-
import { ensureCognitoToken
|
|
6
|
+
import { ensureCognitoToken } from "../utils/cognito-session.js";
|
|
7
7
|
import { readCache, writeCache, removeCacheEntry, clearAllCache, } from "../utils/secrets-cache.js";
|
|
8
8
|
import { SECRET_NAME_PATTERN, GROUP_ID_PATTERN } from "./_patterns.js";
|
|
9
|
+
import { vaultApiFetch, getCompanyUid } from "../utils/vault-api.js";
|
|
10
|
+
export { vaultApiFetch, getCompanyUid };
|
|
9
11
|
function shellSingleQuote(value) {
|
|
10
12
|
return "'" + value.replace(/'/g, "'\\''") + "'";
|
|
11
13
|
}
|
|
@@ -19,59 +21,6 @@ function buildSecretNamePath(companyUid, name) {
|
|
|
19
21
|
.join("/");
|
|
20
22
|
return `/secrets/${encodeURIComponent(companyUid)}/name/${encodedName}`;
|
|
21
23
|
}
|
|
22
|
-
export async function vaultApiFetch(opts) {
|
|
23
|
-
const url = new URL(opts.path, DEFAULT_VAULT_API_URL);
|
|
24
|
-
if (opts.query) {
|
|
25
|
-
for (const [k, v] of Object.entries(opts.query)) {
|
|
26
|
-
url.searchParams.set(k, v);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
return fetch(url.toString(), {
|
|
30
|
-
method: opts.method ?? "GET",
|
|
31
|
-
headers: {
|
|
32
|
-
Authorization: `Bearer ${opts.token}`,
|
|
33
|
-
"Content-Type": "application/json",
|
|
34
|
-
},
|
|
35
|
-
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
async function resolveCompanyUid(token, slug) {
|
|
39
|
-
const res = await vaultApiFetch({
|
|
40
|
-
token,
|
|
41
|
-
path: `/entity/by-slug/company/${encodeURIComponent(slug)}`,
|
|
42
|
-
});
|
|
43
|
-
if (!res.ok) {
|
|
44
|
-
const body = await res.json().catch(() => ({}));
|
|
45
|
-
throw new Error(`Failed to resolve company slug '${slug}': ${body.error ?? res.statusText}`);
|
|
46
|
-
}
|
|
47
|
-
const data = (await res.json());
|
|
48
|
-
return data.entity.uid;
|
|
49
|
-
}
|
|
50
|
-
async function resolveCompanyFromMemberships(token) {
|
|
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());
|
|
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(`Multiple companies found (${uids}). Use --company <slug> to specify which one.`);
|
|
68
|
-
}
|
|
69
|
-
export async function getCompanyUid(token, companySlug) {
|
|
70
|
-
if (companySlug) {
|
|
71
|
-
return resolveCompanyUid(token, companySlug);
|
|
72
|
-
}
|
|
73
|
-
return resolveCompanyFromMemberships(token);
|
|
74
|
-
}
|
|
75
24
|
function parseDuration(input) {
|
|
76
25
|
const match = input.match(/^(\d+)(m|h|d)$/);
|
|
77
26
|
if (!match)
|
|
@@ -756,4 +705,4 @@ export function registerSecretsCommand(program) {
|
|
|
756
705
|
});
|
|
757
706
|
}
|
|
758
707
|
//# sourceMappingURL=secrets.js.map
|
|
759
|
-
//# debugId=
|
|
708
|
+
//# debugId=0239c476-98b8-53c0-9458-1c82dc0d26a9
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* HQ CLI - Module management, package management, and cloud sync for HQ
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
!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]="
|
|
6
|
+
!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]="ebc3116c-f836-550a-b5bb-4a74bce24abc")}catch(e){}}();
|
|
7
7
|
import { Command } from "commander";
|
|
8
8
|
import { initSentry, Sentry } from "./sentry.js";
|
|
9
9
|
import { registerAddCommand } from "./commands/add.js";
|
|
@@ -12,6 +12,7 @@ import { registerListCommand } from "./commands/list.js";
|
|
|
12
12
|
import { registerUpdateCommand } from "./commands/update.js";
|
|
13
13
|
import { registerCloudCommands } from "./commands/cloud.js";
|
|
14
14
|
import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
|
|
15
|
+
import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
|
|
15
16
|
import { registerLoginCommand } from "./commands/login.js";
|
|
16
17
|
import { registerLogoutCommand } from "./commands/logout.js";
|
|
17
18
|
import { registerWhoamiCommand } from "./commands/whoami.js";
|
|
@@ -23,6 +24,7 @@ import { registerPackageListCommand } from "./commands/pkg-list.js";
|
|
|
23
24
|
import { registerTeamSyncCommand } from "./commands/team-sync.js";
|
|
24
25
|
import { registerAuthCommands } from "./commands/auth.js";
|
|
25
26
|
import { registerSecretsCommand } from "./commands/secrets.js";
|
|
27
|
+
import { registerRunCommand } from "./commands/run.js";
|
|
26
28
|
import { registerGroupsCommand } from "./commands/groups.js";
|
|
27
29
|
import { registerFilesCommand } from "./commands/files.js";
|
|
28
30
|
initSentry();
|
|
@@ -63,6 +65,7 @@ const cloudCmd = program
|
|
|
63
65
|
.command("cloud")
|
|
64
66
|
.description("Cloud commands — provision entities and manage cloud-backed companies");
|
|
65
67
|
registerCloudProvisionCommands(cloudCmd);
|
|
68
|
+
registerCloudDemoteCommands(cloudCmd);
|
|
66
69
|
// Team commands (top-level)
|
|
67
70
|
registerTeamSyncCommand(program);
|
|
68
71
|
// Auth commands (top-level — Cognito OAuth)
|
|
@@ -72,6 +75,8 @@ registerWhoamiCommand(program);
|
|
|
72
75
|
registerAuthCommands(program);
|
|
73
76
|
// Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
|
|
74
77
|
registerSecretsCommand(program);
|
|
78
|
+
// Schema-driven dev runner — hq run [options] -- <cmd>
|
|
79
|
+
registerRunCommand(program);
|
|
75
80
|
// Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
|
|
76
81
|
registerGroupsCommand(program);
|
|
77
82
|
// Files ACL management (subcommand group — hq files share|unshare|acl)
|
|
@@ -91,4 +96,4 @@ registerOnboardCommand(program);
|
|
|
91
96
|
}
|
|
92
97
|
})();
|
|
93
98
|
//# sourceMappingURL=index.js.map
|
|
94
|
-
//# debugId=
|
|
99
|
+
//# debugId=ebc3116c-f836-550a-b5bb-4a74bce24abc
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface SchemaConflict {
|
|
2
|
+
paths: [string, string];
|
|
3
|
+
slugs: [string, string];
|
|
4
|
+
}
|
|
5
|
+
export interface DiscoverSchemasResult {
|
|
6
|
+
schemaPaths: string[];
|
|
7
|
+
envLocalPaths: string[];
|
|
8
|
+
companySlug: string | null;
|
|
9
|
+
conflict: SchemaConflict | null;
|
|
10
|
+
}
|
|
11
|
+
export declare function discoverSchemas(cwd: string): DiscoverSchemasResult;
|
|
12
|
+
//# sourceMappingURL=discover-schemas.d.ts.map
|