@indigoai-us/hq-cli 5.77.13 → 5.78.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 (307) hide show
  1. package/CHANGELOG.md +34 -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/members.js +16 -5
  31. package/dist/commands/pack-install.d.ts +14 -0
  32. package/dist/commands/pack-install.js +51 -2
  33. package/dist/commands/pkg-install.js +43 -0
  34. package/dist/commands/run.js +8 -0
  35. package/dist/commands/secrets.js +125 -65
  36. package/dist/main.js +6 -0
  37. package/dist/utils/api-key-command-gate.d.ts +45 -0
  38. package/dist/utils/api-key-command-gate.js +51 -0
  39. package/dist/utils/hq-roots.d.ts +91 -0
  40. package/dist/utils/hq-roots.js +212 -0
  41. package/dist/utils/resolve-vault-credential.d.ts +63 -3
  42. package/dist/utils/resolve-vault-credential.js +152 -6
  43. package/dist/utils/run-bundled-script.d.ts +66 -0
  44. package/dist/utils/run-bundled-script.js +80 -0
  45. package/dist/utils/vault-api.d.ts +21 -0
  46. package/dist/utils/vault-api.js +74 -3
  47. package/package.json +7 -1
  48. package/.claude/policies/hq-cli-interactive-reads-use-sts-vend.md +0 -49
  49. package/.github/workflows/ci.yml +0 -46
  50. package/.github/workflows/publish.yml +0 -36
  51. package/.github/workflows/scripts/smoke-test-pkg.sh +0 -97
  52. package/e2e/cli.test.ts +0 -128
  53. package/eslint.config.js +0 -37
  54. package/pnpm-workspace.yaml +0 -4
  55. package/scripts/chmod-bins.mjs +0 -49
  56. package/scripts/generate-dsn.mjs +0 -26
  57. package/scripts/generate-scan-packages-table.mjs +0 -113
  58. package/scripts/smoke-sources-signals.sh +0 -103
  59. package/src/bin/hq-auth-refresh.ts +0 -43
  60. package/src/cli-version.ts +0 -13
  61. package/src/commands/__fixtures__/make-tar.ts +0 -126
  62. package/src/commands/_patterns.ts +0 -10
  63. package/src/commands/add.ts +0 -75
  64. package/src/commands/agents.test.ts +0 -527
  65. package/src/commands/agents.ts +0 -923
  66. package/src/commands/api-keys.test.ts +0 -291
  67. package/src/commands/api-keys.ts +0 -382
  68. package/src/commands/artifact-verify.test.ts +0 -177
  69. package/src/commands/auth.test.ts +0 -82
  70. package/src/commands/auth.ts +0 -213
  71. package/src/commands/billing.test.ts +0 -158
  72. package/src/commands/billing.ts +0 -146
  73. package/src/commands/channels.test.ts +0 -74
  74. package/src/commands/channels.ts +0 -91
  75. package/src/commands/cloud-demote.test.ts +0 -401
  76. package/src/commands/cloud-demote.ts +0 -278
  77. package/src/commands/cloud-provision.test.ts +0 -1117
  78. package/src/commands/cloud-provision.ts +0 -942
  79. package/src/commands/cloud.pull-all.test.ts +0 -711
  80. package/src/commands/cloud.pull-per-company.test.ts +0 -188
  81. package/src/commands/cloud.push-all.test.ts +0 -485
  82. package/src/commands/cloud.scope-excluded-warning.test.ts +0 -22
  83. package/src/commands/cloud.selectors.test.ts +0 -208
  84. package/src/commands/cloud.status.test.ts +0 -160
  85. package/src/commands/cloud.test.ts +0 -41
  86. package/src/commands/cloud.ts +0 -2130
  87. package/src/commands/company.test.ts +0 -202
  88. package/src/commands/company.ts +0 -148
  89. package/src/commands/creators.test.ts +0 -60
  90. package/src/commands/creators.ts +0 -117
  91. package/src/commands/crm.test.ts +0 -179
  92. package/src/commands/crm.ts +0 -236
  93. package/src/commands/db-migrate.ts +0 -55
  94. package/src/commands/db-provision.ts +0 -114
  95. package/src/commands/db-sql.ts +0 -124
  96. package/src/commands/db-status.ts +0 -108
  97. package/src/commands/db.ts +0 -26
  98. package/src/commands/dm.test.ts +0 -748
  99. package/src/commands/dm.ts +0 -1226
  100. package/src/commands/feedback.test.ts +0 -413
  101. package/src/commands/feedback.ts +0 -169
  102. package/src/commands/files-browse.test.ts +0 -1249
  103. package/src/commands/files-browse.ts +0 -1506
  104. package/src/commands/files-delete.test.ts +0 -484
  105. package/src/commands/files-recovery.test.ts +0 -370
  106. package/src/commands/files.test.ts +0 -722
  107. package/src/commands/files.ts +0 -1446
  108. package/src/commands/group-grants.test.ts +0 -330
  109. package/src/commands/group-grants.ts +0 -455
  110. package/src/commands/groups.test.ts +0 -44
  111. package/src/commands/groups.ts +0 -368
  112. package/src/commands/integrations.test.ts +0 -633
  113. package/src/commands/integrations.ts +0 -507
  114. package/src/commands/list.ts +0 -85
  115. package/src/commands/login.ts +0 -52
  116. package/src/commands/logout.ts +0 -30
  117. package/src/commands/marketplace-install.test.ts +0 -543
  118. package/src/commands/marketplace-security.test.ts +0 -646
  119. package/src/commands/mcp-registration.test.ts +0 -2787
  120. package/src/commands/mcp-registration.ts +0 -2612
  121. package/src/commands/mcp-status.test.ts +0 -483
  122. package/src/commands/mcp-status.ts +0 -575
  123. package/src/commands/mcp-status.us011.test.ts +0 -243
  124. package/src/commands/meetings.test.ts +0 -522
  125. package/src/commands/meetings.ts +0 -789
  126. package/src/commands/members.test.ts +0 -1474
  127. package/src/commands/members.ts +0 -1181
  128. package/src/commands/onboard-identity-guard.test.ts +0 -99
  129. package/src/commands/onboard-identity-guard.ts +0 -103
  130. package/src/commands/onboard-join.test.ts +0 -96
  131. package/src/commands/onboard-join.ts +0 -101
  132. package/src/commands/onboard-warning.test.ts +0 -26
  133. package/src/commands/onboard-warning.ts +0 -12
  134. package/src/commands/onboard.ts +0 -267
  135. package/src/commands/outposts-heartbeat.test.ts +0 -299
  136. package/src/commands/outposts-heartbeat.ts +0 -310
  137. package/src/commands/outposts-replica-sync.test.ts +0 -272
  138. package/src/commands/outposts-self-deploy.test.ts +0 -243
  139. package/src/commands/outposts.test.ts +0 -1039
  140. package/src/commands/outposts.ts +0 -1935
  141. package/src/commands/pack-install-secret-authorization.test.ts +0 -115
  142. package/src/commands/pack-install.test.ts +0 -1469
  143. package/src/commands/pack-install.ts +0 -2247
  144. package/src/commands/pack-update-cache.test.ts +0 -149
  145. package/src/commands/packs.test.ts +0 -88
  146. package/src/commands/packs.ts +0 -622
  147. package/src/commands/people.test.ts +0 -807
  148. package/src/commands/people.ts +0 -422
  149. package/src/commands/pkg-install.dispatch.test.ts +0 -71
  150. package/src/commands/pkg-install.ts +0 -215
  151. package/src/commands/pkg-list.test.ts +0 -79
  152. package/src/commands/pkg-list.ts +0 -13
  153. package/src/commands/pkg-remove.ts +0 -71
  154. package/src/commands/pkg-update.ts +0 -189
  155. package/src/commands/publish.test.ts +0 -650
  156. package/src/commands/publish.ts +0 -580
  157. package/src/commands/reindex.test.ts +0 -259
  158. package/src/commands/reindex.ts +0 -274
  159. package/src/commands/rescue.test.ts +0 -39
  160. package/src/commands/rescue.ts +0 -210
  161. package/src/commands/run.env-local.test.ts +0 -88
  162. package/src/commands/run.test.ts +0 -45
  163. package/src/commands/run.ts +0 -184
  164. package/src/commands/safe-extract.test.ts +0 -459
  165. package/src/commands/safe-extract.ts +0 -444
  166. package/src/commands/secrets-scope.test.ts +0 -56
  167. package/src/commands/secrets-scope.ts +0 -32
  168. package/src/commands/secrets.parse-destination.test.ts +0 -38
  169. package/src/commands/secrets.test.ts +0 -2037
  170. package/src/commands/secrets.ts +0 -2240
  171. package/src/commands/signals.ts +0 -351
  172. package/src/commands/skill.test.ts +0 -770
  173. package/src/commands/skill.ts +0 -796
  174. package/src/commands/sources.ts +0 -362
  175. package/src/commands/sync-mode.test.ts +0 -366
  176. package/src/commands/sync-mode.ts +0 -387
  177. package/src/commands/sync-narrow.test.ts +0 -633
  178. package/src/commands/sync-narrow.ts +0 -555
  179. package/src/commands/sync.ts +0 -165
  180. package/src/commands/team-sync.ts +0 -628
  181. package/src/commands/update.ts +0 -71
  182. package/src/commands/whoami.ts +0 -83
  183. package/src/commands/workers.test.ts +0 -158
  184. package/src/commands/workers.ts +0 -301
  185. package/src/index.test.ts +0 -32
  186. package/src/index.ts +0 -20
  187. package/src/lib/db/control-plane.test.ts +0 -59
  188. package/src/lib/db/control-plane.ts +0 -113
  189. package/src/lib/db/local.test.ts +0 -81
  190. package/src/lib/db/local.ts +0 -148
  191. package/src/lib/db/migrate.test.ts +0 -133
  192. package/src/lib/db/migrate.ts +0 -137
  193. package/src/lib/db/paths.test.ts +0 -112
  194. package/src/lib/db/paths.ts +0 -128
  195. package/src/lib/db/remote-engine.test.ts +0 -44
  196. package/src/lib/db/remote-engine.ts +0 -148
  197. package/src/lib/db/remote-sql.test.ts +0 -32
  198. package/src/lib/db/remote-sql.ts +0 -62
  199. package/src/lib/db/sql.test.ts +0 -106
  200. package/src/lib/db/sql.ts +0 -192
  201. package/src/lib/hq-cloud-dep.smoke.test.ts +0 -75
  202. package/src/lib/local-tree-diff.test.ts +0 -301
  203. package/src/lib/local-tree-diff.ts +0 -362
  204. package/src/lib/narrow-hint-banner.test.ts +0 -235
  205. package/src/lib/narrow-hint-banner.ts +0 -212
  206. package/src/lib/plan-limit-nag.test.ts +0 -317
  207. package/src/lib/plan-limit-nag.ts +0 -264
  208. package/src/main.ts +0 -371
  209. package/src/node-preflight.test.ts +0 -60
  210. package/src/node-preflight.ts +0 -67
  211. package/src/outpost/session-heartbeat-bounds.test.ts +0 -195
  212. package/src/outpost/session-heartbeat-guard.test.ts +0 -105
  213. package/src/outpost/session-heartbeat-publisher.test.ts +0 -178
  214. package/src/outpost/session-heartbeat-publisher.ts +0 -186
  215. package/src/outpost/session-heartbeat-retain-guard.test.ts +0 -126
  216. package/src/outpost/session-heartbeat.test.ts +0 -459
  217. package/src/outpost/session-heartbeat.ts +0 -877
  218. package/src/packaging.test.ts +0 -109
  219. package/src/run/__fixtures__/discover-schemas/example.env.schema +0 -4
  220. package/src/run/discover-schemas.test.ts +0 -153
  221. package/src/run/discover-schemas.ts +0 -79
  222. package/src/run/hq-plugin.test.ts +0 -371
  223. package/src/run/hq-plugin.ts +0 -277
  224. package/src/run/varlock-shape.test.ts +0 -57
  225. package/src/schemas/hq-package.schema.json +0 -155
  226. package/src/sentry-before-send.test.ts +0 -359
  227. package/src/sentry-before-send.ts +0 -221
  228. package/src/sentry-epipe.test.ts +0 -37
  229. package/src/sentry-release.test.ts +0 -54
  230. package/src/sentry.test.ts +0 -24
  231. package/src/sentry.ts +0 -54
  232. package/src/strategies/link.ts +0 -62
  233. package/src/strategies/merge.ts +0 -142
  234. package/src/types.ts +0 -146
  235. package/src/utils/__fixtures__/scan-packages.generated-block.sh +0 -23
  236. package/src/utils/auth-error.test.ts +0 -40
  237. package/src/utils/auth-error.ts +0 -42
  238. package/src/utils/billing-gate.test.ts +0 -95
  239. package/src/utils/billing-gate.ts +0 -228
  240. package/src/utils/breadcrumb-buffer.ts +0 -18
  241. package/src/utils/cli-telemetry.test.ts +0 -153
  242. package/src/utils/cli-telemetry.ts +0 -61
  243. package/src/utils/cognito-session.machine.test.ts +0 -109
  244. package/src/utils/cognito-session.refresh.test.ts +0 -84
  245. package/src/utils/cognito-session.test.ts +0 -328
  246. package/src/utils/cognito-session.ts +0 -448
  247. package/src/utils/company-selection-error.test.ts +0 -42
  248. package/src/utils/company-selection-error.ts +0 -45
  249. package/src/utils/contribution-table.ts +0 -83
  250. package/src/utils/environmental-error.test.ts +0 -45
  251. package/src/utils/environmental-error.ts +0 -39
  252. package/src/utils/epipe.test.ts +0 -28
  253. package/src/utils/epipe.ts +0 -29
  254. package/src/utils/expected-cli-error.test.ts +0 -28
  255. package/src/utils/expected-cli-error.ts +0 -39
  256. package/src/utils/feedback-diagnostics.test.ts +0 -183
  257. package/src/utils/feedback-diagnostics.ts +0 -123
  258. package/src/utils/feedback-screenshots.test.ts +0 -134
  259. package/src/utils/feedback-screenshots.ts +0 -124
  260. package/src/utils/feedback-versions.test.ts +0 -98
  261. package/src/utils/feedback-versions.ts +0 -68
  262. package/src/utils/git.ts +0 -74
  263. package/src/utils/integrity.ts +0 -59
  264. package/src/utils/intercepted-process-exit.test.ts +0 -37
  265. package/src/utils/intercepted-process-exit.ts +0 -36
  266. package/src/utils/login-provider.test.ts +0 -42
  267. package/src/utils/login-provider.ts +0 -30
  268. package/src/utils/manifest.test.ts +0 -167
  269. package/src/utils/manifest.ts +0 -131
  270. package/src/utils/pack-contributions.test.ts +0 -603
  271. package/src/utils/pack-contributions.ts +0 -450
  272. package/src/utils/people.ts +0 -215
  273. package/src/utils/registry-client.ts +0 -204
  274. package/src/utils/registry.ts +0 -90
  275. package/src/utils/resolve-vault-credential.test.ts +0 -69
  276. package/src/utils/resolve-vault-credential.ts +0 -60
  277. package/src/utils/sandbox-runner-client.test.ts +0 -279
  278. package/src/utils/sandbox-runner-client.ts +0 -260
  279. package/src/utils/secrets-cache.ts +0 -183
  280. package/src/utils/sentry-identity.ts +0 -45
  281. package/src/utils/settle-with-timeout.test.ts +0 -21
  282. package/src/utils/settle-with-timeout.ts +0 -22
  283. package/src/utils/user-yaml-error.test.ts +0 -24
  284. package/src/utils/user-yaml-error.ts +0 -30
  285. package/src/utils/vault-api.test.ts +0 -536
  286. package/src/utils/vault-api.ts +0 -382
  287. package/src/utils/version-check.test.ts +0 -176
  288. package/src/utils/version-check.ts +0 -155
  289. package/src/utils/version-gate.test.ts +0 -1024
  290. package/src/utils/version-gate.ts +0 -702
  291. package/test/commands/db-tenant-isolation.test.ts +0 -94
  292. package/test/commands/db.test.ts +0 -85
  293. package/test/commands/signals.test.ts +0 -207
  294. package/test/commands/sources.test.ts +0 -231
  295. package/test/e2e/smoke-install-mcp.sh +0 -113
  296. package/test/fixtures/hq-pack-smoke-mcp/mcp/smoke-http.json +0 -1
  297. package/test/fixtures/hq-pack-smoke-mcp/package.yaml +0 -11
  298. package/test/fixtures/signals/action_item/sample.md +0 -16
  299. package/test/fixtures/signals/summary/sample.md +0 -12
  300. package/test/fixtures/sources/meetings/sample.md +0 -25
  301. package/test/helpers/cli-runner.ts +0 -150
  302. package/test/helpers/s3-list-mock.ts +0 -79
  303. package/test/helpers/vault-service-mock.ts +0 -295
  304. package/test/sources-signals/smoke.test.ts +0 -228
  305. package/tsconfig.json +0 -20
  306. package/vitest.config.ts +0 -11
  307. package/vitest.e2e.config.ts +0 -7
