@indigoai-us/hq-cli 5.77.14 → 5.79.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 (309) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/assets/scaffold/core/scripts/archive-old-threads.sh +86 -0
  3. package/assets/scaffold/core/scripts/backfill-company-skill-mirrors.sh +73 -0
  4. package/assets/scaffold/core/scripts/backfill-workspace-mirror.sh +51 -0
  5. package/assets/scaffold/core/scripts/codex-skill-bridge.sh +550 -0
  6. package/assets/scaffold/core/scripts/detect-stale-core-policy-mirror.sh +185 -0
  7. package/assets/scaffold/core/scripts/hq-status-summary.sh +187 -0
  8. package/assets/scaffold/core/scripts/ontology-readme-drift.sh +264 -0
  9. package/assets/scaffold/core/scripts/qmd-reindex-after-sync.sh +93 -0
  10. package/assets/scaffold/core/scripts/rebuild-all-indexes.sh +69 -0
  11. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +206 -0
  12. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +127 -0
  13. package/assets/scaffold/core/scripts/rebuild-orchestrator-index.sh +86 -0
  14. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +105 -0
  15. package/assets/scaffold/core/scripts/rebuild-public-knowledge-index.sh +83 -0
  16. package/assets/scaffold/core/scripts/rebuild-reports-index.sh +114 -0
  17. package/assets/scaffold/core/scripts/rebuild-social-drafts-index.sh +135 -0
  18. package/assets/scaffold/core/scripts/rebuild-threads-index.sh +82 -0
  19. package/assets/scaffold/core/scripts/rebuild-workers-index.sh +97 -0
  20. package/assets/scaffold/core/scripts/resize-screenshot.sh +47 -0
  21. package/assets/scaffold/core/scripts/token-usage-report.sh +254 -0
  22. package/assets/scaffold/core/scripts/worktree.sh +136 -0
  23. package/dist/commands/agents.js +28 -12
  24. package/dist/commands/api-keys.js +100 -20
  25. package/dist/commands/core.d.ts +90 -0
  26. package/dist/commands/core.js +279 -0
  27. package/dist/commands/files-browse.d.ts +21 -0
  28. package/dist/commands/files-browse.js +145 -24
  29. package/dist/commands/files.js +33 -7
  30. package/dist/commands/meetings.js +16 -9
  31. package/dist/commands/members.js +16 -5
  32. package/dist/commands/pack-install.d.ts +14 -0
  33. package/dist/commands/pack-install.js +42 -2
  34. package/dist/commands/pkg-install.js +39 -2
  35. package/dist/commands/run.js +6 -2
  36. package/dist/commands/secrets.js +120 -65
  37. package/dist/main.js +6 -0
  38. package/dist/utils/api-key-command-gate.d.ts +45 -0
  39. package/dist/utils/api-key-command-gate.js +51 -0
  40. package/dist/utils/hq-roots.d.ts +91 -0
  41. package/dist/utils/hq-roots.js +212 -0
  42. package/dist/utils/resolve-vault-credential.d.ts +63 -3
  43. package/dist/utils/resolve-vault-credential.js +152 -6
  44. package/dist/utils/run-bundled-script.d.ts +66 -0
  45. package/dist/utils/run-bundled-script.js +80 -0
  46. package/dist/utils/vault-api.d.ts +21 -0
  47. package/dist/utils/vault-api.js +74 -3
  48. package/package.json +7 -1
  49. package/.claude/policies/hq-cli-interactive-reads-use-sts-vend.md +0 -49
  50. package/.github/workflows/ci.yml +0 -46
  51. package/.github/workflows/publish.yml +0 -36
  52. package/.github/workflows/scripts/smoke-test-pkg.sh +0 -97
  53. package/e2e/cli.test.ts +0 -128
  54. package/eslint.config.js +0 -37
  55. package/pnpm-workspace.yaml +0 -4
  56. package/scripts/chmod-bins.mjs +0 -49
  57. package/scripts/generate-dsn.mjs +0 -26
  58. package/scripts/generate-scan-packages-table.mjs +0 -113
  59. package/scripts/smoke-sources-signals.sh +0 -103
  60. package/src/bin/hq-auth-refresh.ts +0 -43
  61. package/src/cli-version.ts +0 -13
  62. package/src/commands/__fixtures__/make-tar.ts +0 -126
  63. package/src/commands/_patterns.ts +0 -10
  64. package/src/commands/add.ts +0 -75
  65. package/src/commands/agents.test.ts +0 -527
  66. package/src/commands/agents.ts +0 -923
  67. package/src/commands/api-keys.test.ts +0 -291
  68. package/src/commands/api-keys.ts +0 -382
  69. package/src/commands/artifact-verify.test.ts +0 -177
  70. package/src/commands/auth.test.ts +0 -82
  71. package/src/commands/auth.ts +0 -213
  72. package/src/commands/billing.test.ts +0 -158
  73. package/src/commands/billing.ts +0 -146
  74. package/src/commands/channels.test.ts +0 -74
  75. package/src/commands/channels.ts +0 -91
  76. package/src/commands/cloud-demote.test.ts +0 -401
  77. package/src/commands/cloud-demote.ts +0 -278
  78. package/src/commands/cloud-provision.test.ts +0 -1117
  79. package/src/commands/cloud-provision.ts +0 -942
  80. package/src/commands/cloud.pull-all.test.ts +0 -711
  81. package/src/commands/cloud.pull-per-company.test.ts +0 -188
  82. package/src/commands/cloud.push-all.test.ts +0 -485
  83. package/src/commands/cloud.scope-excluded-warning.test.ts +0 -22
  84. package/src/commands/cloud.selectors.test.ts +0 -208
  85. package/src/commands/cloud.status.test.ts +0 -160
  86. package/src/commands/cloud.test.ts +0 -41
  87. package/src/commands/cloud.ts +0 -2130
  88. package/src/commands/company.test.ts +0 -202
  89. package/src/commands/company.ts +0 -148
  90. package/src/commands/creators.test.ts +0 -60
  91. package/src/commands/creators.ts +0 -117
  92. package/src/commands/crm.test.ts +0 -179
  93. package/src/commands/crm.ts +0 -236
  94. package/src/commands/db-migrate.ts +0 -55
  95. package/src/commands/db-provision.ts +0 -114
  96. package/src/commands/db-sql.ts +0 -124
  97. package/src/commands/db-status.ts +0 -108
  98. package/src/commands/db.ts +0 -26
  99. package/src/commands/dm.test.ts +0 -748
  100. package/src/commands/dm.ts +0 -1226
  101. package/src/commands/feedback.test.ts +0 -413
  102. package/src/commands/feedback.ts +0 -169
  103. package/src/commands/files-browse.test.ts +0 -1249
  104. package/src/commands/files-browse.ts +0 -1506
  105. package/src/commands/files-delete.test.ts +0 -484
  106. package/src/commands/files-recovery.test.ts +0 -370
  107. package/src/commands/files.test.ts +0 -722
  108. package/src/commands/files.ts +0 -1446
  109. package/src/commands/group-grants.test.ts +0 -330
  110. package/src/commands/group-grants.ts +0 -455
  111. package/src/commands/groups.test.ts +0 -44
  112. package/src/commands/groups.ts +0 -368
  113. package/src/commands/integrations.test.ts +0 -633
  114. package/src/commands/integrations.ts +0 -507
  115. package/src/commands/list.ts +0 -85
  116. package/src/commands/login.ts +0 -52
  117. package/src/commands/logout.ts +0 -30
  118. package/src/commands/marketplace-install.test.ts +0 -543
  119. package/src/commands/marketplace-security.test.ts +0 -646
  120. package/src/commands/mcp-registration.test.ts +0 -2787
  121. package/src/commands/mcp-registration.ts +0 -2612
  122. package/src/commands/mcp-status.test.ts +0 -483
  123. package/src/commands/mcp-status.ts +0 -575
  124. package/src/commands/mcp-status.us011.test.ts +0 -243
  125. package/src/commands/meetings.test.ts +0 -522
  126. package/src/commands/meetings.ts +0 -789
  127. package/src/commands/members.test.ts +0 -1474
  128. package/src/commands/members.ts +0 -1181
  129. package/src/commands/onboard-identity-guard.test.ts +0 -99
  130. package/src/commands/onboard-identity-guard.ts +0 -103
  131. package/src/commands/onboard-join.test.ts +0 -96
  132. package/src/commands/onboard-join.ts +0 -101
  133. package/src/commands/onboard-warning.test.ts +0 -26
  134. package/src/commands/onboard-warning.ts +0 -12
  135. package/src/commands/onboard.ts +0 -267
  136. package/src/commands/outposts-heartbeat.test.ts +0 -299
  137. package/src/commands/outposts-heartbeat.ts +0 -310
  138. package/src/commands/outposts-replica-sync.test.ts +0 -272
  139. package/src/commands/outposts-self-deploy.test.ts +0 -243
  140. package/src/commands/outposts.test.ts +0 -1039
  141. package/src/commands/outposts.ts +0 -1935
  142. package/src/commands/pack-install-secret-authorization.test.ts +0 -115
  143. package/src/commands/pack-install.test.ts +0 -1469
  144. package/src/commands/pack-install.ts +0 -2256
  145. package/src/commands/pack-update-cache.test.ts +0 -149
  146. package/src/commands/packs-update-api-key.test.ts +0 -105
  147. package/src/commands/packs.test.ts +0 -88
  148. package/src/commands/packs.ts +0 -622
  149. package/src/commands/people.test.ts +0 -807
  150. package/src/commands/people.ts +0 -422
  151. package/src/commands/pkg-install.dispatch.test.ts +0 -103
  152. package/src/commands/pkg-install.ts +0 -221
  153. package/src/commands/pkg-list.test.ts +0 -79
  154. package/src/commands/pkg-list.ts +0 -13
  155. package/src/commands/pkg-remove.ts +0 -71
  156. package/src/commands/pkg-update.ts +0 -189
  157. package/src/commands/publish.test.ts +0 -650
  158. package/src/commands/publish.ts +0 -580
  159. package/src/commands/reindex.test.ts +0 -259
  160. package/src/commands/reindex.ts +0 -274
  161. package/src/commands/rescue.test.ts +0 -39
  162. package/src/commands/rescue.ts +0 -210
  163. package/src/commands/run.env-local.test.ts +0 -88
  164. package/src/commands/run.test.ts +0 -45
  165. package/src/commands/run.ts +0 -190
  166. package/src/commands/safe-extract.test.ts +0 -459
  167. package/src/commands/safe-extract.ts +0 -444
  168. package/src/commands/secrets-scope.test.ts +0 -56
  169. package/src/commands/secrets-scope.ts +0 -32
  170. package/src/commands/secrets.parse-destination.test.ts +0 -38
  171. package/src/commands/secrets.test.ts +0 -2050
  172. package/src/commands/secrets.ts +0 -2249
  173. package/src/commands/signals.ts +0 -351
  174. package/src/commands/skill.test.ts +0 -770
  175. package/src/commands/skill.ts +0 -796
  176. package/src/commands/sources.ts +0 -362
  177. package/src/commands/sync-mode.test.ts +0 -366
  178. package/src/commands/sync-mode.ts +0 -387
  179. package/src/commands/sync-narrow.test.ts +0 -633
  180. package/src/commands/sync-narrow.ts +0 -555
  181. package/src/commands/sync.ts +0 -165
  182. package/src/commands/team-sync.ts +0 -628
  183. package/src/commands/update.ts +0 -71
  184. package/src/commands/whoami.ts +0 -83
  185. package/src/commands/workers.test.ts +0 -158
  186. package/src/commands/workers.ts +0 -301
  187. package/src/index.test.ts +0 -32
  188. package/src/index.ts +0 -20
  189. package/src/lib/db/control-plane.test.ts +0 -59
  190. package/src/lib/db/control-plane.ts +0 -113
  191. package/src/lib/db/local.test.ts +0 -81
  192. package/src/lib/db/local.ts +0 -148
  193. package/src/lib/db/migrate.test.ts +0 -133
  194. package/src/lib/db/migrate.ts +0 -137
  195. package/src/lib/db/paths.test.ts +0 -112
  196. package/src/lib/db/paths.ts +0 -128
  197. package/src/lib/db/remote-engine.test.ts +0 -44
  198. package/src/lib/db/remote-engine.ts +0 -148
  199. package/src/lib/db/remote-sql.test.ts +0 -32
  200. package/src/lib/db/remote-sql.ts +0 -62
  201. package/src/lib/db/sql.test.ts +0 -106
  202. package/src/lib/db/sql.ts +0 -192
  203. package/src/lib/hq-cloud-dep.smoke.test.ts +0 -75
  204. package/src/lib/local-tree-diff.test.ts +0 -301
  205. package/src/lib/local-tree-diff.ts +0 -362
  206. package/src/lib/narrow-hint-banner.test.ts +0 -235
  207. package/src/lib/narrow-hint-banner.ts +0 -212
  208. package/src/lib/plan-limit-nag.test.ts +0 -317
  209. package/src/lib/plan-limit-nag.ts +0 -264
  210. package/src/main.ts +0 -371
  211. package/src/node-preflight.test.ts +0 -60
  212. package/src/node-preflight.ts +0 -67
  213. package/src/outpost/session-heartbeat-bounds.test.ts +0 -195
  214. package/src/outpost/session-heartbeat-guard.test.ts +0 -105
  215. package/src/outpost/session-heartbeat-publisher.test.ts +0 -178
  216. package/src/outpost/session-heartbeat-publisher.ts +0 -186
  217. package/src/outpost/session-heartbeat-retain-guard.test.ts +0 -126
  218. package/src/outpost/session-heartbeat.test.ts +0 -459
  219. package/src/outpost/session-heartbeat.ts +0 -877
  220. package/src/packaging.test.ts +0 -109
  221. package/src/run/__fixtures__/discover-schemas/example.env.schema +0 -4
  222. package/src/run/discover-schemas.test.ts +0 -153
  223. package/src/run/discover-schemas.ts +0 -79
  224. package/src/run/hq-plugin.test.ts +0 -371
  225. package/src/run/hq-plugin.ts +0 -277
  226. package/src/run/varlock-shape.test.ts +0 -57
  227. package/src/schemas/hq-package.schema.json +0 -155
  228. package/src/sentry-before-send.test.ts +0 -359
  229. package/src/sentry-before-send.ts +0 -221
  230. package/src/sentry-epipe.test.ts +0 -37
  231. package/src/sentry-release.test.ts +0 -54
  232. package/src/sentry.test.ts +0 -24
  233. package/src/sentry.ts +0 -54
  234. package/src/strategies/link.ts +0 -62
  235. package/src/strategies/merge.ts +0 -142
  236. package/src/types.ts +0 -146
  237. package/src/utils/__fixtures__/scan-packages.generated-block.sh +0 -23
  238. package/src/utils/auth-error.test.ts +0 -40
  239. package/src/utils/auth-error.ts +0 -42
  240. package/src/utils/billing-gate.test.ts +0 -95
  241. package/src/utils/billing-gate.ts +0 -228
  242. package/src/utils/breadcrumb-buffer.ts +0 -18
  243. package/src/utils/cli-telemetry.test.ts +0 -153
  244. package/src/utils/cli-telemetry.ts +0 -61
  245. package/src/utils/cognito-session.machine.test.ts +0 -109
  246. package/src/utils/cognito-session.refresh.test.ts +0 -84
  247. package/src/utils/cognito-session.test.ts +0 -328
  248. package/src/utils/cognito-session.ts +0 -448
  249. package/src/utils/company-selection-error.test.ts +0 -42
  250. package/src/utils/company-selection-error.ts +0 -45
  251. package/src/utils/contribution-table.ts +0 -83
  252. package/src/utils/environmental-error.test.ts +0 -45
  253. package/src/utils/environmental-error.ts +0 -39
  254. package/src/utils/epipe.test.ts +0 -28
  255. package/src/utils/epipe.ts +0 -29
  256. package/src/utils/expected-cli-error.test.ts +0 -28
  257. package/src/utils/expected-cli-error.ts +0 -39
  258. package/src/utils/feedback-diagnostics.test.ts +0 -183
  259. package/src/utils/feedback-diagnostics.ts +0 -123
  260. package/src/utils/feedback-screenshots.test.ts +0 -134
  261. package/src/utils/feedback-screenshots.ts +0 -124
  262. package/src/utils/feedback-versions.test.ts +0 -98
  263. package/src/utils/feedback-versions.ts +0 -68
  264. package/src/utils/git.ts +0 -74
  265. package/src/utils/integrity.ts +0 -59
  266. package/src/utils/intercepted-process-exit.test.ts +0 -37
  267. package/src/utils/intercepted-process-exit.ts +0 -36
  268. package/src/utils/login-provider.test.ts +0 -42
  269. package/src/utils/login-provider.ts +0 -30
  270. package/src/utils/manifest.test.ts +0 -167
  271. package/src/utils/manifest.ts +0 -131
  272. package/src/utils/pack-contributions.test.ts +0 -603
  273. package/src/utils/pack-contributions.ts +0 -450
  274. package/src/utils/people.ts +0 -215
  275. package/src/utils/registry-client.ts +0 -204
  276. package/src/utils/registry.ts +0 -90
  277. package/src/utils/resolve-vault-credential.test.ts +0 -69
  278. package/src/utils/resolve-vault-credential.ts +0 -60
  279. package/src/utils/sandbox-runner-client.test.ts +0 -279
  280. package/src/utils/sandbox-runner-client.ts +0 -260
  281. package/src/utils/secrets-cache.ts +0 -183
  282. package/src/utils/sentry-identity.ts +0 -45
  283. package/src/utils/settle-with-timeout.test.ts +0 -21
  284. package/src/utils/settle-with-timeout.ts +0 -22
  285. package/src/utils/user-yaml-error.test.ts +0 -24
  286. package/src/utils/user-yaml-error.ts +0 -30
  287. package/src/utils/vault-api.test.ts +0 -536
  288. package/src/utils/vault-api.ts +0 -382
  289. package/src/utils/version-check.test.ts +0 -176
  290. package/src/utils/version-check.ts +0 -155
  291. package/src/utils/version-gate.test.ts +0 -1024
  292. package/src/utils/version-gate.ts +0 -702
  293. package/test/commands/db-tenant-isolation.test.ts +0 -94
  294. package/test/commands/db.test.ts +0 -85
  295. package/test/commands/signals.test.ts +0 -207
  296. package/test/commands/sources.test.ts +0 -231
  297. package/test/e2e/smoke-install-mcp.sh +0 -113
  298. package/test/fixtures/hq-pack-smoke-mcp/mcp/smoke-http.json +0 -1
  299. package/test/fixtures/hq-pack-smoke-mcp/package.yaml +0 -11
  300. package/test/fixtures/signals/action_item/sample.md +0 -16
  301. package/test/fixtures/signals/summary/sample.md +0 -12
  302. package/test/fixtures/sources/meetings/sample.md +0 -25
  303. package/test/helpers/cli-runner.ts +0 -150
  304. package/test/helpers/s3-list-mock.ts +0 -79
  305. package/test/helpers/vault-service-mock.ts +0 -295
  306. package/test/sources-signals/smoke.test.ts +0 -228
  307. package/tsconfig.json +0 -20
  308. package/vitest.config.ts +0 -11
  309. package/vitest.e2e.config.ts +0 -7