@@ -1,2240 +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
- const res = await vaultApiFetch({
1059
- token: cred.token,
1060
- path: "/v1/keys/secrets/fetch",
1061
- method: "POST",
1062
- body: { name },
1063
- });
1064
- const body = (await res.json().catch(() => ({}))) as Record<
1065
- string,
1066
- unknown
1067
- >;
1068
- if (!res.ok) {
1069
- if (res.status === 403 && body.highSecurity === true) {
1070
- console.error(chalk.red(highSecuritySandboxOnlyMessage(name)));
1071
- process.exit(1);
1072
- }
1073
- console.error(
1074
- chalk.red(
1075
- `Failed to get secret: ${extractApiMessage(body, res.statusText)}`,
1076
- ),
1077
- );
1078
- process.exit(1);
1079
- }
1080
- const secret =
1081
- typeof body.secret === "object" && body.secret !== null
1082
- ? (body.secret as SecretGetResponse["secret"] & {
1083
- value?: string;
1084
- })
1085
- : null;
1086
- if (!secret || typeof secret.name !== "string") {
1087
- console.error(chalk.red("Failed to get secret: malformed response"));
1088
- process.exit(1);
1089
- }
1090
- console.log(chalk.bold(`Secret: ${secret.name}`));
1091
- if (secret.lastModifiedDate) {
1092
- console.log(` Last Modified: ${secret.lastModifiedDate}`);
1093
- }
1094
- if (secret.version != null) {
1095
- console.log(` Version: ${secret.version}`);
1096
- }
1097
- console.log(` Tier: ${normalizeSecretTier(secret.tier)}`);
1098
- console.log(
1099
- ` Script Lock: ${normalizeScriptLockMode(secret.scriptLock?.mode)}`,
1100
- );
1101
- if (opts.reveal) {
1102
- if (typeof secret.value !== "string") {
1103
- console.error(
1104
- chalk.red(
1105
- "Failed to get secret: reveal requested but response omitted secret.value",
1106
- ),
1107
- );
1108
- process.exit(1);
1109
- }
1110
- console.log(` Value: ${secret.value}`);
1111
- } else {
1112
- console.log(` Value: ${chalk.dim("[REDACTED]")}`);
1113
- }
1114
- return;
1115
- }
1116
-
1117
- const token = cred.token;
1118
- const companyUid = await getEntityUid(
1119
- token,
1120
- scopeOpts(secrets.opts()),
1121
- );
1122
-
1123
- const res = await vaultApiFetch({
1124
- token,
1125
- path: buildSecretNamePath(companyUid, name),
1126
- });
1127
-
1128
- if (!res.ok) {
1129
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1130
- // High-security secrets cannot be revealed locally. Surface the
1131
- // hosted execution path rather than a raw 4xx; `--script` never
1132
- // overrides this boundary.
1133
- if (res.status === 403 && body.highSecurity === true) {
1134
- console.error(chalk.red(highSecuritySandboxOnlyMessage(name)));
1135
- process.exit(1);
1136
- }
1137
- console.error(
1138
- chalk.red(`Failed to get secret: ${extractApiMessage(body, res.statusText)}`),
1139
- );
1140
- process.exit(1);
1141
- }
1142
-
1143
- const data = (await res.json()) as SecretGetResponse;
1144
-
1145
- let revealedValue: string | undefined;
1146
- let revealError: string | null = null;
1147
- if (opts.reveal) {
1148
- try {
1149
- revealedValue = (
1150
- await loadRevealedSecrets(token, companyUid, [name], await buildSecretUsage("reveal"))
1151
- ).get(name);
1152
- } catch (err) {
1153
- revealError = err instanceof Error ? err.message : String(err);
1154
- }
1155
- }
1156
-
1157
- const s = data.secret;
1158
- console.log(chalk.bold(`Secret: ${s.name}`));
1159
- if (s.lastModifiedDate) {
1160
- console.log(` Last Modified: ${s.lastModifiedDate}`);
1161
- }
1162
- if (s.version != null) {
1163
- console.log(` Version: ${s.version}`);
1164
- }
1165
- console.log(` Tier: ${normalizeSecretTier(s.tier)}`);
1166
- console.log(
1167
- ` Script Lock: ${normalizeScriptLockMode(s.scriptLock?.mode)}`,
1168
- );
1169
- if (opts.reveal && revealedValue != null) {
1170
- console.log(` Value: ${revealedValue}`);
1171
- } else {
1172
- console.log(` Value: ${chalk.dim("[REDACTED]")}`);
1173
- }
1174
- if (revealError) {
1175
- console.error(chalk.red(revealError));
1176
- process.exit(1);
1177
- }
1178
- } catch (err) {
1179
- console.error(
1180
- chalk.red("Error:"),
1181
- err instanceof Error ? err.message : String(err),
1182
- );
1183
- process.exit(1);
1184
- }
1185
- });
1186
-
1187
- // HQ-4H: existence probe via the HEAD route. Optional-credential readers
1188
- // should HEAD-first so a missing secret no longer fires a spurious GET-404
1189
- // Sentry warning server-side: `hq secrets exists FOO && hq secrets get FOO …`.
1190
- // A HEAD never decrypts or reveals the value.
1191
- //
1192
- // Exit codes are designed for shell chaining:
1193
- // 0 → secret exists (200)
1194
- // 1 → secret is absent (404) — the normal "no" answer, NOT an error
1195
- // 2 → a real failure (auth/network/permission) — distinct from absence so
1196
- // `&&` chains don't mistake an outage for "absent and proceed"
1197
- secrets
1198
- .command("exists <name>")
1199
- .description("Check whether a secret exists (HEAD; exit 0=present, 1=absent, 2=error)")
1200
- .option("--quiet", "Suppress the present/absent line (use the exit code only)")
1201
- .action(async (name: string, opts: { quiet?: boolean }) => {
1202
- try {
1203
- const token = await requireCognitoTokenForSecrets("secrets exists");
1204
- const companyUid = await getEntityUid(
1205
- token,
1206
- scopeOpts(secrets.opts()),
1207
- );
1208
-
1209
- const res = await vaultApiFetch({
1210
- token,
1211
- method: "HEAD",
1212
- path: buildSecretNamePath(companyUid, name),
1213
- });
1214
-
1215
- if (res.status === 200) {
1216
- if (!opts.quiet) console.log(chalk.green(`exists: ${name}`));
1217
- process.exit(0);
1218
- }
1219
- if (res.status === 404) {
1220
- if (!opts.quiet) console.log(chalk.dim(`absent: ${name}`));
1221
- process.exit(1);
1222
- }
1223
- // Any other status (401/403/5xx) is a real failure, not an absence.
1224
- console.error(
1225
- chalk.red(
1226
- `Failed to check secret '${name}': HTTP ${res.status} ${res.statusText}`,
1227
- ),
1228
- );
1229
- process.exit(2);
1230
- } catch (err) {
1231
- console.error(
1232
- chalk.red("Error:"),
1233
- err instanceof Error ? err.message : String(err),
1234
- );
1235
- process.exit(2);
1236
- }
1237
- });
1238
-
1239
- secrets
1240
- .command("list")
1241
- .description("List all secrets for the company (including nested path-based names)")
1242
- .option(
1243
- "--prefix <path>",
1244
- "Filter by path prefix (e.g. DEV or DEV/SUB); omit or pass empty string for all secrets",
1245
- )
1246
- .action(async (opts: { prefix?: string }) => {
1247
- try {
1248
- // MUST match SECRET_PREFIX_PATTERN in hq-pro/src/vault-service/handlers/secrets.ts
1249
- let normalizedPrefix: string | undefined;
1250
- if (opts.prefix) {
1251
- const normalized = opts.prefix.replace(/^\/+|\/+$/g, "");
1252
- if (
1253
- normalized.length === 0 ||
1254
- !SECRET_NAME_PATTERN.test(normalized)
1255
- ) {
1256
- console.error(
1257
- chalk.red(
1258
- `Invalid prefix '${opts.prefix}': must match ^[A-Z][A-Z0-9_]*(/[A-Z][A-Z0-9_]+)*$ (e.g. DEV or DEV/SUB)`,
1259
- ),
1260
- );
1261
- process.exit(1);
1262
- }
1263
- normalizedPrefix = normalized;
1264
- }
1265
-
1266
- const token = await requireCognitoTokenForSecrets("secrets list");
1267
- const scope = scopeOpts(secrets.opts());
1268
- const companyUid = await getEntityUid(token, scope);
1269
- const scopeLabel = describeSecretsScope({
1270
- personal: scope.personal,
1271
- companySlug: scope.companySlug,
1272
- companyUid,
1273
- });
1274
-
1275
- const query: Record<string, string> = {};
1276
- if (normalizedPrefix) {
1277
- query.prefix = normalizedPrefix;
1278
- }
1279
-
1280
- const res = await vaultApiFetch({
1281
- token,
1282
- path: `/secrets/${encodeURIComponent(companyUid)}`,
1283
- query: Object.keys(query).length > 0 ? query : undefined,
1284
- });
1285
-
1286
- if (!res.ok) {
1287
- const body = await res.json().catch(() => ({}));
1288
- console.error(
1289
- chalk.red(`Failed to list secrets: ${(body as Record<string, string>).error ?? res.statusText}`),
1290
- );
1291
- process.exit(1);
1292
- }
1293
-
1294
- const data = (await res.json()) as {
1295
- secrets: Array<
1296
- {
1297
- name: string;
1298
- lastModifiedDate?: string;
1299
- version?: number;
1300
- permission?: "admin" | "write" | "read";
1301
- } & SecretMetadata
1302
- >;
1303
- };
1304
-
1305
- if (data.secrets.length === 0) {
1306
- console.log(chalk.dim(formatSecretsListEmpty(scopeLabel)));
1307
- return;
1308
- }
1309
-
1310
- const nameWidth = Math.max(4, ...data.secrets.map((s) => s.name.length));
1311
- const hasPermission = data.secrets.some((s) => s.permission !== undefined);
1312
- const tierWidth = Math.max(
1313
- 4,
1314
- ...data.secrets.map((s) => normalizeSecretTier(s.tier).length),
1315
- );
1316
- const scriptLockWidth = Math.max(
1317
- 11,
1318
- ...data.secrets.map((s) => normalizeScriptLockMode(s.scriptLock?.mode).length),
1319
- );
1320
- if (hasPermission) {
1321
- const accessWidth = Math.max(6, ...data.secrets.map((s) => (s.permission ?? "-").length));
1322
- const header = `${"NAME".padEnd(nameWidth)} ${"ACCESS".padEnd(accessWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
1323
- console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
1324
- console.log(chalk.bold(header));
1325
- for (const s of data.secrets) {
1326
- const access = s.permission ?? "-";
1327
- const tier = normalizeSecretTier(s.tier);
1328
- const scriptLock = normalizeScriptLockMode(s.scriptLock?.mode);
1329
- const modified = s.lastModifiedDate ?? "-";
1330
- console.log(`${s.name.padEnd(nameWidth)} ${access.padEnd(accessWidth)} ${tier.padEnd(tierWidth)} ${scriptLock.padEnd(scriptLockWidth)} ${modified}`);
1331
- }
1332
- } else {
1333
- const header = `${"NAME".padEnd(nameWidth)} ${"TIER".padEnd(tierWidth)} ${"SCRIPT LOCK".padEnd(scriptLockWidth)} LAST MODIFIED`;
1334
- console.log(chalk.dim(formatSecretsListHeader(scopeLabel)));
1335
- console.log(chalk.bold(header));
1336
- for (const s of data.secrets) {
1337
- const tier = normalizeSecretTier(s.tier);
1338
- const scriptLock = normalizeScriptLockMode(s.scriptLock?.mode);
1339
- const modified = s.lastModifiedDate ?? "-";
1340
- console.log(`${s.name.padEnd(nameWidth)} ${tier.padEnd(tierWidth)} ${scriptLock.padEnd(scriptLockWidth)} ${modified}`);
1341
- }
1342
- }
1343
- } catch (err) {
1344
- console.error(
1345
- chalk.red("Error:"),
1346
- err instanceof Error ? err.message : String(err),
1347
- );
1348
- process.exit(1);
1349
- }
1350
- });
1351
-
1352
- const policy = secrets
1353
- .command("policy")
1354
- .description("View or update secret access policy");
1355
-
1356
- policy
1357
- .command("get <path>")
1358
- .description("Show the policy for a secret path")
1359
- .action(async (secretPath: string) => {
1360
- try {
1361
- rejectIfPersonal(secrets.opts(), "policy get");
1362
-
1363
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1364
- 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)`));
1365
- process.exit(1);
1366
- }
1367
-
1368
- const token = await requireCognitoTokenForSecrets("secrets");
1369
- const companyUid = await getEntityUid(
1370
- token,
1371
- scopeOpts(secrets.opts()),
1372
- );
1373
- const res = await vaultApiFetch({
1374
- token,
1375
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1376
- query: { path: secretPath },
1377
- });
1378
-
1379
- if (res.status === 404) {
1380
- renderPolicySummary(
1381
- normalizePolicyRecord(secretPath, { policy: { path: secretPath } }),
1382
- );
1383
- return;
1384
- }
1385
- if (!res.ok) {
1386
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1387
- console.error(
1388
- chalk.red(`Failed to get policy: ${extractApiMessage(body, res.statusText)}`),
1389
- );
1390
- process.exit(1);
1391
- }
1392
-
1393
- const data = (await res.json()) as SecretPolicyResponse;
1394
- renderPolicySummary(normalizePolicyRecord(secretPath, data));
1395
- } catch (err) {
1396
- console.error(
1397
- chalk.red("Error:"),
1398
- err instanceof Error ? err.message : String(err),
1399
- );
1400
- process.exit(1);
1401
- }
1402
- });
1403
-
1404
- policy
1405
- .command("set <path>")
1406
- .description("Set the policy for a secret path")
1407
- .option("--tier <tier>", "Secret tier: standard | sensitive | nuclear")
1408
- .option("--lock-script <mode>", "Script-lock mode: off | enforce")
1409
- .action(async (
1410
- secretPath: string,
1411
- opts: { tier?: string; lockScript?: string },
1412
- ) => {
1413
- try {
1414
- rejectIfPersonal(secrets.opts(), "policy set");
1415
-
1416
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1417
- 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)`));
1418
- process.exit(1);
1419
- }
1420
-
1421
- const tier = opts.tier;
1422
- if (
1423
- tier !== undefined &&
1424
- tier !== "standard" &&
1425
- tier !== "sensitive" &&
1426
- tier !== "nuclear"
1427
- ) {
1428
- console.error(chalk.red(`Invalid tier '${tier}': must be one of standard, sensitive, nuclear`));
1429
- process.exit(1);
1430
- }
1431
-
1432
- let scriptLock:
1433
- | { mode: SecretScriptLockMode }
1434
- | undefined;
1435
- if (opts.lockScript !== undefined) {
1436
- if (opts.lockScript === "off") {
1437
- scriptLock = { mode: "off" };
1438
- } else if (opts.lockScript === "enforce") {
1439
- scriptLock = { mode: "enforced" };
1440
- } else {
1441
- console.error(chalk.red(`Invalid script lock mode '${opts.lockScript}': must be one of off, enforce`));
1442
- process.exit(1);
1443
- }
1444
- }
1445
-
1446
- if (tier === undefined && scriptLock === undefined) {
1447
- console.error(chalk.red("Error: provide at least one of --tier or --lock-script."));
1448
- process.exit(1);
1449
- }
1450
-
1451
- const token = await requireCognitoTokenForSecrets("secrets");
1452
- const companyUid = await getEntityUid(
1453
- token,
1454
- scopeOpts(secrets.opts()),
1455
- );
1456
- const res = await vaultApiFetch({
1457
- token,
1458
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1459
- method: "PUT",
1460
- body: {
1461
- path: secretPath,
1462
- ...(tier !== undefined ? { tier } : {}),
1463
- ...(scriptLock ? { scriptLock } : {}),
1464
- },
1465
- });
1466
-
1467
- if (!res.ok) {
1468
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1469
- console.error(
1470
- chalk.red(`Failed to set policy: ${extractApiMessage(body, res.statusText)}`),
1471
- );
1472
- process.exit(1);
1473
- }
1474
-
1475
- const data = (await res.json().catch(() => ({}))) as SecretPolicyResponse;
1476
- removeCacheEntry(companyUid, secretPath);
1477
- console.log(chalk.green(`Policy updated for '${secretPath}'.`));
1478
- renderPolicySummary(
1479
- normalizePolicyRecord(
1480
- secretPath,
1481
- data.policy ? data : { policy: { path: secretPath, tier, scriptLock } },
1482
- ),
1483
- );
1484
- } catch (err) {
1485
- console.error(
1486
- chalk.red("Error:"),
1487
- err instanceof Error ? err.message : String(err),
1488
- );
1489
- process.exit(1);
1490
- }
1491
- });
1492
-
1493
- const script = secrets
1494
- .command("script")
1495
- .description("Manage approved scripts for script-locked secrets");
1496
-
1497
- script
1498
- .command("approve <path>")
1499
- .description("Approve a script for a secret path")
1500
- .requiredOption("--id <scriptId>", "Stable script identifier")
1501
- .requiredOption("--script <path>", "Path to the local script file")
1502
- .option(
1503
- "--remote-path <path>",
1504
- "Script path reported by the target runtime (defaults to the local path)",
1505
- )
1506
- .option(
1507
- "--attestation <level>",
1508
- "Attestation level",
1509
- "self-asserted-hash",
1510
- )
1511
- .action(async (
1512
- secretPath: string,
1513
- opts: {
1514
- id: string;
1515
- script: string;
1516
- remotePath?: string;
1517
- attestation: string;
1518
- },
1519
- ) => {
1520
- try {
1521
- rejectIfPersonal(secrets.opts(), "script approve");
1522
-
1523
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1524
- 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)`));
1525
- process.exit(1);
1526
- }
1527
-
1528
- const usage = await buildSecretUsage(
1529
- "exec",
1530
- opts.script,
1531
- opts.id,
1532
- opts.attestation,
1533
- );
1534
- const token = await requireCognitoTokenForSecrets("secrets");
1535
- const companyUid = await getEntityUid(
1536
- token,
1537
- scopeOpts(secrets.opts()),
1538
- );
1539
- const res = await vaultApiFetch({
1540
- token,
1541
- path: `/secrets/${encodeURIComponent(companyUid)}/policy/scripts`,
1542
- method: "POST",
1543
- body: {
1544
- path: secretPath,
1545
- scriptId: usage.script?.scriptId,
1546
- scriptPath: opts.remotePath ?? usage.script?.path,
1547
- sha256: usage.script?.sha256,
1548
- attestationLevel: usage.script?.attestationLevel,
1549
- },
1550
- });
1551
-
1552
- if (!res.ok) {
1553
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1554
- console.error(
1555
- chalk.red(`Failed to approve script: ${extractApiMessage(body, res.statusText)}`),
1556
- );
1557
- process.exit(1);
1558
- }
1559
-
1560
- removeCacheEntry(companyUid, secretPath);
1561
- console.log(chalk.green(`Approved script '${opts.id}' for '${secretPath}'.`));
1562
- } catch (err) {
1563
- console.error(
1564
- chalk.red("Error:"),
1565
- err instanceof Error ? err.message : String(err),
1566
- );
1567
- process.exit(1);
1568
- }
1569
- });
1570
-
1571
- script
1572
- .command("revoke <path>")
1573
- .description("Revoke an approved script from a secret path")
1574
- .requiredOption("--id <scriptId>", "Stable script identifier")
1575
- .action(async (secretPath: string, opts: { id: string }) => {
1576
- try {
1577
- rejectIfPersonal(secrets.opts(), "script revoke");
1578
-
1579
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1580
- 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)`));
1581
- process.exit(1);
1582
- }
1583
-
1584
- const token = await requireCognitoTokenForSecrets("secrets");
1585
- const companyUid = await getEntityUid(
1586
- token,
1587
- scopeOpts(secrets.opts()),
1588
- );
1589
- const res = await vaultApiFetch({
1590
- token,
1591
- path: `/secrets/${encodeURIComponent(companyUid)}/policy/scripts`,
1592
- method: "DELETE",
1593
- body: { path: secretPath, scriptId: opts.id },
1594
- });
1595
-
1596
- if (!res.ok) {
1597
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1598
- console.error(
1599
- chalk.red(`Failed to revoke script: ${extractApiMessage(body, res.statusText)}`),
1600
- );
1601
- process.exit(1);
1602
- }
1603
-
1604
- removeCacheEntry(companyUid, secretPath);
1605
- console.log(chalk.green(`Revoked script '${opts.id}' for '${secretPath}'.`));
1606
- } catch (err) {
1607
- console.error(
1608
- chalk.red("Error:"),
1609
- err instanceof Error ? err.message : String(err),
1610
- );
1611
- process.exit(1);
1612
- }
1613
- });
1614
-
1615
- script
1616
- .command("list <path>")
1617
- .description("List approved scripts for a secret path")
1618
- .action(async (secretPath: string) => {
1619
- try {
1620
- rejectIfPersonal(secrets.opts(), "script list");
1621
-
1622
- if (!SECRET_NAME_PATTERN.test(secretPath)) {
1623
- 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)`));
1624
- process.exit(1);
1625
- }
1626
-
1627
- const token = await requireCognitoTokenForSecrets("secrets");
1628
- const companyUid = await getEntityUid(
1629
- token,
1630
- scopeOpts(secrets.opts()),
1631
- );
1632
- const res = await vaultApiFetch({
1633
- token,
1634
- path: `/secrets/${encodeURIComponent(companyUid)}/policy`,
1635
- query: { path: secretPath },
1636
- });
1637
-
1638
- if (res.status === 404) {
1639
- const policyRecord = normalizePolicyRecord(secretPath, {
1640
- policy: { path: secretPath },
1641
- });
1642
- renderPolicySummary(policyRecord);
1643
- renderPolicyScripts(policyRecord.scripts);
1644
- return;
1645
- }
1646
- if (!res.ok) {
1647
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
1648
- console.error(
1649
- chalk.red(`Failed to list scripts: ${extractApiMessage(body, res.statusText)}`),
1650
- );
1651
- process.exit(1);
1652
- }
1653
-
1654
- const data = (await res.json()) as SecretPolicyResponse;
1655
- const policyRecord = normalizePolicyRecord(secretPath, data);
1656
- renderPolicySummary(policyRecord);
1657
- renderPolicyScripts(policyRecord.scripts);
1658
- } catch (err) {
1659
- console.error(
1660
- chalk.red("Error:"),
1661
- err instanceof Error ? err.message : String(err),
1662
- );
1663
- process.exit(1);
1664
- }
1665
- });
1666
-
1667
- secrets
1668
- .command("delete <name>")
1669
- .description("Delete a secret")
1670
- .option("--force", "Skip confirmation prompt")
1671
- .action(async (name: string, opts: { force?: boolean }) => {
1672
- try {
1673
- if (!SECRET_NAME_PATTERN.test(name)) {
1674
- 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)`));
1675
- process.exit(1);
1676
- }
1677
-
1678
- if (!opts.force) {
1679
- const confirmed = await confirmPrompt(
1680
- `Delete secret '${name}'? This cannot be undone.`,
1681
- );
1682
- if (!confirmed) {
1683
- console.log(chalk.dim("Aborted."));
1684
- return;
1685
- }
1686
- }
1687
-
1688
- const token = await requireCognitoTokenForSecrets("secrets");
1689
- const companyUid = await getEntityUid(
1690
- token,
1691
- scopeOpts(secrets.opts()),
1692
- );
1693
-
1694
- const res = await vaultApiFetch({
1695
- token,
1696
- path: buildSecretNamePath(companyUid, name),
1697
- method: "DELETE",
1698
- });
1699
-
1700
- if (!res.ok) {
1701
- const body = await res.json().catch(() => ({}));
1702
- console.error(
1703
- chalk.red(`Failed to delete secret: ${(body as Record<string, string>).error ?? res.statusText}`),
1704
- );
1705
- process.exit(1);
1706
- }
1707
-
1708
- removeCacheEntry(companyUid, name);
1709
- console.log(chalk.green(`Secret '${name}' deleted.`));
1710
- } catch (err) {
1711
- console.error(
1712
- chalk.red("Error:"),
1713
- err instanceof Error ? err.message : String(err),
1714
- );
1715
- process.exit(1);
1716
- }
1717
- });
1718
-
1719
- secrets
1720
- .command("sandbox")
1721
- .description("Run a command in the hosted sandbox with named secrets injected as env vars; open egress, secrets never touch this machine")
1722
- .option("--company <slug>", "Company slug (resolves to companyUid)")
1723
- .option(
1724
- "--personal",
1725
- "Operate on the caller's personal vault (no sharing)",
1726
- )
1727
- .option("--only <keys>", "Secret names to inject (comma-separated; may be repeated) (required)", collectSecretNames)
1728
- .allowUnknownOption(true)
1729
- .action(async (opts: { company?: string; personal?: boolean; only?: string[] }, cmd: Command) => {
1730
- try {
1731
- if (!opts.only || opts.only.length === 0) {
1732
- console.error(chalk.red("Error: --only is required and must name at least one secret."));
1733
- process.exit(1);
1734
- }
1735
-
1736
- const rawArgs = cmd.args;
1737
- const command = rawArgs.join(" ").trim();
1738
- if (command.length === 0) {
1739
- console.error(chalk.red("Error: no command specified. Usage: hq secrets sandbox --company <slug> --only KEY1,KEY2 -- <command>"));
1740
- process.exit(1);
1741
- }
1742
- if (command.length > 8192) {
1743
- console.error(chalk.red("Error: sandbox command exceeds the 8192 character limit."));
1744
- process.exit(1);
1745
- }
1746
-
1747
- const keys = parseSecretNameList(opts.only);
1748
- const token = await requireCognitoTokenForSecrets("secrets");
1749
- const scope = scopeOpts(mergeScopeOpts(secrets.opts(), opts));
1750
- const companyUid = await getEntityUid(token, scope);
1751
- const client = new SandboxRunnerClient();
1752
- const started = await client.startJob(token, {
1753
- companyUid,
1754
- secretNames: keys,
1755
- command,
1756
- });
1757
- const job =
1758
- started.status === "succeeded" || started.status === "failed"
1759
- ? await client.getJob(token, started.jobId)
1760
- : await client.pollJob(token, started.jobId);
1761
-
1762
- renderSandboxJobResult(job, keys);
1763
- const exitCode = typeof job.exitCode === "number" ? job.exitCode : undefined;
1764
- if (job.success === false || (exitCode !== undefined && exitCode !== 0) || job.status === "failed") {
1765
- if (exitCode !== undefined && exitCode !== 0) {
1766
- console.error(chalk.red(`Sandbox command failed with exit code ${exitCode}.`));
1767
- process.exit(exitCode);
1768
- }
1769
- console.error(
1770
- chalk.red(
1771
- job.error !== undefined
1772
- ? scrubSandboxOutput(job.error, keys)
1773
- : "Sandbox execution failed before the command produced an exit code.",
1774
- ),
1775
- );
1776
- process.exit(1);
1777
- }
1778
- } catch (err) {
1779
- console.error(
1780
- chalk.red("Error:"),
1781
- err instanceof Error ? scrubSandboxOutput(err.message) : scrubSandboxOutput(String(err)),
1782
- );
1783
- process.exit(1);
1784
- }
1785
- });
1786
-
1787
- secrets
1788
- .command("exec")
1789
- .description("Run a command with secrets injected as env vars")
1790
- .requiredOption("--only <keys>", "Secret names to inject (comma-separated; may be repeated) (required)", collectSecretNames)
1791
- .option("--script <path>", "Attach local script identity for script-locked secrets")
1792
- .option("--script-id <id>", "Stable script identifier approved by policy")
1793
- .allowUnknownOption(true)
1794
- .action(async (
1795
- _opts: { only: string[]; script?: string; scriptId?: string },
1796
- cmd: Command,
1797
- ) => {
1798
- try {
1799
- const rawArgs = cmd.args;
1800
- const dashIndex = process.argv.indexOf("--");
1801
- let childArgs: string[];
1802
- if (dashIndex !== -1) {
1803
- childArgs = process.argv.slice(dashIndex + 1);
1804
- } else {
1805
- childArgs = rawArgs;
1806
- }
1807
-
1808
- if (childArgs.length === 0) {
1809
- console.error(chalk.red("Error: no command specified. Usage: hq secrets exec --only KEY1,KEY2 -- <command>"));
1810
- process.exit(1);
1811
- }
1812
-
1813
- const keys = parseSecretNameList(_opts.only);
1814
-
1815
- const cred = await resolveVaultCredential();
1816
- const companyUid =
1817
- cred.kind === "api-key"
1818
- ? "__api_key__"
1819
- : await getEntityUid(cred.token, scopeOpts(secrets.opts()));
1820
-
1821
- const revealed = await loadRevealedSecrets(
1822
- cred.token,
1823
- companyUid,
1824
- keys,
1825
- cred.kind === "cognito"
1826
- ? await buildSecretUsage("exec", _opts.script, _opts.scriptId)
1827
- : undefined,
1828
- );
1829
-
1830
- const secretEnv: Record<string, string> = {};
1831
- for (const key of keys) {
1832
- const value = revealed.get(key);
1833
- // loadRevealedSecrets throws on any unresolved key, so a miss here is
1834
- // unreachable — guard rather than inject an `undefined` into the env.
1835
- if (value === undefined) {
1836
- throw new Error(`Failed to fetch secret '${key}': not returned by vault`);
1837
- }
1838
- secretEnv[key] = value;
1839
- }
1840
-
1841
- const [childCmd, ...childCmdArgs] = childArgs;
1842
- const child = spawn(childCmd, childCmdArgs, {
1843
- stdio: "inherit",
1844
- env: { ...process.env, ...secretEnv },
1845
- });
1846
-
1847
- child.on("error", (err) => {
1848
- console.error(chalk.red(`Failed to start command '${childCmd}': ${err.message}`));
1849
- process.exit(1);
1850
- });
1851
-
1852
- child.on("close", (code, signal) => {
1853
- if (signal) {
1854
- process.kill(process.pid, signal);
1855
- }
1856
- process.exit(code ?? 1);
1857
- });
1858
- } catch (err) {
1859
- console.error(
1860
- chalk.red("Error:"),
1861
- err instanceof Error ? err.message : String(err),
1862
- );
1863
- process.exit(1);
1864
- }
1865
- });
1866
-
1867
- secrets
1868
- .command("env")
1869
- .description("Print 'export KEY=VALUE' lines suitable for: source <(hq secrets env --only K1,K2)")
1870
- .requiredOption("--only <keys>", "Secret names to print (comma-separated; may be repeated) (required)", collectSecretNames)
1871
- .option("--script <path>", "Attach local script identity for script-locked secrets")
1872
- .option("--script-id <id>", "Stable script identifier approved by policy")
1873
- .action(async (
1874
- opts: { only: string[]; script?: string; scriptId?: string },
1875
- ) => {
1876
- try {
1877
- const redact = process.stdout.isTTY;
1878
- if (redact) {
1879
- console.error(
1880
- chalk.yellow(
1881
- "stdout is a terminal — values redacted. Use: source <(hq secrets env --only KEY1,KEY2)",
1882
- ),
1883
- );
1884
- }
1885
-
1886
- const keys = parseSecretNameList(opts.only);
1887
-
1888
- const cred = await resolveVaultCredential();
1889
- const companyUid =
1890
- cred.kind === "api-key"
1891
- ? "__api_key__"
1892
- : await getEntityUid(cred.token, scopeOpts(secrets.opts()));
1893
-
1894
- const revealed = await loadRevealedSecrets(
1895
- cred.token,
1896
- companyUid,
1897
- keys,
1898
- cred.kind === "cognito"
1899
- ? await buildSecretUsage("env", opts.script, opts.scriptId)
1900
- : undefined,
1901
- );
1902
-
1903
- for (const key of keys) {
1904
- const value = revealed.get(key);
1905
- // loadRevealedSecrets throws on any unresolved key, so a miss here is
1906
- // unreachable — guard rather than print an `undefined` export line.
1907
- if (value === undefined) {
1908
- throw new Error(`Failed to fetch secret '${key}': not returned by vault`);
1909
- }
1910
- const out = redact ? "[REDACTED]" : value;
1911
- process.stdout.write(`export ${key}=${shellSingleQuote(out)}\n`);
1912
- }
1913
- } catch (err) {
1914
- console.error(
1915
- chalk.red("Error:"),
1916
- err instanceof Error ? err.message : String(err),
1917
- );
1918
- process.exit(1);
1919
- }
1920
- });
1921
-
1922
- secrets
1923
- .command("generate-link <name>")
1924
- .description("Generate a one-time link for someone to submit a secret value")
1925
- .option("--expires <duration>", "Token expiry duration (e.g. 24h, 2d, 30m)", "24h")
1926
- .action(async (name: string, opts: { expires: string }) => {
1927
- try {
1928
- if (!SECRET_NAME_PATTERN.test(name)) {
1929
- 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)`));
1930
- process.exit(1);
1931
- }
1932
-
1933
- const expiresInMs = parseDuration(opts.expires);
1934
- if (expiresInMs === null) {
1935
- console.error(chalk.red(`Invalid duration '${opts.expires}'. Use formats like 30m, 12h, 2d.`));
1936
- process.exit(1);
1937
- }
1938
-
1939
- const MAX_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
1940
- if (expiresInMs > MAX_EXPIRY_MS) {
1941
- console.error(chalk.red("Maximum expiry is 7 days (7d)."));
1942
- process.exit(1);
1943
- }
1944
-
1945
- const token = await requireCognitoTokenForSecrets("secrets");
1946
- const companyUid = await getEntityUid(
1947
- token,
1948
- scopeOpts(secrets.opts()),
1949
- );
1950
-
1951
- const res = await vaultApiFetch({
1952
- token,
1953
- path: buildSecretNamePath(companyUid, name),
1954
- method: "POST",
1955
- body: { expiresInMs },
1956
- query: { action: "generate-token" },
1957
- });
1958
-
1959
- if (!res.ok) {
1960
- const body = await res.json().catch(() => ({}));
1961
- console.error(
1962
- chalk.red(`Failed to generate link: ${(body as Record<string, string>).error ?? res.statusText}`),
1963
- );
1964
- process.exit(1);
1965
- }
1966
-
1967
- const data = (await res.json()) as {
1968
- url: string;
1969
- expiresAt: string;
1970
- secretName: string;
1971
- };
1972
-
1973
- console.log(chalk.green("Secret input link generated:"));
1974
- console.log(`\n ${data.url}\n`);
1975
- console.log(chalk.dim(` Secret: ${data.secretName}`));
1976
- console.log(chalk.dim(` Expires: ${data.expiresAt}`));
1977
- console.log(chalk.dim(" One-time use — link is invalidated after first submission."));
1978
- } catch (err) {
1979
- console.error(
1980
- chalk.red("Error:"),
1981
- err instanceof Error ? err.message : String(err),
1982
- );
1983
- process.exit(1);
1984
- }
1985
- });
1986
-
1987
- secrets
1988
- .command("share <path>")
1989
- .description("Share a secret with an email address, group, or the entire company (@all)")
1990
- .requiredOption("--with <principal>", "Email address, group id, or @all (entire company) to share with")
1991
- .requiredOption("--permission <level>", "Permission level: read | write | admin")
1992
- .action(async (path: string, opts: { with: string; permission: string }) => {
1993
- try {
1994
- rejectIfPersonal(secrets.opts(), "share");
1995
-
1996
- if (!SECRET_NAME_PATTERN.test(path)) {
1997
- 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)`));
1998
- process.exit(1);
1999
- }
2000
-
2001
- if (!["read", "write", "admin"].includes(opts.permission)) {
2002
- console.error(chalk.red(`Invalid permission '${opts.permission}': must be one of read, write, admin`));
2003
- process.exit(1);
2004
- }
2005
-
2006
- const principal = parseSecretAclPrincipal(opts.with);
2007
- if (!principal) {
2008
- process.exit(1);
2009
- }
2010
-
2011
- const token = await requireCognitoTokenForSecrets("secrets");
2012
- const companyUid = await getEntityUid(
2013
- token,
2014
- scopeOpts(secrets.opts()),
2015
- );
2016
-
2017
- const res = await vaultApiFetch({
2018
- token,
2019
- path: `/secrets/${encodeURIComponent(companyUid)}/acl/grant`,
2020
- method: "POST",
2021
- body: {
2022
- path,
2023
- granteeType: principal.granteeType,
2024
- granteeId: principal.granteeId,
2025
- permission: opts.permission,
2026
- },
2027
- });
2028
-
2029
- if (!res.ok) {
2030
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2031
- if (res.status === 401) {
2032
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2033
- } else if (res.status === 403) {
2034
- console.error(chalk.red("Not authorized to share this secret"));
2035
- } else if (res.status === 404) {
2036
- console.error(chalk.red("ACL record not found for this path — has the secret been created?"));
2037
- } else if (res.status === 409) {
2038
- console.error(chalk.red("Concurrent modification — please retry"));
2039
- } else if (res.status >= 500) {
2040
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2041
- } else {
2042
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2043
- }
2044
- process.exit(1);
2045
- }
2046
-
2047
- console.log(chalk.green(`Shared '${path}' with ${describeSecretAclPrincipal(principal)} (${opts.permission})`));
2048
- } catch (err) {
2049
- console.error(
2050
- chalk.red("Error:"),
2051
- err instanceof Error ? err.message : String(err),
2052
- );
2053
- process.exit(1);
2054
- }
2055
- });
2056
-
2057
- secrets
2058
- .command("unshare <path>")
2059
- .description("Remove a grant from a secret")
2060
- .requiredOption("--from <principal>", "Email address, group id, or @all (entire company) to remove")
2061
- .action(async (path: string, opts: { from: string }) => {
2062
- try {
2063
- rejectIfPersonal(secrets.opts(), "unshare");
2064
-
2065
- if (!SECRET_NAME_PATTERN.test(path)) {
2066
- 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)`));
2067
- process.exit(1);
2068
- }
2069
-
2070
- const principal = parseSecretAclPrincipal(opts.from);
2071
- if (!principal) {
2072
- process.exit(1);
2073
- }
2074
-
2075
- const token = await requireCognitoTokenForSecrets("secrets");
2076
- const companyUid = await getEntityUid(
2077
- token,
2078
- scopeOpts(secrets.opts()),
2079
- );
2080
-
2081
- const res = await vaultApiFetch({
2082
- token,
2083
- path: `/secrets/${encodeURIComponent(companyUid)}/acl/revoke`,
2084
- method: "POST",
2085
- body: {
2086
- path,
2087
- granteeType: principal.granteeType,
2088
- granteeId: principal.granteeId,
2089
- },
2090
- });
2091
-
2092
- if (!res.ok) {
2093
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2094
- if (res.status === 401) {
2095
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2096
- } else if (res.status === 403) {
2097
- console.error(chalk.red("Not authorized to modify this secret's ACL"));
2098
- } else if (res.status === 404) {
2099
- console.log(chalk.green(`Grant already absent for '${path}' / ${describeSecretAclPrincipal(principal)}`));
2100
- return;
2101
- } else if (res.status >= 500) {
2102
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2103
- } else {
2104
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2105
- }
2106
- process.exit(1);
2107
- }
2108
-
2109
- console.log(chalk.green(`Removed grant for ${describeSecretAclPrincipal(principal)} on '${path}'`));
2110
- } catch (err) {
2111
- console.error(
2112
- chalk.red("Error:"),
2113
- err instanceof Error ? err.message : String(err),
2114
- );
2115
- process.exit(1);
2116
- }
2117
- });
2118
-
2119
- secrets
2120
- .command("acl <path>")
2121
- .description("Show the ACL (access control list) for a secret path")
2122
- .action(async (path: string) => {
2123
- try {
2124
- rejectIfPersonal(secrets.opts(), "acl");
2125
-
2126
- if (!SECRET_NAME_PATTERN.test(path)) {
2127
- 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)`));
2128
- process.exit(1);
2129
- }
2130
-
2131
- const token = await requireCognitoTokenForSecrets("secrets");
2132
- const companyUid = await getEntityUid(
2133
- token,
2134
- scopeOpts(secrets.opts()),
2135
- );
2136
-
2137
- const secretPath = path;
2138
- const res = await vaultApiFetch({
2139
- token,
2140
- path: `/secrets/${encodeURIComponent(companyUid)}/acl`,
2141
- query: { path: secretPath },
2142
- });
2143
-
2144
- if (!res.ok) {
2145
- const body = await res.json().catch(() => ({})) as Record<string, string>;
2146
- if (res.status === 401) {
2147
- console.error(chalk.red("Not authenticated — please run `hq login`"));
2148
- } else if (res.status === 403) {
2149
- console.error(chalk.red("Not authorized to view this secret's ACL"));
2150
- } else if (res.status === 404) {
2151
- console.error(chalk.red(`No ACL record exists for '${path}'`));
2152
- } else if (res.status >= 500) {
2153
- console.error(chalk.red(`Server error: ${body.error ?? res.statusText}`));
2154
- } else {
2155
- console.error(chalk.red(body.message ?? body.error ?? "Invalid request"));
2156
- }
2157
- process.exit(1);
2158
- }
2159
-
2160
- const data = (await res.json()) as {
2161
- acl: {
2162
- itemType: "ACL";
2163
- companyUid: string;
2164
- path: string;
2165
- creatorUid: string;
2166
- open?: boolean;
2167
- entries: Array<{
2168
- granteeType: string;
2169
- granteeId: string;
2170
- permission: string;
2171
- grantedBy: string;
2172
- grantedAt: string;
2173
- }>;
2174
- createdAt: string;
2175
- updatedAt: string;
2176
- schemaVersion: number;
2177
- };
2178
- };
2179
-
2180
- const acl = data.acl;
2181
- const aclStatus = acl.open ? "open" : "restricted";
2182
-
2183
- console.log(chalk.green(`ACL for ${acl.path} (${aclStatus})`));
2184
- console.log(`Creator: ${acl.creatorUid}`);
2185
-
2186
- if (acl.entries.length === 0) {
2187
- if (acl.open) {
2188
- console.log(chalk.gray("Open ACL — all active members have read access."));
2189
- } else {
2190
- console.log(chalk.gray("No explicit grants — only creator has access."));
2191
- }
2192
- return;
2193
- }
2194
-
2195
- console.log("Entries:");
2196
- const TYPE_W = Math.max(4, ...acl.entries.map((e) => e.granteeType.length));
2197
- const GRANTEE_W = Math.max(7, ...acl.entries.map((e) => e.granteeId.length));
2198
- const PERM_W = Math.max(10, ...acl.entries.map((e) => e.permission.length));
2199
- const BY_W = Math.max(10, ...acl.entries.map((e) => e.grantedBy.length));
2200
- const tableHeader = [
2201
- "TYPE".padEnd(TYPE_W),
2202
- "GRANTEE".padEnd(GRANTEE_W),
2203
- "PERMISSION".padEnd(PERM_W),
2204
- "GRANTED_BY".padEnd(BY_W),
2205
- "GRANTED_AT",
2206
- ].join(" ");
2207
- console.log(chalk.bold(tableHeader));
2208
- for (const e of acl.entries) {
2209
- const grantedAt = e.grantedAt.slice(0, 10);
2210
- console.log(
2211
- [
2212
- e.granteeType.padEnd(TYPE_W),
2213
- e.granteeId.padEnd(GRANTEE_W),
2214
- e.permission.padEnd(PERM_W),
2215
- e.grantedBy.padEnd(BY_W),
2216
- grantedAt,
2217
- ].join(" "),
2218
- );
2219
- }
2220
- } catch (err) {
2221
- console.error(
2222
- chalk.red("Error:"),
2223
- err instanceof Error ? err.message : String(err),
2224
- );
2225
- process.exit(1);
2226
- }
2227
- });
2228
-
2229
- const cache = secrets
2230
- .command("cache")
2231
- .description("Manage the local secrets cache");
2232
-
2233
- cache
2234
- .command("clear")
2235
- .description("Clear all cached secrets")
2236
- .action(async () => {
2237
- clearAllCache();
2238
- console.log(chalk.green("Secrets cache cleared."));
2239
- });
2240
- }