@@ -1,2249 +0,0 @@
1
- import { Command } from "commander";
2
- import chalk from "chalk";
3
- import * as readline from "node:readline";
4
- import { spawn } from "node:child_process";
5
- import * as nodePath from "node:path";
6
- import { ensureCognitoToken } from "../utils/cognito-session.js";
7
- import {
8
- DEFAULT_SECRETS_CACHE_TTL_MS,
9
- writeCache,
10
- removeCacheEntry,
11
- clearAllCache,
12
- } from "../utils/secrets-cache.js";
13
- import { computeSha256 } from "../utils/integrity.js";
14
- import { SECRET_NAME_PATTERN, GROUP_ID_PATTERN, EMAIL_PATTERN } from "./_patterns.js";
15
- import {
16
- describeSecretsScope,
17
- formatSecretSaved,
18
- formatSecretsListEmpty,
19
- formatSecretsListHeader,
20
- } from "./secrets-scope.js";
21
- import {
22
- vaultApiFetch,
23
- getCompanyUid,
24
- getEntityUid,
25
- } from "../utils/vault-api.js";
26
- import {
27
- HQ_API_KEY_PREFIX,
28
- assertCognitoOnlyCommand,
29
- resolveVaultCredential,
30
- } from "../utils/resolve-vault-credential.js";
31
- import {
32
- SandboxRunnerClient,
33
- type SandboxRunnerJob,
34
- } from "../utils/sandbox-runner-client.js";
35
- export type { VaultApiOptions } from "../utils/vault-api.js";
36
- export { vaultApiFetch, getCompanyUid, getEntityUid };
37
-
38
- /** Cognito session for secrets commands that do not support HQ_API_KEY. */
39
- async function requireCognitoTokenForSecrets(
40
- commandLabel: string,
41
- ): Promise<string> {
42
- assertCognitoOnlyCommand(commandLabel);
43
- return ensureCognitoToken();
44
- }
45
-
46
- interface SecretsScopeOpts {
47
- company?: string;
48
- personal?: boolean;
49
- }
50
-
51
- function scopeOpts(opts: SecretsScopeOpts): {
52
- personal: boolean;
53
- companySlug: string | undefined;
54
- } {
55
- if (opts.personal && opts.company) {
56
- console.error(
57
- chalk.red("Error: --personal cannot be combined with --company."),
58
- );
59
- process.exit(1);
60
- }
61
- return { personal: !!opts.personal, companySlug: opts.company };
62
- }
63
-
64
- function rejectIfPersonal(opts: SecretsScopeOpts, action: string): void {
65
- if (opts.personal) {
66
- console.error(
67
- chalk.red(`Error: ${action} is not supported with --personal.`),
68
- );
69
- process.exit(1);
70
- }
71
- }
72
-
73
- function shellSingleQuote(value: string): string {
74
- return "'" + value.replace(/'/g, "'\\''") + "'";
75
- }
76
-
77
- // API Gateway v2 URL-decodes `%2F` before route matching, so a full-name
78
- // `encodeURIComponent` would collapse structural `/` separators into a single
79
- // segment the `/name/{proxy+}` route can't match.
80
- function buildSecretNamePath(companyUid: string, name: string): string {
81
- const encodedName = name
82
- .split("/")
83
- .map(encodeURIComponent)
84
- .join("/");
85
- return `/secrets/${encodeURIComponent(companyUid)}/name/${encodedName}`;
86
- }
87
-
88
- function parseDuration(input: string): number | null {
89
- const match = input.match(/^(\d+)(m|h|d)$/);
90
- if (!match) return null;
91
- const value = parseInt(match[1], 10);
92
- const unit = match[2];
93
- if (unit === "m") return value * 60 * 1000;
94
- if (unit === "h") return value * 60 * 60 * 1000;
95
- if (unit === "d") return value * 24 * 60 * 60 * 1000;
96
- return null;
97
- }
98
-
99
- function confirmPrompt(message: string): Promise<boolean> {
100
- const rl = readline.createInterface({
101
- input: process.stdin,
102
- output: process.stdout,
103
- });
104
- return new Promise((resolve) => {
105
- rl.question(`${message} [y/N] `, (answer) => {
106
- rl.close();
107
- resolve(answer.trim().toLowerCase() === "y");
108
- });
109
- });
110
- }
111
-
112
- function readFromPipedStdin(): Promise<string> {
113
- return new Promise((resolve, reject) => {
114
- let data = "";
115
- process.stdin.setEncoding("utf8");
116
- process.stdin.on("data", (chunk) => {
117
- data += chunk;
118
- });
119
- process.stdin.on("end", () => resolve(data.replace(/\n$/, "")));
120
- process.stdin.on("error", reject);
121
- });
122
- }
123
-
124
- function promptSecretInteractively(): Promise<string> {
125
- return new Promise((resolve, reject) => {
126
- process.stdout.write("Enter secret value: ");
127
-
128
- if (process.stdin.isTTY) {
129
- process.stdin.setRawMode(true);
130
- }
131
-
132
- let value = "";
133
- process.stdin.setEncoding("utf8");
134
-
135
- const cleanup = () => {
136
- if (process.stdin.isTTY) {
137
- process.stdin.setRawMode(false);
138
- }
139
- process.stdin.removeListener("data", onData);
140
- process.stdin.removeListener("end", onEnd);
141
- process.stdin.pause();
142
- };
143
-
144
- const onEnd = () => {
145
- cleanup();
146
- process.stdout.write("\n");
147
- resolve(value);
148
- };
149
-
150
- const onData = (ch: string) => {
151
- for (const c of ch) {
152
- const code = c.codePointAt(0)!;
153
- if (c === "\n" || c === "\r" || code === 4) {
154
- cleanup();
155
- process.stdout.write("\n");
156
- resolve(value);
157
- return;
158
- } else if (code === 3) {
159
- cleanup();
160
- reject(new Error("Aborted"));
161
- return;
162
- } else if (code === 0x1b) {
163
- return;
164
- } else if (code === 127) {
165
- if (value.length > 0) {
166
- value = value.slice(0, -1);
167
- }
168
- } else if (code >= 0x20) {
169
- value += c;
170
- }
171
- }
172
- };
173
-
174
- process.stdin.on("data", onData);
175
- process.stdin.on("end", onEnd);
176
- process.stdin.resume();
177
- });
178
- }
179
-
180
- // Maximum names per batch-load request. Mirrors hq-pro's MAX_BATCH_NAMES so a
181
- // large --only list is chunked client-side rather than 400'd whole by the
182
- // server (the legacy per-key GET path had no such cap).
183
- const MAX_BATCH_NAMES = 100;
184
- const SECRET_LOAD_TIMEOUT_MS = 30_000;
185
-
186
- export type SecretTier = "standard" | "sensitive" | "nuclear";
187
- export type SecretScriptLockMode = "off" | "enforced";
188
- export type SecretUsageChannel =
189
- | "run"
190
- | "exec"
191
- | "env"
192
- | "sandbox"
193
- | "reveal"
194
- | "submit-link";
195
-
196
- export interface SecretScriptUsage {
197
- scriptId: string;
198
- path: string;
199
- sha256: string;
200
- attestationLevel: string;
201
- }
202
-
203
- export interface SecretUsage {
204
- channel: SecretUsageChannel;
205
- reason?: string;
206
- script?: SecretScriptUsage;
207
- }
208
-
209
- export interface SecretMetadata {
210
- tier?: SecretTier;
211
- scriptLock?: {
212
- mode?: SecretScriptLockMode;
213
- requiredAttestation?: string;
214
- };
215
- cacheTtlMs?: number;
216
- }
217
-
218
- export interface SecretLoadSuccessRow extends SecretMetadata {
219
- name: string;
220
- value?: string;
221
- }
222
-
223
- export interface SecretLoadResponse {
224
- secrets: SecretLoadSuccessRow[];
225
- errors: Array<{ name: string; code: string; message?: string }>;
226
- }
227
-
228
- function highSecuritySandboxOnlyMessage(secretName?: string): string {
229
- const sandboxExample = secretName
230
- ? `hq secrets sandbox --only ${secretName} -- <command>`
231
- : "hq secrets sandbox --only <secret> -- <command>";
232
- return `High-security secrets can run only in the sandbox (use \`${sandboxExample}\`) or through the HQ secret proxy. Local injection and script locks (\`--script\`) are not supported.`;
233
- }
234
-
235
- interface SecretGetResponse {
236
- secret: {
237
- name: string;
238
- companyUid: string;
239
- type?: string;
240
- lastModifiedDate?: string;
241
- version?: number;
242
- value?: string;
243
- } & SecretMetadata;
244
- }
245
-
246
- interface SecretPolicyScript {
247
- scriptId: string;
248
- scriptPath: string;
249
- sha256: string;
250
- attestationLevel: string;
251
- }
252
-
253
- interface SecretPolicyApprovedScript {
254
- scriptId: string;
255
- path: string;
256
- sha256?: string;
257
- attestationLevel: string;
258
- revokedAt?: string;
259
- }
260
-
261
- interface SecretPolicyRecord {
262
- path: string;
263
- tier?: SecretTier;
264
- scriptLock?: {
265
- mode?: SecretScriptLockMode;
266
- requiredAttestation?: string;
267
- approvedScripts?: SecretPolicyApprovedScript[];
268
- };
269
- scripts?: SecretPolicyScript[];
270
- }
271
-
272
- interface SecretPolicyResponse {
273
- policy?: SecretPolicyRecord;
274
- scripts?: SecretPolicyScript[];
275
- }
276
-
277
- interface SecretAclPrincipal {
278
- granteeType: "email" | "group" | "company-wide";
279
- granteeId: string;
280
- }
281
-
282
- function parseSecretAclPrincipal(
283
- principal: string,
284
- ): SecretAclPrincipal | null {
285
- const p = principal.trim();
286
- if (p === "@all") {
287
- // Company-wide grant: every active member of the company. The server
288
- // carries no specific grantee id for this axis, so granteeId is empty.
289
- return { granteeType: "company-wide", granteeId: "" };
290
- }
291
- if (EMAIL_PATTERN.test(p)) {
292
- return { granteeType: "email", granteeId: p.toLowerCase() };
293
- }
294
- if (GROUP_ID_PATTERN.test(p)) {
295
- return { granteeType: "group", granteeId: p };
296
- }
297
- console.error(
298
- chalk.red(
299
- `Invalid principal '${principal}': must be '@all', an email address, or a group id matching grp_<alphanumeric, underscore, hyphen>`,
300
- ),
301
- );
302
- return null;
303
- }
304
-
305
- function describeSecretAclPrincipal(principal: SecretAclPrincipal): string {
306
- return principal.granteeType === "company-wide"
307
- ? "@all (entire company)"
308
- : principal.granteeId;
309
- }
310
-
311
- // secrets-proxy-per-secret-destination US-006: an InjectionRecipe as sent on
312
- // the create/update POST body. Mirrors hq-pro's `InjectionRecipe`
313
- // (src/vault-service/handlers/secrets.ts) — kept as a local shape (not
314
- // imported) since the CLI does not depend on the hq-pro package.
315
- export interface SecretInjectionRecipe {
316
- header: string;
317
- scheme: "raw" | "bearer";
318
- extraHeaders?: Record<string, string>;
319
- }
320
-
321
- // Mirrors hq-pro's server-authoritative KNOWN_DESTINATION_REGISTRY
322
- // (src/vault-service/handlers/destination-registry.ts) — a KNOWN host's
323
- // --auth-style is optional because the server resolves the recipe itself.
324
- // This client-side copy exists purely so an UNKNOWN host with no
325
- // --auth-style can be rejected immediately with a clear, actionable message
326
- // instead of a round trip; the server remains the authoritative validator
327
- // (this list drifting stale merely means one extra CLI round trip, not a
328
- // security gap — the server still 400s an unrecognized host with no recipe).
329
- const KNOWN_DESTINATION_HOSTS = new Set([
330
- "api.anthropic.com",
331
- "api.openai.com",
332
- "api.stripe.com",
333
- ]);
334
-
335
- // Parses `--auth-style` into the InjectionRecipe shape the server expects.
336
- // Returns `null` (with a printed error) for an unrecognized value.
337
- function parseAuthStyle(authStyle: string): SecretInjectionRecipe | null {
338
- if (authStyle === "bearer") {
339
- return { header: "authorization", scheme: "bearer" };
340
- }
341
- if (authStyle === "x-api-key") {
342
- return { header: "x-api-key", scheme: "raw" };
343
- }
344
- const headerMatch = authStyle.match(/^header:(.+)$/);
345
- if (headerMatch) {
346
- const headerName = headerMatch[1].trim();
347
- if (!headerName) {
348
- console.error(
349
- chalk.red(
350
- `Invalid --auth-style 'header:': must name a header, e.g. header:X-Custom-Key`,
351
- ),
352
- );
353
- return null;
354
- }
355
- return { header: headerName, scheme: "raw" };
356
- }
357
- console.error(
358
- chalk.red(
359
- `Invalid --auth-style '${authStyle}': must be one of bearer, x-api-key, or header:NAME`,
360
- ),
361
- );
362
- return null;
363
- }
364
-
365
- // Validates `--destination` is a bare HTTPS scheme+host URL (no path, query,
366
- // port). Mirrors hq-pro's `validateDestinations` server-side check
367
- // (src/vault-service/handlers/secrets.ts) so a malformed URL is caught
368
- // locally with an actionable message rather than a round trip — the server
369
- // re-validates and remains authoritative.
370
- export function parseDestinationUrl(
371
- raw: string,
372
- ): { ok: true; url: string; hostname: string } | { ok: false } {
373
- let parsed: URL;
374
- try {
375
- parsed = new URL(raw);
376
- } catch {
377
- console.error(
378
- chalk.red(`Invalid --destination '${raw}': must be a valid URL`),
379
- );
380
- return { ok: false };
381
- }
382
- if (parsed.protocol !== "https:") {
383
- console.error(
384
- chalk.red(`Invalid --destination '${raw}': must use https://`),
385
- );
386
- return { ok: false };
387
- }
388
- if (!parsed.hostname) {
389
- console.error(
390
- chalk.red(`Invalid --destination '${raw}': missing hostname`),
391
- );
392
- return { ok: false };
393
- }
394
- // Reject an embedded `user:pass@host` credential segment explicitly rather
395
- // than letting `new URL()` silently drop it (mirrors hq-pro's authoritative
396
- // `validateDestinations`; the server re-validates and remains authoritative).
397
- if (parsed.username !== "" || parsed.password !== "") {
398
- console.error(
399
- chalk.red(
400
- `Invalid --destination '${raw}': must not contain embedded userinfo (user:pass@) credentials`,
401
- ),
402
- );
403
- return { ok: false };
404
- }
405
- if (
406
- (parsed.pathname !== "" && parsed.pathname !== "/") ||
407
- parsed.search !== "" ||
408
- parsed.hash !== ""
409
- ) {
410
- console.error(
411
- chalk.red(
412
- `Invalid --destination '${raw}': must be a bare scheme+host URL with no path, query, or fragment (e.g. https://api.openai.com)`,
413
- ),
414
- );
415
- return { ok: false };
416
- }
417
- if (parsed.port !== "") {
418
- console.error(
419
- chalk.red(`Invalid --destination '${raw}': must not specify a port`),
420
- );
421
- return { ok: false };
422
- }
423
- return { ok: true, url: `https://${parsed.hostname}`, hostname: parsed.hostname };
424
- }
425
-
426
- function normalizeSecretTier(tier?: string): SecretTier {
427
- return tier === "sensitive" || tier === "nuclear" ? tier : "standard";
428
- }
429
-
430
- function normalizeScriptLockMode(mode?: string): SecretScriptLockMode {
431
- return mode === "enforced" ? "enforced" : "off";
432
- }
433
-
434
- function normalizeCacheTtlMs(metadata: SecretMetadata): number {
435
- // Controlled rows must never reach the offline cache even if a mixed-version
436
- // or malformed response carries a positive TTL. The server is authoritative
437
- // for access, but the client still has enough policy metadata to fail safe.
438
- if (
439
- metadata.tier === "sensitive" ||
440
- metadata.tier === "nuclear" ||
441
- metadata.scriptLock?.mode === "enforced"
442
- ) {
443
- return 0;
444
- }
445
- if (metadata.cacheTtlMs === undefined) {
446
- return DEFAULT_SECRETS_CACHE_TTL_MS;
447
- }
448
- return typeof metadata.cacheTtlMs === "number" &&
449
- Number.isFinite(metadata.cacheTtlMs) &&
450
- metadata.cacheTtlMs > 0
451
- ? metadata.cacheTtlMs
452
- : 0;
453
- }
454
-
455
- function extractApiMessage(
456
- body: Record<string, unknown>,
457
- fallback: string,
458
- ): string {
459
- const message = typeof body.message === "string" ? body.message : undefined;
460
- const error = typeof body.error === "string" ? body.error : undefined;
461
- return message ?? error ?? fallback;
462
- }
463
-
464
- async function buildSecretUsage(
465
- channel: SecretUsageChannel,
466
- scriptPath?: string,
467
- scriptId?: string,
468
- attestationLevel = "self-asserted-hash",
469
- ): Promise<SecretUsage> {
470
- if (scriptId && !scriptPath) {
471
- throw new Error("--script-id requires --script");
472
- }
473
- if (!scriptPath) {
474
- return { channel };
475
- }
476
- const resolvedPath = nodePath.resolve(scriptPath);
477
- return {
478
- channel,
479
- script: {
480
- scriptId: scriptId ?? resolvedPath,
481
- path: resolvedPath,
482
- sha256: await computeSha256(resolvedPath),
483
- attestationLevel,
484
- },
485
- };
486
- }
487
-
488
- // Commander collector for `--only`: accumulates across REPEATED flags instead
489
- // of the last one silently winning, and each value may still be
490
- // comma-separated. So `--only A,B`, `--only A --only B`, and
491
- // `--only A,B --only C` all resolve to the full list.
492
- export function collectSecretNames(value: string, previous?: string[]): string[] {
493
- const parsed = value.split(",").map((k) => k.trim()).filter(Boolean);
494
- return (previous ?? []).concat(parsed);
495
- }
496
-
497
- function parseSecretNameList(input: string[] | undefined): string[] {
498
- const keys = input ?? [];
499
- if (keys.length === 0) {
500
- console.error(chalk.red("Error: --only requires at least one secret name."));
501
- process.exit(1);
502
- }
503
- for (const key of keys) {
504
- if (!SECRET_NAME_PATTERN.test(key)) {
505
- console.error(chalk.red(`Invalid secret name '${key}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$`));
506
- process.exit(1);
507
- }
508
- }
509
- return keys;
510
- }
511
-
512
- function mergeScopeOpts(
513
- parent: SecretsScopeOpts,
514
- child: SecretsScopeOpts,
515
- ): SecretsScopeOpts {
516
- return {
517
- company: child.company ?? parent.company,
518
- personal: child.personal ?? parent.personal,
519
- };
520
- }
521
-
522
- export function scrubSandboxOutput(text: string, secretNames: string[] = []): string {
523
- let scrubbed = text;
524
- for (const name of secretNames) {
525
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
526
- scrubbed = scrubbed.replace(
527
- new RegExp(`\\b(${escaped})\\s*=\\s*([^\\s'"\\n]+|'[^'\\n]*'|"[^"\\n]*")`, "g"),
528
- "$1=[REDACTED]",
529
- );
530
- scrubbed = scrubbed.replace(
531
- new RegExp(`\\b(${escaped})\\s*:\\s*([^\\s'"\\n]+|'[^'\\n]*'|"[^"\\n]*")`, "g"),
532
- "$1: [REDACTED]",
533
- );
534
- }
535
- return scrubbed
536
- .replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[REDACTED]")
537
- .replace(/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/g, "[REDACTED]")
538
- .replace(/\b[A-Za-z0-9+/]{40,}={0,2}\b/g, "[REDACTED]");
539
- }
540
-
541
- function renderSandboxJobResult(job: SandboxRunnerJob, secretNames: string[]): void {
542
- if (job.output) {
543
- const output = scrubSandboxOutput(job.output, secretNames);
544
- process.stdout.write(output);
545
- if (output.length > 0 && !output.endsWith("\n")) {
546
- process.stdout.write("\n");
547
- }
548
- }
549
- }
550
-
551
- function normalizePolicyRecord(
552
- secretPath: string,
553
- data: SecretPolicyResponse,
554
- ): SecretPolicyRecord & { scripts: SecretPolicyScript[] } {
555
- const policy = data.policy ?? { path: secretPath };
556
- const scripts = Array.isArray(policy.scriptLock?.approvedScripts)
557
- ? policy.scriptLock.approvedScripts
558
- .filter(
559
- (script) =>
560
- script !== null &&
561
- typeof script === "object" &&
562
- typeof script.scriptId === "string" &&
563
- typeof script.path === "string" &&
564
- typeof script.attestationLevel === "string" &&
565
- !script.revokedAt,
566
- )
567
- .map((script) => ({
568
- scriptId: script.scriptId,
569
- scriptPath: script.path,
570
- sha256: typeof script.sha256 === "string" ? script.sha256 : "",
571
- attestationLevel: script.attestationLevel,
572
- }))
573
- : Array.isArray(policy.scripts)
574
- ? policy.scripts.filter(isSecretPolicyScript)
575
- : Array.isArray(data.scripts)
576
- ? data.scripts.filter(isSecretPolicyScript)
577
- : [];
578
- return {
579
- path: policy.path ?? secretPath,
580
- tier: normalizeSecretTier(policy.tier),
581
- scriptLock: {
582
- mode: normalizeScriptLockMode(policy.scriptLock?.mode),
583
- requiredAttestation: policy.scriptLock?.requiredAttestation,
584
- },
585
- scripts,
586
- };
587
- }
588
-
589
- function isSecretPolicyScript(value: unknown): value is SecretPolicyScript {
590
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
591
- const script = value as Partial<SecretPolicyScript>;
592
- return (
593
- typeof script.scriptId === "string" &&
594
- typeof script.scriptPath === "string" &&
595
- typeof script.sha256 === "string" &&
596
- typeof script.attestationLevel === "string"
597
- );
598
- }
599
-
600
- function renderPolicySummary(policy: SecretPolicyRecord): void {
601
- console.log(chalk.bold(`Policy: ${policy.path}`));
602
- console.log(` Tier: ${normalizeSecretTier(policy.tier)}`);
603
- console.log(
604
- ` Script Lock: ${normalizeScriptLockMode(policy.scriptLock?.mode)}`,
605
- );
606
- if (policy.scriptLock?.requiredAttestation) {
607
- console.log(
608
- ` Attestation: ${policy.scriptLock.requiredAttestation}`,
609
- );
610
- }
611
- }
612
-
613
- function renderPolicyScripts(scripts: SecretPolicyScript[]): void {
614
- if (scripts.length === 0) {
615
- console.log(chalk.dim("No approved scripts."));
616
- return;
617
- }
618
-
619
- const idWidth = Math.max(2, ...scripts.map((script) => script.scriptId.length));
620
- const pathWidth = Math.max(
621
- 6,
622
- ...scripts.map((script) => script.scriptPath.length),
623
- );
624
- const attestationWidth = Math.max(
625
- 11,
626
- ...scripts.map((script) => script.attestationLevel.length),
627
- );
628
- const header = [
629
- "ID".padEnd(idWidth),
630
- "SCRIPT".padEnd(pathWidth),
631
- "ATTESTATION".padEnd(attestationWidth),
632
- "SHA256",
633
- ].join(" ");
634
- console.log(chalk.bold(header));
635
- for (const script of scripts) {
636
- console.log(
637
- [
638
- script.scriptId.padEnd(idWidth),
639
- script.scriptPath.padEnd(pathWidth),
640
- script.attestationLevel.padEnd(attestationWidth),
641
- script.sha256 || "-",
642
- ].join(" "),
643
- );
644
- }
645
- }
646
-
647
- // HQ-4H — load + decrypt secrets through the BATCH-LOAD endpoint
648
- // (`POST /secrets/{companyUid}/load`) instead of one single-secret GET per key.
649
- //
650
- // Every single-secret GET that 404s makes vault-service emit an unattributed
651
- // "Secret not found" Sentry *warning* — each `response(404, …)` is captured at
652
- // the response boundary (hq-pro `_error-response.ts`). That capture is the
653
- // right signal for `hq secrets get <name>` ("a caller genuinely needed THIS
654
- // secret and it was missing"), but it is pure noise for a multi-key load where
655
- // a missing / renamed / rotated key is a per-key outcome `exec`/`env` already
656
- // report cleanly to the user. The batch-load endpoint returns 200 with a
657
- // per-name `errors[]` array and never captures — the same path `hq run` uses,
658
- // which is exactly why `hq run` never contributed to HQ-4H. Routing `exec` and
659
- // `env` through it stops those callers from emitting the warning while keeping
660
- // identical UX and error text.
661
- //
662
- // Every value use through exec/env/reveal is server-authorized, including when
663
- // an encrypted disk-cache entry exists. The cache remains write-through for
664
- // explicitly offline install-time consumers; these commands never trust it as
665
- // an authorization decision. This means a policy, ACL, tier, or script-approval
666
- // change takes effect on their next use even though there is no push revocation.
667
- // Requests are chunked at MAX_BATCH_NAMES and throw on the FIRST unresolved key
668
- // with the same `Failed to fetch secret '<k>': <reason>` shape the per-key GET
669
- // path used — never swallows a failure.
670
- async function loadRevealedSecretsViaApiKey(
671
- token: string,
672
- keys: string[],
673
- ): Promise<Map<string, string>> {
674
- const resolved = new Map<string, string>();
675
- const requested = [...new Set(keys)];
676
- const cacheScope = "__api_key__";
677
-
678
- for (const name of requested) {
679
- const res = await vaultApiFetch({
680
- token,
681
- path: "/v1/keys/secrets/fetch",
682
- method: "POST",
683
- body: { name },
684
- signal: AbortSignal.timeout(SECRET_LOAD_TIMEOUT_MS),
685
- });
686
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
687
-
688
- if (!res.ok) {
689
- if (res.status === 404) {
690
- throw new Error(`Failed to fetch secret '${name}': Secret not found`);
691
- }
692
- if (res.status === 403) {
693
- const message =
694
- typeof body.error === "string"
695
- ? body.error
696
- : typeof body.message === "string"
697
- ? body.message
698
- : "No read permission";
699
- if (body.highSecurity === true) {
700
- throw new Error(highSecuritySandboxOnlyMessage(name));
701
- }
702
- throw new Error(`Failed to fetch secret '${name}': ${message}`);
703
- }
704
- if (res.status === 401) {
705
- throw new Error(
706
- `Failed to fetch secret '${name}': Invalid or missing API key`,
707
- );
708
- }
709
- throw new Error(
710
- `Failed to fetch secret '${name}': ${extractApiMessage(body, res.statusText)}`,
711
- );
712
- }
713
-
714
- const secret =
715
- typeof body.secret === "object" && body.secret !== null
716
- ? (body.secret as { value?: unknown; name?: unknown })
717
- : null;
718
- if (typeof secret?.value !== "string") {
719
- throw new Error(
720
- `Failed to fetch secret '${name}': malformed fetch response`,
721
- );
722
- }
723
- removeCacheEntry(cacheScope, name);
724
- resolved.set(name, secret.value);
725
- }
726
-
727
- return resolved;
728
- }
729
-
730
- export async function loadRevealedSecrets(
731
- token: string,
732
- companyUid: string,
733
- keys: string[],
734
- usage?: SecretUsage,
735
- ): Promise<Map<string, string>> {
736
- if (token.startsWith(HQ_API_KEY_PREFIX)) {
737
- return loadRevealedSecretsViaApiKey(token, keys);
738
- }
739
-
740
- const resolved = new Map<string, string>();
741
- const requested = [...new Set(keys)];
742
- try {
743
- for (let i = 0; i < requested.length; i += MAX_BATCH_NAMES) {
744
- const chunk = requested.slice(i, i + MAX_BATCH_NAMES);
745
- const chunkNames = new Set(chunk);
746
- const res = await vaultApiFetch({
747
- token,
748
- path: `/secrets/${encodeURIComponent(companyUid)}/load`,
749
- method: "POST",
750
- body: usage ? { names: chunk, usage } : { names: chunk },
751
- signal: AbortSignal.timeout(SECRET_LOAD_TIMEOUT_MS),
752
- });
753
- if (!res.ok) {
754
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
755
- const message = extractApiMessage(body, res.statusText);
756
- // High-security refusal surfaced at the batch level (rather than
757
- // per-name): point the caller at the sandbox/proxy and never leak
758
- // plaintext. A local script attestation is not an override.
759
- if (
760
- body.code === "high_security_denied" ||
761
- body.code === "high_security_sandbox_only" ||
762
- body.highSecurity === true
763
- ) {
764
- throw new Error(highSecuritySandboxOnlyMessage());
765
- }
766
- if (
767
- res.status >= 400 &&
768
- res.status < 500 &&
769
- typeof body.code === "string"
770
- ) {
771
- throw new Error(message);
772
- }
773
- throw new Error(
774
- `Failed to batch-load secrets: ${message}`,
775
- );
776
- }
777
- const data = (await res.json()) as Partial<SecretLoadResponse>;
778
- if (!Array.isArray(data.secrets) || !Array.isArray(data.errors)) {
779
- throw new Error("Invalid secret load response from vault");
780
- }
781
- const errorsByName = new Map<string, { code: string; message?: string }>();
782
- const seenNames = new Set<string>();
783
-
784
- for (const rawSecret of data.secrets) {
785
- if (!rawSecret || typeof rawSecret !== "object") {
786
- throw new Error("Invalid secret load response from vault");
787
- }
788
- const s = rawSecret as SecretLoadSuccessRow;
789
- if (
790
- typeof s.name !== "string" ||
791
- !chunkNames.has(s.name) ||
792
- seenNames.has(s.name) ||
793
- (s.value != null && typeof s.value !== "string")
794
- ) {
795
- throw new Error("Invalid secret load response from vault");
796
- }
797
- seenNames.add(s.name);
798
- if (s.value == null) {
799
- errorsByName.set(s.name, {
800
- code: "not_returned",
801
- message: `Secret '${s.name}' has no value (reveal may not be permitted).`,
802
- });
803
- removeCacheEntry(companyUid, s.name);
804
- continue;
805
- }
806
- const cacheTtlMs = normalizeCacheTtlMs(s);
807
- if (cacheTtlMs > 0) {
808
- writeCache(companyUid, s.name, s.value, cacheTtlMs);
809
- } else {
810
- removeCacheEntry(companyUid, s.name);
811
- }
812
- resolved.set(s.name, s.value);
813
- }
814
-
815
- for (const rawError of data.errors) {
816
- if (!rawError || typeof rawError !== "object") {
817
- throw new Error("Invalid secret load response from vault");
818
- }
819
- const e = rawError as { name?: unknown; code?: unknown; message?: unknown };
820
- if (
821
- typeof e.name !== "string" ||
822
- !chunkNames.has(e.name) ||
823
- seenNames.has(e.name) ||
824
- typeof e.code !== "string" ||
825
- (e.message !== undefined && typeof e.message !== "string")
826
- ) {
827
- throw new Error("Invalid secret load response from vault");
828
- }
829
- seenNames.add(e.name);
830
- errorsByName.set(e.name, { code: e.code, message: e.message });
831
- resolved.delete(e.name);
832
- removeCacheEntry(companyUid, e.name);
833
- }
834
- // Any requested key in this chunk the server did not return is a per-key
835
- // failure — surface it with the same prefix the single-GET path used so
836
- // callers (and scripts grepping stderr) see no behavior change.
837
- let firstFailure: Error | null = null;
838
- for (const key of chunk) {
839
- if (resolved.has(key)) continue;
840
- removeCacheEntry(companyUid, key);
841
- const err = errorsByName.get(key);
842
- // Every caller of loadRevealedSecrets injects or prints the plaintext
843
- // locally (`secrets get --reveal`, `secrets exec`, `secrets env`). Both
844
- // high-security denial shapes therefore receive the same explicit
845
- // sandbox/proxy guidance, even if the caller supplied `--script`.
846
- if (
847
- err?.code === "high_security_denied" ||
848
- err?.code === "high_security_sandbox_only"
849
- ) {
850
- firstFailure ??= new Error(highSecuritySandboxOnlyMessage(key));
851
- continue;
852
- }
853
- const reason =
854
- err?.code === "not_found"
855
- ? "Secret not found"
856
- : err?.code === "forbidden"
857
- ? err.message ?? "No read permission"
858
- : err?.message ?? err?.code ?? "not returned by vault";
859
- firstFailure ??= new Error(`Failed to fetch secret '${key}': ${reason}`);
860
- }
861
- if (firstFailure) {
862
- throw firstFailure;
863
- }
864
- }
865
-
866
- return resolved;
867
- } catch (err) {
868
- // A transport failure, stale session, malformed response, or a later chunk
869
- // failure must not leave values written by this attempted operation available
870
- // to offline cache readers. Evict the whole request before failing closed.
871
- for (const key of requested) {
872
- removeCacheEntry(companyUid, key);
873
- }
874
- throw err;
875
- }
876
- }
877
-
878
- export function registerSecretsCommand(program: Command): void {
879
- const secrets = program
880
- .command("secrets")
881
- .description("Manage secrets in HQ vault (SSM Parameter Store)")
882
- .option("--company <slug>", "Company slug (resolves to companyUid)")
883
- .option(
884
- "--personal",
885
- "Operate on the caller's personal vault (no sharing)",
886
- );
887
-
888
- secrets
889
- .command("set <name>")
890
- .description("Create or update a secret")
891
- .option("--from-stdin", "Read secret value from piped stdin")
892
- .option(
893
- "--high-security",
894
- "Mark the secret high-security: it can never be revealed or injected locally, only used through the HQ secret proxy (requires --destination)",
895
- )
896
- .option(
897
- "--destination <https-url>",
898
- "Approved scheme+host HTTPS URL the proxy may forward this secret to (e.g. https://api.openai.com); required with --high-security",
899
- )
900
- .option(
901
- "--auth-style <style>",
902
- "How the proxy attaches the key upstream: bearer | x-api-key | header:NAME. Optional for known destinations (auto-resolved server-side); required for unknown ones",
903
- )
904
- .action(async (
905
- name: string,
906
- opts: {
907
- fromStdin?: boolean;
908
- highSecurity?: boolean;
909
- destination?: string;
910
- authStyle?: string;
911
- },
912
- ) => {
913
- try {
914
- if (!SECRET_NAME_PATTERN.test(name)) {
915
- console.error(chalk.red(`Invalid secret name '${name}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_API_KEY or DEV/MY_KEY)`));
916
- process.exit(1);
917
- }
918
-
919
- // secrets-proxy-per-secret-destination US-006: --high-security marks
920
- // the secret so it can only ever be used through the server-side
921
- // proxy (never revealed/injected locally — that refusal is the
922
- // pre-existing consumption-side behavior in `get`/`exec`/`env` above,
923
- // unchanged by this story). It REQUIRES a --destination: the proxy
924
- // (hq-pro US-002) fails closed with no destination configured, so
925
- // catching the missing pin here is a clear, immediate CLI error
926
- // rather than a deferred proxy-time failure.
927
- let destinations: string[] | undefined;
928
- let injection: SecretInjectionRecipe | undefined;
929
- if (opts.highSecurity) {
930
- if (!opts.destination) {
931
- console.error(
932
- chalk.red(
933
- "Error: --high-security requires --destination <https-url> (e.g. --destination https://api.openai.com).",
934
- ),
935
- );
936
- process.exit(1);
937
- }
938
-
939
- const destResult = parseDestinationUrl(opts.destination);
940
- if (!destResult.ok) {
941
- process.exit(1);
942
- }
943
- destinations = [destResult.url];
944
-
945
- if (opts.authStyle) {
946
- const recipe = parseAuthStyle(opts.authStyle);
947
- if (!recipe) {
948
- process.exit(1);
949
- }
950
- injection = recipe;
951
- } else if (!KNOWN_DESTINATION_HOSTS.has(destResult.hostname)) {
952
- // Unknown host + no explicit recipe: the server would reject this
953
- // 400 anyway (US-004 registry lookup only, never guesses) — fail
954
- // fast locally with an actionable message instead of a round trip.
955
- console.error(
956
- chalk.red(
957
- `Error: unknown destination host '${destResult.hostname}' — provide --auth-style <bearer|x-api-key|header:NAME> (known hosts auto-resolve: ${[...KNOWN_DESTINATION_HOSTS].join(", ")}).`,
958
- ),
959
- );
960
- process.exit(1);
961
- }
962
- // Known host + no --auth-style: leave `injection` undefined so the
963
- // server (US-004) auto-resolves the recipe from its registry.
964
- } else if (opts.destination || opts.authStyle) {
965
- console.error(
966
- chalk.red(
967
- "Error: --destination/--auth-style require --high-security.",
968
- ),
969
- );
970
- process.exit(1);
971
- }
972
-
973
- let value: string;
974
- if (opts.fromStdin) {
975
- if (process.stdin.isTTY) {
976
- console.error(chalk.red("Error: --from-stdin requires piped input (e.g. echo 'val' | hq secrets set NAME --from-stdin)"));
977
- process.exit(1);
978
- }
979
- value = await readFromPipedStdin();
980
- } else {
981
- if (!process.stdin.isTTY) {
982
- console.error(chalk.red("Error: stdin is not a terminal. Use --from-stdin for piped input."));
983
- process.exit(1);
984
- }
985
- value = await promptSecretInteractively();
986
- }
987
-
988
- if (!value) {
989
- console.error(chalk.red("Error: secret value cannot be empty."));
990
- process.exit(1);
991
- }
992
-
993
- if (Buffer.byteLength(value, "utf8") > 4096) {
994
- console.error(chalk.red(`Secret value exceeds 4096-byte SSM limit (got ${Buffer.byteLength(value, "utf8")} bytes).`));
995
- process.exit(1);
996
- }
997
-
998
- const token = await requireCognitoTokenForSecrets("secrets set");
999
- const scope = scopeOpts(secrets.opts());
1000
- const companyUid = await getEntityUid(token, scope);
1001
- const scopeLabel = describeSecretsScope({
1002
- personal: scope.personal,
1003
- companySlug: scope.companySlug,
1004
- companyUid,
1005
- });
1006
-
1007
- const res = await vaultApiFetch({
1008
- token,
1009
- path: `/secrets/${encodeURIComponent(companyUid)}`,
1010
- method: "POST",
1011
- body: {
1012
- name,
1013
- value,
1014
- // Only present when --high-security was passed — an ordinary
1015
- // `set` with no flags sends exactly `{ name, value }`, byte-for-
1016
- // byte unchanged from before this story.
1017
- ...(opts.highSecurity ? { highSecurity: true } : {}),
1018
- ...(destinations ? { destinations } : {}),
1019
- ...(injection ? { injection } : {}),
1020
- },
1021
- });
1022
-
1023
- if (!res.ok) {
1024
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1025
- console.error(
1026
- chalk.red(`Failed to set secret: ${extractApiMessage(body, res.statusText)}`),
1027
- );
1028
- process.exit(1);
1029
- }
1030
-
1031
- removeCacheEntry(companyUid, name);
1032
- console.log(chalk.green(formatSecretSaved(name, scopeLabel)));
1033
- if (opts.highSecurity) {
1034
- console.log(
1035
- chalk.dim(
1036
- ` High-security: destination pinned to ${destinations?.[0]}. This value can run only in the sandbox (hq secrets sandbox) or through the HQ secret proxy; local injection and script locks are unsupported.`,
1037
- ),
1038
- );
1039
- }
1040
- } catch (err) {
1041
- console.error(
1042
- chalk.red("Error:"),
1043
- err instanceof Error ? err.message : String(err),
1044
- );
1045
- process.exit(1);
1046
- }
1047
- });
1048
-
1049
- secrets
1050
- .command("get <name>")
1051
- .description("Get a secret's metadata (use --reveal for value)")
1052
- .option("--reveal", "Include the decrypted secret value")
1053
- .action(async (name: string, opts: { reveal?: boolean }) => {
1054
- try {
1055
- const cred = await resolveVaultCredential();
1056
-
1057
- if (cred.kind === "api-key") {
1058
- if (!opts.reveal) {
1059
- console.error(
1060
- chalk.red(
1061
- "HQ_API_KEY is set; `hq secrets get` without --reveal is not supported for API keys. " +
1062
- "Use --reveal to fetch the value, or unset HQ_API_KEY for metadata-only reads.",
1063
- ),
1064
- );
1065
- process.exit(1);
1066
- }
1067
- const res = await vaultApiFetch({
1068
- token: cred.token,
1069
- path: "/v1/keys/secrets/fetch",
1070
- method: "POST",
1071
- body: { name },
1072
- });
1073
- const body = (await res.json().catch(() => ({}))) as Record<
1074
- string,
1075
- unknown
1076
- >;
1077
- if (!res.ok) {
1078
- if (res.status === 403 && body.highSecurity === true) {
1079
- console.error(chalk.red(highSecuritySandboxOnlyMessage(name)));
1080
- process.exit(1);
1081
- }
1082
- console.error(
1083
- chalk.red(
1084
- `Failed to get secret: ${extractApiMessage(body, res.statusText)}`,
1085
- ),
1086
- );
1087
- process.exit(1);
1088
- }
1089
- const secret =
1090
- typeof body.secret === "object" && body.secret !== null
1091
- ? (body.secret as SecretGetResponse["secret"] & {
1092
- value?: string;
1093
- })
1094
- : null;
1095
- if (!secret || typeof secret.name !== "string") {
1096
- console.error(chalk.red("Failed to get secret: malformed response"));
1097
- process.exit(1);
1098
- }
1099
- console.log(chalk.bold(`Secret: ${secret.name}`));
1100
- if (secret.lastModifiedDate) {
1101
- console.log(` Last Modified: ${secret.lastModifiedDate}`);
1102
- }
1103
- if (secret.version != null) {
1104
- console.log(` Version: ${secret.version}`);
1105
- }
1106
- console.log(` Tier: ${normalizeSecretTier(secret.tier)}`);
1107
- console.log(
1108
- ` Script Lock: ${normalizeScriptLockMode(secret.scriptLock?.mode)}`,
1109
- );
1110
- if (opts.reveal) {
1111
- if (typeof secret.value !== "string") {
1112
- console.error(
1113
- chalk.red(
1114
- "Failed to get secret: reveal requested but response omitted secret.value",
1115
- ),
1116
- );
1117
- process.exit(1);
1118
- }
1119
- console.log(` Value: ${secret.value}`);
1120
- } else {
1121
- console.log(` Value: ${chalk.dim("[REDACTED]")}`);
1122
- }
1123
- return;
1124
- }
1125
-
1126
- const token = cred.token;
1127
- const companyUid = await getEntityUid(
1128
- token,
1129
- scopeOpts(secrets.opts()),
1130
- );
1131
-
1132
- const res = await vaultApiFetch({
1133
- token,
1134
- path: buildSecretNamePath(companyUid, name),
1135
- });
1136
-
1137
- if (!res.ok) {
1138
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1139
- // High-security secrets cannot be revealed locally. Surface the
1140
- // hosted execution path rather than a raw 4xx; `--script` never
1141
- // overrides this boundary.
1142
- if (res.status === 403 && body.highSecurity === true) {
1143
- console.error(chalk.red(highSecuritySandboxOnlyMessage(name)));
1144
- process.exit(1);
1145
- }
1146
- console.error(
1147
- chalk.red(`Failed to get secret: ${extractApiMessage(body, res.statusText)}`),
1148
- );
1149
- process.exit(1);
1150
- }
1151
-
1152
- const data = (await res.json()) as SecretGetResponse;
1153
-
1154
- let revealedValue: string | undefined;
1155
- let revealError: string | null = null;
1156
- if (opts.reveal) {
1157
- try {
1158
- revealedValue = (
1159
- await loadRevealedSecrets(token, companyUid, [name], await buildSecretUsage("reveal"))
1160
- ).get(name);
1161
- } catch (err) {
1162
- revealError = err instanceof Error ? err.message : String(err);
1163
- }
1164
- }
1165
-
1166
- const s = data.secret;
1167
- console.log(chalk.bold(`Secret: ${s.name}`));
1168
- if (s.lastModifiedDate) {
1169
- console.log(` Last Modified: ${s.lastModifiedDate}`);
1170
- }
1171
- if (s.version != null) {
1172
- console.log(` Version: ${s.version}`);
1173
- }
1174
- console.log(` Tier: ${normalizeSecretTier(s.tier)}`);
1175
- console.log(
1176
- ` Script Lock: ${normalizeScriptLockMode(s.scriptLock?.mode)}`,
1177
- );
1178
- if (opts.reveal && revealedValue != null) {
1179
- console.log(` Value: ${revealedValue}`);
1180
- } else {
1181
- console.log(` Value: ${chalk.dim("[REDACTED]")}`);
1182
- }
1183
- if (revealError) {
1184
- console.error(chalk.red(revealError));
1185
- process.exit(1);
1186
- }
1187
- } catch (err) {
1188
- console.error(
1189
- chalk.red("Error:"),
1190
- err instanceof Error ? err.message : String(err),
1191
- );
1192
- process.exit(1);
1193
- }
1194
- });
1195
-
1196
- // HQ-4H: existence probe via the HEAD route. Optional-credential readers
1197
- // should HEAD-first so a missing secret no longer fires a spurious GET-404
1198
- // Sentry warning server-side: `hq secrets exists FOO && hq secrets get FOO …`.
1199
- // A HEAD never decrypts or reveals the value.
1200
- //
1201
- // Exit codes are designed for shell chaining:
1202
- // 0 → secret exists (200)
1203
- // 1 → secret is absent (404) — the normal "no" answer, NOT an error
1204
- // 2 → a real failure (auth/network/permission) — distinct from absence so
1205
- // `&&` chains don't mistake an outage for "absent and proceed"
1206
- secrets
1207
- .command("exists <name>")
1208
- .description("Check whether a secret exists (HEAD; exit 0=present, 1=absent, 2=error)")
1209
- .option("--quiet", "Suppress the present/absent line (use the exit code only)")
1210
- .action(async (name: string, opts: { quiet?: boolean }) => {
1211
- try {
1212
- const token = await requireCognitoTokenForSecrets("secrets exists");
1213
- const companyUid = await getEntityUid(
1214
- token,
1215
- scopeOpts(secrets.opts()),
1216
- );
1217
-
1218
- const res = await vaultApiFetch({
1219
- token,
1220
- method: "HEAD",
1221
- path: buildSecretNamePath(companyUid, name),
1222
- });
1223
-
1224
- if (res.status === 200) {
1225
- if (!opts.quiet) console.log(chalk.green(`exists: ${name}`));
1226
- process.exit(0);
1227
- }
1228
- if (res.status === 404) {
1229
- if (!opts.quiet) console.log(chalk.dim(`absent: ${name}`));
1230
- process.exit(1);
1231
- }
1232
- // Any other status (401/403/5xx) is a real failure, not an absence.
1233
- console.error(
1234
- chalk.red(
1235
- `Failed to check secret '${name}': HTTP ${res.status} ${res.statusText}`,
1236
- ),
1237
- );
1238
- process.exit(2);
1239
- } catch (err) {
1240
- console.error(
1241
- chalk.red("Error:"),
1242
- err instanceof Error ? err.message : String(err),
1243
- );
1244
- process.exit(2);
1245
- }
1246
- });
1247
-
1248
- secrets
1249
- .command("list")
1250
- .description("List all secrets for the company (including nested path-based names)")
1251
- .option(
1252
- "--prefix <path>",
1253
- "Filter by path prefix (e.g. DEV or DEV/SUB); omit or pass empty string for all secrets",
1254
- )
1255
- .action(async (opts: { prefix?: string }) => {
1256
- try {
1257
- // MUST match SECRET_PREFIX_PATTERN in hq-pro/src/vault-service/handlers/secrets.ts
1258
- let normalizedPrefix: string | undefined;
1259
- if (opts.prefix) {
1260
- const normalized = opts.prefix.replace(/^\/+|\/+$/g, "");
1261
- if (
1262
- normalized.length === 0 ||
1263
- !SECRET_NAME_PATTERN.test(normalized)
1264
- ) {
1265
- console.error(
1266
- chalk.red(
1267
- `Invalid prefix '${opts.prefix}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. DEV or DEV/SUB)`,
1268
- ),
1269
- );
1270
- process.exit(1);
1271
- }
1272
- normalizedPrefix = normalized;
1273
- }
1274
-
1275
- const token = await requireCognitoTokenForSecrets("secrets list");
1276
- const scope = scopeOpts(secrets.opts());
1277
- const companyUid = await getEntityUid(token, scope);
1278
- const scopeLabel = describeSecretsScope({
1279
- personal: scope.personal,
1280
- companySlug: scope.companySlug,
1281
- companyUid,
1282
- });
1283
-
1284
- const query: Record<string, string> = {};
1285
- if (normalizedPrefix) {
1286
- query.prefix = normalizedPrefix;
1287
- }
1288
-
1289
- const res = await vaultApiFetch({
1290
- token,
1291
- path: `/secrets/${encodeURIComponent(companyUid)}`,
1292
- query: Object.keys(query).length > 0 ? query : undefined,
1293
- });
1294
-
1295
- if (!res.ok) {
1296
- const body = await res.json().catch(() => ({}));
1297
- console.error(
1298
- chalk.red(`Failed to list secrets: ${(body as Record<string, string>).error ?? res.statusText}`),
1299
- );
1300
- process.exit(1);
1301
- }
1302
-
1303
- const data = (await res.json()) as {
1304
- secrets: Array<
1305
- {
1306
- name: string;
1307
- lastModifiedDate?: string;
1308
- version?: number;
1309
- permission?: "admin" | "write" | "read";
1310
- } & SecretMetadata
1311
- >;
1312
- };
1313
-
1314
- if (data.secrets.length === 0) {
1315
- console.log(chalk.dim(formatSecretsListEmpty(scopeLabel)));
1316
- return;
1317
- }
1318
-
1319
- const nameWidth = Math.max(4, ...data.secrets.map((s) => s.name.length));
1320
- const hasPermission = data.secrets.some((s) => s.permission !== undefined);
1321
- const tierWidth = Math.max(
1322
- 4,
1323
- ...data.secrets.map((s) => normalizeSecretTier(s.tier).length),
1324
- );
1325
- const scriptLockWidth = Math.max(
1326
- 11,
1327
- ...data.secrets.map((s) => normalizeScriptLockMode(s.scriptLock?.mode).length),
1328
- );
1329
- if (hasPermission) {
1330
- const accessWidth = Math.max(6, ...data.secrets.map((s) => (s.permission ?? "-").length));
1331
- const header = `${"NAME".padEnd(nameWidth)} ${"ACCESS".padEnd(accessWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
1332
- console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
1333
- console.log(chalk.bold(header));
1334
- for (const s of data.secrets) {
1335
- const access = s.permission ?? "-";
1336
- const tier = normalizeSecretTier(s.tier);
1337
- const scriptLock = normalizeScriptLockMode(s.scriptLock?.mode);
1338
- const modified = s.lastModifiedDate ?? "-";
1339
- console.log(`${s.name.padEnd(nameWidth)} ${access.padEnd(accessWidth)} ${tier.padEnd(tierWidth)} ${scriptLock.padEnd(scriptLockWidth)} ${modified}`);
1340
- }
1341
- } else {
1342
- const header = `${"NAME".padEnd(nameWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
1343
- console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
1344
- console.log(chalk.bold(header));
1345
- for (const s of data.secrets) {
1346
- const tier = normalizeSecretTier(s.tier);
1347
- const scriptLock = normalizeScriptLockMode(s.scriptLock?.mode);
1348
- const modified = s.lastModifiedDate ?? "-";
1349
- console.log(`${s.name.padEnd(nameWidth)} ${tier.padEnd(tierWidth)} ${scriptLock.padEnd(scriptLockWidth)} ${modified}`);
1350
- }
1351
- }
1352
- } catch (err) {
1353
- console.error(
1354
- chalk.red("Error:"),
1355
- err instanceof Error ? err.message : String(err),
1356
- );
1357
- process.exit(1);
1358
- }
1359
- });
1360
-
1361
- const policy = secrets
1362
- .command("policy")
1363
- .description("View or update secret access policy");
1364
-
1365
- policy
1366
- .command("get <path>")
1367
- .description("Show the policy for a secret path")
1368
- .action(async (secretPath: string) => {
1369
- try {
1370
- rejectIfPersonal(secrets.opts(), "policy get");
1371
-
1372
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1373
- console.error(chalk.red(`Invalid secret path '${secretPath}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
1374
- process.exit(1);
1375
- }
1376
-
1377
- const token = await requireCognitoTokenForSecrets("secrets");
1378
- const companyUid = await getEntityUid(
1379
- token,
1380
- scopeOpts(secrets.opts()),
1381
- );
1382
- const res = await vaultApiFetch({
1383
- token,
1384
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1385
- query: { path: secretPath },
1386
- });
1387
-
1388
- if (res.status === 404) {
1389
- renderPolicySummary(
1390
- normalizePolicyRecord(secretPath, { policy: { path: secretPath } }),
1391
- );
1392
- return;
1393
- }
1394
- if (!res.ok) {
1395
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1396
- console.error(
1397
- chalk.red(`Failed to get policy: ${extractApiMessage(body, res.statusText)}`),
1398
- );
1399
- process.exit(1);
1400
- }
1401
-
1402
- const data = (await res.json()) as SecretPolicyResponse;
1403
- renderPolicySummary(normalizePolicyRecord(secretPath, data));
1404
- } catch (err) {
1405
- console.error(
1406
- chalk.red("Error:"),
1407
- err instanceof Error ? err.message : String(err),
1408
- );
1409
- process.exit(1);
1410
- }
1411
- });
1412
-
1413
- policy
1414
- .command("set <path>")
1415
- .description("Set the policy for a secret path")
1416
- .option("--tier <tier>", "Secret tier: standard | sensitive | nuclear")
1417
- .option("--lock-script <mode>", "Script-lock mode: off | enforce")
1418
- .action(async (
1419
- secretPath: string,
1420
- opts: { tier?: string; lockScript?: string },
1421
- ) => {
1422
- try {
1423
- rejectIfPersonal(secrets.opts(), "policy set");
1424
-
1425
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1426
- console.error(chalk.red(`Invalid secret path '${secretPath}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
1427
- process.exit(1);
1428
- }
1429
-
1430
- const tier = opts.tier;
1431
- if (
1432
- tier !== undefined &&
1433
- tier !== "standard" &&
1434
- tier !== "sensitive" &&
1435
- tier !== "nuclear"
1436
- ) {
1437
- console.error(chalk.red(`Invalid tier '${tier}': must be one of standard, sensitive, nuclear`));
1438
- process.exit(1);
1439
- }
1440
-
1441
- let scriptLock:
1442
- | { mode: SecretScriptLockMode }
1443
- | undefined;
1444
- if (opts.lockScript !== undefined) {
1445
- if (opts.lockScript === "off") {
1446
- scriptLock = { mode: "off" };
1447
- } else if (opts.lockScript === "enforce") {
1448
- scriptLock = { mode: "enforced" };
1449
- } else {
1450
- console.error(chalk.red(`Invalid script lock mode '${opts.lockScript}': must be one of off, enforce`));
1451
- process.exit(1);
1452
- }
1453
- }
1454
-
1455
- if (tier === undefined && scriptLock === undefined) {
1456
- console.error(chalk.red("Error: provide at least one of --tier or --lock-script."));
1457
- process.exit(1);
1458
- }
1459
-
1460
- const token = await requireCognitoTokenForSecrets("secrets");
1461
- const companyUid = await getEntityUid(
1462
- token,
1463
- scopeOpts(secrets.opts()),
1464
- );
1465
- const res = await vaultApiFetch({
1466
- token,
1467
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1468
- method: "PUT",
1469
- body: {
1470
- path: secretPath,
1471
- ...(tier !== undefined ? { tier } : {}),
1472
- ...(scriptLock ? { scriptLock } : {}),
1473
- },
1474
- });
1475
-
1476
- if (!res.ok) {
1477
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1478
- console.error(
1479
- chalk.red(`Failed to set policy: ${extractApiMessage(body, res.statusText)}`),
1480
- );
1481
- process.exit(1);
1482
- }
1483
-
1484
- const data = (await res.json().catch(() => ({}))) as SecretPolicyResponse;
1485
- removeCacheEntry(companyUid, secretPath);
1486
- console.log(chalk.green(`Policy updated for '${secretPath}'.`));
1487
- renderPolicySummary(
1488
- normalizePolicyRecord(
1489
- secretPath,
1490
- data.policy ? data : { policy: { path: secretPath, tier, scriptLock } },
1491
- ),
1492
- );
1493
- } catch (err) {
1494
- console.error(
1495
- chalk.red("Error:"),
1496
- err instanceof Error ? err.message : String(err),
1497
- );
1498
- process.exit(1);
1499
- }
1500
- });
1501
-
1502
- const script = secrets
1503
- .command("script")
1504
- .description("Manage approved scripts for script-locked secrets");
1505
-
1506
- script
1507
- .command("approve <path>")
1508
- .description("Approve a script for a secret path")
1509
- .requiredOption("--id <scriptId>", "Stable script identifier")
1510
- .requiredOption("--script <path>", "Path to the local script file")
1511
- .option(
1512
- "--remote-path <path>",
1513
- "Script path reported by the target runtime (defaults to the local path)",
1514
- )
1515
- .option(
1516
- "--attestation <level>",
1517
- "Attestation level",
1518
- "self-asserted-hash",
1519
- )
1520
- .action(async (
1521
- secretPath: string,
1522
- opts: {
1523
- id: string;
1524
- script: string;
1525
- remotePath?: string;
1526
- attestation: string;
1527
- },
1528
- ) => {
1529
- try {
1530
- rejectIfPersonal(secrets.opts(), "script approve");
1531
-
1532
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1533
- console.error(chalk.red(`Invalid secret path '${secretPath}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
1534
- process.exit(1);
1535
- }
1536
-
1537
- const usage = await buildSecretUsage(
1538
- "exec",
1539
- opts.script,
1540
- opts.id,
1541
- opts.attestation,
1542
- );
1543
- const token = await requireCognitoTokenForSecrets("secrets");
1544
- const companyUid = await getEntityUid(
1545
- token,
1546
- scopeOpts(secrets.opts()),
1547
- );
1548
- const res = await vaultApiFetch({
1549
- token,
1550
- path: `/secrets/${encodeURIComponent(companyUid)}/policy/scripts`,
1551
- method: "POST",
1552
- body: {
1553
- path: secretPath,
1554
- scriptId: usage.script?.scriptId,
1555
- scriptPath: opts.remotePath ?? usage.script?.path,
1556
- sha256: usage.script?.sha256,
1557
- attestationLevel: usage.script?.attestationLevel,
1558
- },
1559
- });
1560
-
1561
- if (!res.ok) {
1562
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1563
- console.error(
1564
- chalk.red(`Failed to approve script: ${extractApiMessage(body, res.statusText)}`),
1565
- );
1566
- process.exit(1);
1567
- }
1568
-
1569
- removeCacheEntry(companyUid, secretPath);
1570
- console.log(chalk.green(`Approved script '${opts.id}' for '${secretPath}'.`));
1571
- } catch (err) {
1572
- console.error(
1573
- chalk.red("Error:"),
1574
- err instanceof Error ? err.message : String(err),
1575
- );
1576
- process.exit(1);
1577
- }
1578
- });
1579
-
1580
- script
1581
- .command("revoke <path>")
1582
- .description("Revoke an approved script from a secret path")
1583
- .requiredOption("--id <scriptId>", "Stable script identifier")
1584
- .action(async (secretPath: string, opts: { id: string }) => {
1585
- try {
1586
- rejectIfPersonal(secrets.opts(), "script revoke");
1587
-
1588
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1589
- console.error(chalk.red(`Invalid secret path '${secretPath}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
1590
- process.exit(1);
1591
- }
1592
-
1593
- const token = await requireCognitoTokenForSecrets("secrets");
1594
- const companyUid = await getEntityUid(
1595
- token,
1596
- scopeOpts(secrets.opts()),
1597
- );
1598
- const res = await vaultApiFetch({
1599
- token,
1600
- path: `/secrets/${encodeURIComponent(companyUid)}/policy/scripts`,
1601
- method: "DELETE",
1602
- body: { path: secretPath, scriptId: opts.id },
1603
- });
1604
-
1605
- if (!res.ok) {
1606
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1607
- console.error(
1608
- chalk.red(`Failed to revoke script: ${extractApiMessage(body, res.statusText)}`),
1609
- );
1610
- process.exit(1);
1611
- }
1612
-
1613
- removeCacheEntry(companyUid, secretPath);
1614
- console.log(chalk.green(`Revoked script '${opts.id}' for '${secretPath}'.`));
1615
- } catch (err) {
1616
- console.error(
1617
- chalk.red("Error:"),
1618
- err instanceof Error ? err.message : String(err),
1619
- );
1620
- process.exit(1);
1621
- }
1622
- });
1623
-
1624
- script
1625
- .command("list <path>")
1626
- .description("List approved scripts for a secret path")
1627
- .action(async (secretPath: string) => {
1628
- try {
1629
- rejectIfPersonal(secrets.opts(), "script list");
1630
-
1631
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1632
- console.error(chalk.red(`Invalid secret path '${secretPath}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
1633
- process.exit(1);
1634
- }
1635
-
1636
- const token = await requireCognitoTokenForSecrets("secrets");
1637
- const companyUid = await getEntityUid(
1638
- token,
1639
- scopeOpts(secrets.opts()),
1640
- );
1641
- const res = await vaultApiFetch({
1642
- token,
1643
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1644
- query: { path: secretPath },
1645
- });
1646
-
1647
- if (res.status === 404) {
1648
- const policyRecord = normalizePolicyRecord(secretPath, {
1649
- policy: { path: secretPath },
1650
- });
1651
- renderPolicySummary(policyRecord);
1652
- renderPolicyScripts(policyRecord.scripts);
1653
- return;
1654
- }
1655
- if (!res.ok) {
1656
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1657
- console.error(
1658
- chalk.red(`Failed to list scripts: ${extractApiMessage(body, res.statusText)}`),
1659
- );
1660
- process.exit(1);
1661
- }
1662
-
1663
- const data = (await res.json()) as SecretPolicyResponse;
1664
- const policyRecord = normalizePolicyRecord(secretPath, data);
1665
- renderPolicySummary(policyRecord);
1666
- renderPolicyScripts(policyRecord.scripts);
1667
- } catch (err) {
1668
- console.error(
1669
- chalk.red("Error:"),
1670
- err instanceof Error ? err.message : String(err),
1671
- );
1672
- process.exit(1);
1673
- }
1674
- });
1675
-
1676
- secrets
1677
- .command("delete <name>")
1678
- .description("Delete a secret")
1679
- .option("--force", "Skip confirmation prompt")
1680
- .action(async (name: string, opts: { force?: boolean }) => {
1681
- try {
1682
- if (!SECRET_NAME_PATTERN.test(name)) {
1683
- console.error(chalk.red(`Invalid secret name '${name}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_API_KEY or DEV/MY_KEY)`));
1684
- process.exit(1);
1685
- }
1686
-
1687
- if (!opts.force) {
1688
- const confirmed = await confirmPrompt(
1689
- `Delete secret '${name}'? This cannot be undone.`,
1690
- );
1691
- if (!confirmed) {
1692
- console.log(chalk.dim("Aborted."));
1693
- return;
1694
- }
1695
- }
1696
-
1697
- const token = await requireCognitoTokenForSecrets("secrets");
1698
- const companyUid = await getEntityUid(
1699
- token,
1700
- scopeOpts(secrets.opts()),
1701
- );
1702
-
1703
- const res = await vaultApiFetch({
1704
- token,
1705
- path: buildSecretNamePath(companyUid, name),
1706
- method: "DELETE",
1707
- });
1708
-
1709
- if (!res.ok) {
1710
- const body = await res.json().catch(() => ({}));
1711
- console.error(
1712
- chalk.red(`Failed to delete secret: ${(body as Record<string, string>).error ?? res.statusText}`),
1713
- );
1714
- process.exit(1);
1715
- }
1716
-
1717
- removeCacheEntry(companyUid, name);
1718
- console.log(chalk.green(`Secret '${name}' deleted.`));
1719
- } catch (err) {
1720
- console.error(
1721
- chalk.red("Error:"),
1722
- err instanceof Error ? err.message : String(err),
1723
- );
1724
- process.exit(1);
1725
- }
1726
- });
1727
-
1728
- secrets
1729
- .command("sandbox")
1730
- .description("Run a command in the hosted sandbox with named secrets injected as env vars; open egress, secrets never touch this machine")
1731
- .option("--company <slug>", "Company slug (resolves to companyUid)")
1732
- .option(
1733
- "--personal",
1734
- "Operate on the caller's personal vault (no sharing)",
1735
- )
1736
- .option("--only <keys>", "Secret names to inject (comma-separated; may be repeated) (required)", collectSecretNames)
1737
- .allowUnknownOption(true)
1738
- .action(async (opts: { company?: string; personal?: boolean; only?: string[] }, cmd: Command) => {
1739
- try {
1740
- if (!opts.only || opts.only.length === 0) {
1741
- console.error(chalk.red("Error: --only is required and must name at least one secret."));
1742
- process.exit(1);
1743
- }
1744
-
1745
- const rawArgs = cmd.args;
1746
- const command = rawArgs.join(" ").trim();
1747
- if (command.length === 0) {
1748
- console.error(chalk.red("Error: no command specified. Usage: hq secrets sandbox --company <slug> --only KEY1,KEY2 -- <command>"));
1749
- process.exit(1);
1750
- }
1751
- if (command.length > 8192) {
1752
- console.error(chalk.red("Error: sandbox command exceeds the 8192 character limit."));
1753
- process.exit(1);
1754
- }
1755
-
1756
- const keys = parseSecretNameList(opts.only);
1757
- const token = await requireCognitoTokenForSecrets("secrets");
1758
- const scope = scopeOpts(mergeScopeOpts(secrets.opts(), opts));
1759
- const companyUid = await getEntityUid(token, scope);
1760
- const client = new SandboxRunnerClient();
1761
- const started = await client.startJob(token, {
1762
- companyUid,
1763
- secretNames: keys,
1764
- command,
1765
- });
1766
- const job =
1767
- started.status === "succeeded" || started.status === "failed"
1768
- ? await client.getJob(token, started.jobId)
1769
- : await client.pollJob(token, started.jobId);
1770
-
1771
- renderSandboxJobResult(job, keys);
1772
- const exitCode = typeof job.exitCode === "number" ? job.exitCode : undefined;
1773
- if (job.success === false || (exitCode !== undefined && exitCode !== 0) || job.status === "failed") {
1774
- if (exitCode !== undefined && exitCode !== 0) {
1775
- console.error(chalk.red(`Sandbox command failed with exit code ${exitCode}.`));
1776
- process.exit(exitCode);
1777
- }
1778
- console.error(
1779
- chalk.red(
1780
- job.error !== undefined
1781
- ? scrubSandboxOutput(job.error, keys)
1782
- : "Sandbox execution failed before the command produced an exit code.",
1783
- ),
1784
- );
1785
- process.exit(1);
1786
- }
1787
- } catch (err) {
1788
- console.error(
1789
- chalk.red("Error:"),
1790
- err instanceof Error ? scrubSandboxOutput(err.message) : scrubSandboxOutput(String(err)),
1791
- );
1792
- process.exit(1);
1793
- }
1794
- });
1795
-
1796
- secrets
1797
- .command("exec")
1798
- .description("Run a command with secrets injected as env vars")
1799
- .requiredOption("--only <keys>", "Secret names to inject (comma-separated; may be repeated) (required)", collectSecretNames)
1800
- .option("--script <path>", "Attach local script identity for script-locked secrets")
1801
- .option("--script-id <id>", "Stable script identifier approved by policy")
1802
- .allowUnknownOption(true)
1803
- .action(async (
1804
- _opts: { only: string[]; script?: string; scriptId?: string },
1805
- cmd: Command,
1806
- ) => {
1807
- try {
1808
- const rawArgs = cmd.args;
1809
- const dashIndex = process.argv.indexOf("--");
1810
- let childArgs: string[];
1811
- if (dashIndex !== -1) {
1812
- childArgs = process.argv.slice(dashIndex + 1);
1813
- } else {
1814
- childArgs = rawArgs;
1815
- }
1816
-
1817
- if (childArgs.length === 0) {
1818
- console.error(chalk.red("Error: no command specified. Usage: hq secrets exec --only KEY1,KEY2 -- <command>"));
1819
- process.exit(1);
1820
- }
1821
-
1822
- const keys = parseSecretNameList(_opts.only);
1823
-
1824
- const cred = await resolveVaultCredential();
1825
- const companyUid =
1826
- cred.kind === "api-key"
1827
- ? "__api_key__"
1828
- : await getEntityUid(cred.token, scopeOpts(secrets.opts()));
1829
-
1830
- const revealed = await loadRevealedSecrets(
1831
- cred.token,
1832
- companyUid,
1833
- keys,
1834
- cred.kind === "cognito"
1835
- ? await buildSecretUsage("exec", _opts.script, _opts.scriptId)
1836
- : undefined,
1837
- );
1838
-
1839
- const secretEnv: Record<string, string> = {};
1840
- for (const key of keys) {
1841
- const value = revealed.get(key);
1842
- // loadRevealedSecrets throws on any unresolved key, so a miss here is
1843
- // unreachable — guard rather than inject an `undefined` into the env.
1844
- if (value === undefined) {
1845
- throw new Error(`Failed to fetch secret '${key}': not returned by vault`);
1846
- }
1847
- secretEnv[key] = value;
1848
- }
1849
-
1850
- const [childCmd, ...childCmdArgs] = childArgs;
1851
- const child = spawn(childCmd, childCmdArgs, {
1852
- stdio: "inherit",
1853
- env: { ...process.env, ...secretEnv },
1854
- });
1855
-
1856
- child.on("error", (err) => {
1857
- console.error(chalk.red(`Failed to start command '${childCmd}': ${err.message}`));
1858
- process.exit(1);
1859
- });
1860
-
1861
- child.on("close", (code, signal) => {
1862
- if (signal) {
1863
- process.kill(process.pid, signal);
1864
- }
1865
- process.exit(code ?? 1);
1866
- });
1867
- } catch (err) {
1868
- console.error(
1869
- chalk.red("Error:"),
1870
- err instanceof Error ? err.message : String(err),
1871
- );
1872
- process.exit(1);
1873
- }
1874
- });
1875
-
1876
- secrets
1877
- .command("env")
1878
- .description("Print 'export KEY=VALUE' lines suitable for: source <(hq secrets env --only K1,K2)")
1879
- .requiredOption("--only <keys>", "Secret names to print (comma-separated; may be repeated) (required)", collectSecretNames)
1880
- .option("--script <path>", "Attach local script identity for script-locked secrets")
1881
- .option("--script-id <id>", "Stable script identifier approved by policy")
1882
- .action(async (
1883
- opts: { only: string[]; script?: string; scriptId?: string },
1884
- ) => {
1885
- try {
1886
- const redact = process.stdout.isTTY;
1887
- if (redact) {
1888
- console.error(
1889
- chalk.yellow(
1890
- "stdout is a terminal — values redacted. Use: source <(hq secrets env --only KEY1,KEY2)",
1891
- ),
1892
- );
1893
- }
1894
-
1895
- const keys = parseSecretNameList(opts.only);
1896
-
1897
- const cred = await resolveVaultCredential();
1898
- const companyUid =
1899
- cred.kind === "api-key"
1900
- ? "__api_key__"
1901
- : await getEntityUid(cred.token, scopeOpts(secrets.opts()));
1902
-
1903
- const revealed = await loadRevealedSecrets(
1904
- cred.token,
1905
- companyUid,
1906
- keys,
1907
- cred.kind === "cognito"
1908
- ? await buildSecretUsage("env", opts.script, opts.scriptId)
1909
- : undefined,
1910
- );
1911
-
1912
- for (const key of keys) {
1913
- const value = revealed.get(key);
1914
- // loadRevealedSecrets throws on any unresolved key, so a miss here is
1915
- // unreachable — guard rather than print an `undefined` export line.
1916
- if (value === undefined) {
1917
- throw new Error(`Failed to fetch secret '${key}': not returned by vault`);
1918
- }
1919
- const out = redact ? "[REDACTED]" : value;
1920
- process.stdout.write(`export ${key}=${shellSingleQuote(out)}\n`);
1921
- }
1922
- } catch (err) {
1923
- console.error(
1924
- chalk.red("Error:"),
1925
- err instanceof Error ? err.message : String(err),
1926
- );
1927
- process.exit(1);
1928
- }
1929
- });
1930
-
1931
- secrets
1932
- .command("generate-link <name>")
1933
- .description("Generate a one-time link for someone to submit a secret value")
1934
- .option("--expires <duration>", "Token expiry duration (e.g. 24h, 2d, 30m)", "24h")
1935
- .action(async (name: string, opts: { expires: string }) => {
1936
- try {
1937
- if (!SECRET_NAME_PATTERN.test(name)) {
1938
- console.error(chalk.red(`Invalid secret name '${name}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_API_KEY or DEV/MY_KEY)`));
1939
- process.exit(1);
1940
- }
1941
-
1942
- const expiresInMs = parseDuration(opts.expires);
1943
- if (expiresInMs === null) {
1944
- console.error(chalk.red(`Invalid duration '${opts.expires}'. Use formats like 30m, 12h, 2d.`));
1945
- process.exit(1);
1946
- }
1947
-
1948
- const MAX_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
1949
- if (expiresInMs > MAX_EXPIRY_MS) {
1950
- console.error(chalk.red("Maximum expiry is 7 days (7d)."));
1951
- process.exit(1);
1952
- }
1953
-
1954
- const token = await requireCognitoTokenForSecrets("secrets");
1955
- const companyUid = await getEntityUid(
1956
- token,
1957
- scopeOpts(secrets.opts()),
1958
- );
1959
-
1960
- const res = await vaultApiFetch({
1961
- token,
1962
- path: buildSecretNamePath(companyUid, name),
1963
- method: "POST",
1964
- body: { expiresInMs },
1965
- query: { action: "generate-token" },
1966
- });
1967
-
1968
- if (!res.ok) {
1969
- const body = await res.json().catch(() => ({}));
1970
- console.error(
1971
- chalk.red(`Failed to generate link: ${(body as Record<string, string>).error ?? res.statusText}`),
1972
- );
1973
- process.exit(1);
1974
- }
1975
-
1976
- const data = (await res.json()) as {
1977
- url: string;
1978
- expiresAt: string;
1979
- secretName: string;
1980
- };
1981
-
1982
- console.log(chalk.green("Secret input link generated:"));
1983
- console.log(`\n ${data.url}\n`);
1984
- console.log(chalk.dim(` Secret: ${data.secretName}`));
1985
- console.log(chalk.dim(` Expires: ${data.expiresAt}`));
1986
- console.log(chalk.dim(" One-time use — link is invalidated after first submission."));
1987
- } catch (err) {
1988
- console.error(
1989
- chalk.red("Error:"),
1990
- err instanceof Error ? err.message : String(err),
1991
- );
1992
- process.exit(1);
1993
- }
1994
- });
1995
-
1996
- secrets
1997
- .command("share <path>")
1998
- .description("Share a secret with an email address, group, or the entire company (@all)")
1999
- .requiredOption("--with <principal>", "Email address, group id, or @all (entire company) to share with")
2000
- .requiredOption("--permission <level>", "Permission level: read | write | admin")
2001
- .action(async (path: string, opts: { with: string; permission: string }) => {
2002
- try {
2003
- rejectIfPersonal(secrets.opts(), "share");
2004
-
2005
- if (!SECRET_NAME_PATTERN.test(path)) {
2006
- console.error(chalk.red(`Invalid secret path '${path}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
2007
- process.exit(1);
2008
- }
2009
-
2010
- if (!["read", "write", "admin"].includes(opts.permission)) {
2011
- console.error(chalk.red(`Invalid permission '${opts.permission}': must be one of read, write, admin`));
2012
- process.exit(1);
2013
- }
2014
-
2015
- const principal = parseSecretAclPrincipal(opts.with);
2016
- if (!principal) {
2017
- process.exit(1);
2018
- }
2019
-
2020
- const token = await requireCognitoTokenForSecrets("secrets");
2021
- const companyUid = await getEntityUid(
2022
- token,
2023
- scopeOpts(secrets.opts()),
2024
- );
2025
-
2026
- const res = await vaultApiFetch({
2027
- token,
2028
- path: `/secrets/${encodeURIComponent(companyUid)}/acl/grant`,
2029
- method: "POST",
2030
- body: {
2031
- path,
2032
- granteeType: principal.granteeType,
2033
- granteeId: principal.granteeId,
2034
- permission: opts.permission,
2035
- },
2036
- });
2037
-
2038
- if (!res.ok) {
2039
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2040
- if (res.status === 401) {
2041
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2042
- } else if (res.status === 403) {
2043
- console.error(chalk.red("Not authorized to share this secret"));
2044
- } else if (res.status === 404) {
2045
- console.error(chalk.red("ACL record not found for this path — has the secret been created?"));
2046
- } else if (res.status === 409) {
2047
- console.error(chalk.red("Concurrent modification — please retry"));
2048
- } else if (res.status >= 500) {
2049
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2050
- } else {
2051
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2052
- }
2053
- process.exit(1);
2054
- }
2055
-
2056
- console.log(chalk.green(`Shared '${path}' with ${describeSecretAclPrincipal(principal)} (${opts.permission})`));
2057
- } catch (err) {
2058
- console.error(
2059
- chalk.red("Error:"),
2060
- err instanceof Error ? err.message : String(err),
2061
- );
2062
- process.exit(1);
2063
- }
2064
- });
2065
-
2066
- secrets
2067
- .command("unshare <path>")
2068
- .description("Remove a grant from a secret")
2069
- .requiredOption("--from <principal>", "Email address, group id, or @all (entire company) to remove")
2070
- .action(async (path: string, opts: { from: string }) => {
2071
- try {
2072
- rejectIfPersonal(secrets.opts(), "unshare");
2073
-
2074
- if (!SECRET_NAME_PATTERN.test(path)) {
2075
- console.error(chalk.red(`Invalid secret path '${path}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
2076
- process.exit(1);
2077
- }
2078
-
2079
- const principal = parseSecretAclPrincipal(opts.from);
2080
- if (!principal) {
2081
- process.exit(1);
2082
- }
2083
-
2084
- const token = await requireCognitoTokenForSecrets("secrets");
2085
- const companyUid = await getEntityUid(
2086
- token,
2087
- scopeOpts(secrets.opts()),
2088
- );
2089
-
2090
- const res = await vaultApiFetch({
2091
- token,
2092
- path: `/secrets/${encodeURIComponent(companyUid)}/acl/revoke`,
2093
- method: "POST",
2094
- body: {
2095
- path,
2096
- granteeType: principal.granteeType,
2097
- granteeId: principal.granteeId,
2098
- },
2099
- });
2100
-
2101
- if (!res.ok) {
2102
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2103
- if (res.status === 401) {
2104
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2105
- } else if (res.status === 403) {
2106
- console.error(chalk.red("Not authorized to modify this secret's ACL"));
2107
- } else if (res.status === 404) {
2108
- console.log(chalk.green(`Grant already absent for '${path}' / ${describeSecretAclPrincipal(principal)}`));
2109
- return;
2110
- } else if (res.status >= 500) {
2111
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2112
- } else {
2113
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2114
- }
2115
- process.exit(1);
2116
- }
2117
-
2118
- console.log(chalk.green(`Removed grant for ${describeSecretAclPrincipal(principal)} on '${path}'`));
2119
- } catch (err) {
2120
- console.error(
2121
- chalk.red("Error:"),
2122
- err instanceof Error ? err.message : String(err),
2123
- );
2124
- process.exit(1);
2125
- }
2126
- });
2127
-
2128
- secrets
2129
- .command("acl <path>")
2130
- .description("Show the ACL (access control list) for a secret path")
2131
- .action(async (path: string) => {
2132
- try {
2133
- rejectIfPersonal(secrets.opts(), "acl");
2134
-
2135
- if (!SECRET_NAME_PATTERN.test(path)) {
2136
- console.error(chalk.red(`Invalid secret path '${path}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. MY_KEY or PROD/DB_PASSWORD)`));
2137
- process.exit(1);
2138
- }
2139
-
2140
- const token = await requireCognitoTokenForSecrets("secrets");
2141
- const companyUid = await getEntityUid(
2142
- token,
2143
- scopeOpts(secrets.opts()),
2144
- );
2145
-
2146
- const secretPath = path;
2147
- const res = await vaultApiFetch({
2148
- token,
2149
- path: `/secrets/${encodeURIComponent(companyUid)}/acl`,
2150
- query: { path: secretPath },
2151
- });
2152
-
2153
- if (!res.ok) {
2154
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2155
- if (res.status === 401) {
2156
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2157
- } else if (res.status === 403) {
2158
- console.error(chalk.red("Not authorized to view this secret's ACL"));
2159
- } else if (res.status === 404) {
2160
- console.error(chalk.red(`No ACL record exists for '${path}'`));
2161
- } else if (res.status >= 500) {
2162
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2163
- } else {
2164
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2165
- }
2166
- process.exit(1);
2167
- }
2168
-
2169
- const data = (await res.json()) as {
2170
- acl: {
2171
- itemType: "ACL";
2172
- companyUid: string;
2173
- path: string;
2174
- creatorUid: string;
2175
- open?: boolean;
2176
- entries: Array<{
2177
- granteeType: string;
2178
- granteeId: string;
2179
- permission: string;
2180
- grantedBy: string;
2181
- grantedAt: string;
2182
- }>;
2183
- createdAt: string;
2184
- updatedAt: string;
2185
- schemaVersion: number;
2186
- };
2187
- };
2188
-
2189
- const acl = data.acl;
2190
- const aclStatus = acl.open ? "open" : "restricted";
2191
-
2192
- console.log(chalk.green(`ACL for ${acl.path} (${aclStatus})`));
2193
- console.log(`Creator: ${acl.creatorUid}`);
2194
-
2195
- if (acl.entries.length === 0) {
2196
- if (acl.open) {
2197
- console.log(chalk.gray("Open ACL — all active members have read access."));
2198
- } else {
2199
- console.log(chalk.gray("No explicit grants — only creator has access."));
2200
- }
2201
- return;
2202
- }
2203
-
2204
- console.log("Entries:");
2205
- const TYPE_W = Math.max(4, ...acl.entries.map((e) => e.granteeType.length));
2206
- const GRANTEE_W = Math.max(7, ...acl.entries.map((e) => e.granteeId.length));
2207
- const PERM_W = Math.max(10, ...acl.entries.map((e) => e.permission.length));
2208
- const BY_W = Math.max(10, ...acl.entries.map((e) => e.grantedBy.length));
2209
- const tableHeader = [
2210
- "TYPE".padEnd(TYPE_W),
2211
- "GRANTEE".padEnd(GRANTEE_W),
2212
- "PERMISSION".padEnd(PERM_W),
2213
- "GRANTED_BY".padEnd(BY_W),
2214
- "GRANTED_AT",
2215
- ].join(" ");
2216
- console.log(chalk.bold(tableHeader));
2217
- for (const e of acl.entries) {
2218
- const grantedAt = e.grantedAt.slice(0, 10);
2219
- console.log(
2220
- [
2221
- e.granteeType.padEnd(TYPE_W),
2222
- e.granteeId.padEnd(GRANTEE_W),
2223
- e.permission.padEnd(PERM_W),
2224
- e.grantedBy.padEnd(BY_W),
2225
- grantedAt,
2226
- ].join(" "),
2227
- );
2228
- }
2229
- } catch (err) {
2230
- console.error(
2231
- chalk.red("Error:"),
2232
- err instanceof Error ? err.message : String(err),
2233
- );
2234
- process.exit(1);
2235
- }
2236
- });
2237
-
2238
- const cache = secrets
2239
- .command("cache")
2240
- .description("Manage the local secrets cache");
2241
-
2242
- cache
2243
- .command("clear")
2244
- .description("Clear all cached secrets")
2245
- .action(async () => {
2246
- clearAllCache();
2247
- console.log(chalk.green("Secrets cache cleared."));
2248
- });
2249
- }