@indigoai-us/hq-cli 5.77.14 → 5.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/assets/scaffold/core/scripts/archive-old-threads.sh +86 -0
  3. package/assets/scaffold/core/scripts/backfill-company-skill-mirrors.sh +73 -0
  4. package/assets/scaffold/core/scripts/backfill-workspace-mirror.sh +51 -0
  5. package/assets/scaffold/core/scripts/codex-skill-bridge.sh +550 -0
  6. package/assets/scaffold/core/scripts/detect-stale-core-policy-mirror.sh +185 -0
  7. package/assets/scaffold/core/scripts/hq-status-summary.sh +187 -0
  8. package/assets/scaffold/core/scripts/ontology-readme-drift.sh +264 -0
  9. package/assets/scaffold/core/scripts/qmd-reindex-after-sync.sh +93 -0
  10. package/assets/scaffold/core/scripts/rebuild-all-indexes.sh +69 -0
  11. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +206 -0
  12. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +127 -0
  13. package/assets/scaffold/core/scripts/rebuild-orchestrator-index.sh +86 -0
  14. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +105 -0
  15. package/assets/scaffold/core/scripts/rebuild-public-knowledge-index.sh +83 -0
  16. package/assets/scaffold/core/scripts/rebuild-reports-index.sh +114 -0
  17. package/assets/scaffold/core/scripts/rebuild-social-drafts-index.sh +135 -0
  18. package/assets/scaffold/core/scripts/rebuild-threads-index.sh +82 -0
  19. package/assets/scaffold/core/scripts/rebuild-workers-index.sh +97 -0
  20. package/assets/scaffold/core/scripts/resize-screenshot.sh +47 -0
  21. package/assets/scaffold/core/scripts/token-usage-report.sh +254 -0
  22. package/assets/scaffold/core/scripts/worktree.sh +136 -0
  23. package/dist/commands/agents.js +28 -12
  24. package/dist/commands/api-keys.js +100 -20
  25. package/dist/commands/core.d.ts +90 -0
  26. package/dist/commands/core.js +279 -0
  27. package/dist/commands/files-browse.d.ts +21 -0
  28. package/dist/commands/files-browse.js +145 -24
  29. package/dist/commands/files.js +33 -7
  30. package/dist/commands/meetings.js +16 -9
  31. package/dist/commands/members.js +16 -5
  32. package/dist/commands/pack-install.d.ts +14 -0
  33. package/dist/commands/pack-install.js +42 -2
  34. package/dist/commands/pkg-install.js +39 -2
  35. package/dist/commands/run.js +6 -2
  36. package/dist/commands/secrets.js +120 -65
  37. package/dist/main.js +6 -0
  38. package/dist/utils/api-key-command-gate.d.ts +45 -0
  39. package/dist/utils/api-key-command-gate.js +51 -0
  40. package/dist/utils/hq-roots.d.ts +91 -0
  41. package/dist/utils/hq-roots.js +212 -0
  42. package/dist/utils/resolve-vault-credential.d.ts +63 -3
  43. package/dist/utils/resolve-vault-credential.js +152 -6
  44. package/dist/utils/run-bundled-script.d.ts +66 -0
  45. package/dist/utils/run-bundled-script.js +80 -0
  46. package/dist/utils/vault-api.d.ts +21 -0
  47. package/dist/utils/vault-api.js +74 -3
  48. package/package.json +7 -1
  49. package/.claude/policies/hq-cli-interactive-reads-use-sts-vend.md +0 -49
  50. package/.github/workflows/ci.yml +0 -46
  51. package/.github/workflows/publish.yml +0 -36
  52. package/.github/workflows/scripts/smoke-test-pkg.sh +0 -97
  53. package/e2e/cli.test.ts +0 -128
  54. package/eslint.config.js +0 -37
  55. package/pnpm-workspace.yaml +0 -4
  56. package/scripts/chmod-bins.mjs +0 -49
  57. package/scripts/generate-dsn.mjs +0 -26
  58. package/scripts/generate-scan-packages-table.mjs +0 -113
  59. package/scripts/smoke-sources-signals.sh +0 -103
  60. package/src/bin/hq-auth-refresh.ts +0 -43
  61. package/src/cli-version.ts +0 -13
  62. package/src/commands/__fixtures__/make-tar.ts +0 -126
  63. package/src/commands/_patterns.ts +0 -10
  64. package/src/commands/add.ts +0 -75
  65. package/src/commands/agents.test.ts +0 -527
  66. package/src/commands/agents.ts +0 -923
  67. package/src/commands/api-keys.test.ts +0 -291
  68. package/src/commands/api-keys.ts +0 -382
  69. package/src/commands/artifact-verify.test.ts +0 -177
  70. package/src/commands/auth.test.ts +0 -82
  71. package/src/commands/auth.ts +0 -213
  72. package/src/commands/billing.test.ts +0 -158
  73. package/src/commands/billing.ts +0 -146
  74. package/src/commands/channels.test.ts +0 -74
  75. package/src/commands/channels.ts +0 -91
  76. package/src/commands/cloud-demote.test.ts +0 -401
  77. package/src/commands/cloud-demote.ts +0 -278
  78. package/src/commands/cloud-provision.test.ts +0 -1117
  79. package/src/commands/cloud-provision.ts +0 -942
  80. package/src/commands/cloud.pull-all.test.ts +0 -711
  81. package/src/commands/cloud.pull-per-company.test.ts +0 -188
  82. package/src/commands/cloud.push-all.test.ts +0 -485
  83. package/src/commands/cloud.scope-excluded-warning.test.ts +0 -22
  84. package/src/commands/cloud.selectors.test.ts +0 -208
  85. package/src/commands/cloud.status.test.ts +0 -160
  86. package/src/commands/cloud.test.ts +0 -41
  87. package/src/commands/cloud.ts +0 -2130
  88. package/src/commands/company.test.ts +0 -202
  89. package/src/commands/company.ts +0 -148
  90. package/src/commands/creators.test.ts +0 -60
  91. package/src/commands/creators.ts +0 -117
  92. package/src/commands/crm.test.ts +0 -179
  93. package/src/commands/crm.ts +0 -236
  94. package/src/commands/db-migrate.ts +0 -55
  95. package/src/commands/db-provision.ts +0 -114
  96. package/src/commands/db-sql.ts +0 -124
  97. package/src/commands/db-status.ts +0 -108
  98. package/src/commands/db.ts +0 -26
  99. package/src/commands/dm.test.ts +0 -748
  100. package/src/commands/dm.ts +0 -1226
  101. package/src/commands/feedback.test.ts +0 -413
  102. package/src/commands/feedback.ts +0 -169
  103. package/src/commands/files-browse.test.ts +0 -1249
  104. package/src/commands/files-browse.ts +0 -1506
  105. package/src/commands/files-delete.test.ts +0 -484
  106. package/src/commands/files-recovery.test.ts +0 -370
  107. package/src/commands/files.test.ts +0 -722
  108. package/src/commands/files.ts +0 -1446
  109. package/src/commands/group-grants.test.ts +0 -330
  110. package/src/commands/group-grants.ts +0 -455
  111. package/src/commands/groups.test.ts +0 -44
  112. package/src/commands/groups.ts +0 -368
  113. package/src/commands/integrations.test.ts +0 -633
  114. package/src/commands/integrations.ts +0 -507
  115. package/src/commands/list.ts +0 -85
  116. package/src/commands/login.ts +0 -52
  117. package/src/commands/logout.ts +0 -30
  118. package/src/commands/marketplace-install.test.ts +0 -543
  119. package/src/commands/marketplace-security.test.ts +0 -646
  120. package/src/commands/mcp-registration.test.ts +0 -2787
  121. package/src/commands/mcp-registration.ts +0 -2612
  122. package/src/commands/mcp-status.test.ts +0 -483
  123. package/src/commands/mcp-status.ts +0 -575
  124. package/src/commands/mcp-status.us011.test.ts +0 -243
  125. package/src/commands/meetings.test.ts +0 -522
  126. package/src/commands/meetings.ts +0 -789
  127. package/src/commands/members.test.ts +0 -1474
  128. package/src/commands/members.ts +0 -1181
  129. package/src/commands/onboard-identity-guard.test.ts +0 -99
  130. package/src/commands/onboard-identity-guard.ts +0 -103
  131. package/src/commands/onboard-join.test.ts +0 -96
  132. package/src/commands/onboard-join.ts +0 -101
  133. package/src/commands/onboard-warning.test.ts +0 -26
  134. package/src/commands/onboard-warning.ts +0 -12
  135. package/src/commands/onboard.ts +0 -267
  136. package/src/commands/outposts-heartbeat.test.ts +0 -299
  137. package/src/commands/outposts-heartbeat.ts +0 -310
  138. package/src/commands/outposts-replica-sync.test.ts +0 -272
  139. package/src/commands/outposts-self-deploy.test.ts +0 -243
  140. package/src/commands/outposts.test.ts +0 -1039
  141. package/src/commands/outposts.ts +0 -1935
  142. package/src/commands/pack-install-secret-authorization.test.ts +0 -115
  143. package/src/commands/pack-install.test.ts +0 -1469
  144. package/src/commands/pack-install.ts +0 -2256
  145. package/src/commands/pack-update-cache.test.ts +0 -149
  146. package/src/commands/packs-update-api-key.test.ts +0 -105
  147. package/src/commands/packs.test.ts +0 -88
  148. package/src/commands/packs.ts +0 -622
  149. package/src/commands/people.test.ts +0 -807
  150. package/src/commands/people.ts +0 -422
  151. package/src/commands/pkg-install.dispatch.test.ts +0 -103
  152. package/src/commands/pkg-install.ts +0 -221
  153. package/src/commands/pkg-list.test.ts +0 -79
  154. package/src/commands/pkg-list.ts +0 -13
  155. package/src/commands/pkg-remove.ts +0 -71
  156. package/src/commands/pkg-update.ts +0 -189
  157. package/src/commands/publish.test.ts +0 -650
  158. package/src/commands/publish.ts +0 -580
  159. package/src/commands/reindex.test.ts +0 -259
  160. package/src/commands/reindex.ts +0 -274
  161. package/src/commands/rescue.test.ts +0 -39
  162. package/src/commands/rescue.ts +0 -210
  163. package/src/commands/run.env-local.test.ts +0 -88
  164. package/src/commands/run.test.ts +0 -45
  165. package/src/commands/run.ts +0 -190
  166. package/src/commands/safe-extract.test.ts +0 -459
  167. package/src/commands/safe-extract.ts +0 -444
  168. package/src/commands/secrets-scope.test.ts +0 -56
  169. package/src/commands/secrets-scope.ts +0 -32
  170. package/src/commands/secrets.parse-destination.test.ts +0 -38
  171. package/src/commands/secrets.test.ts +0 -2050
  172. package/src/commands/secrets.ts +0 -2249
  173. package/src/commands/signals.ts +0 -351
  174. package/src/commands/skill.test.ts +0 -770
  175. package/src/commands/skill.ts +0 -796
  176. package/src/commands/sources.ts +0 -362
  177. package/src/commands/sync-mode.test.ts +0 -366
  178. package/src/commands/sync-mode.ts +0 -387
  179. package/src/commands/sync-narrow.test.ts +0 -633
  180. package/src/commands/sync-narrow.ts +0 -555
  181. package/src/commands/sync.ts +0 -165
  182. package/src/commands/team-sync.ts +0 -628
  183. package/src/commands/update.ts +0 -71
  184. package/src/commands/whoami.ts +0 -83
  185. package/src/commands/workers.test.ts +0 -158
  186. package/src/commands/workers.ts +0 -301
  187. package/src/index.test.ts +0 -32
  188. package/src/index.ts +0 -20
  189. package/src/lib/db/control-plane.test.ts +0 -59
  190. package/src/lib/db/control-plane.ts +0 -113
  191. package/src/lib/db/local.test.ts +0 -81
  192. package/src/lib/db/local.ts +0 -148
  193. package/src/lib/db/migrate.test.ts +0 -133
  194. package/src/lib/db/migrate.ts +0 -137
  195. package/src/lib/db/paths.test.ts +0 -112
  196. package/src/lib/db/paths.ts +0 -128
  197. package/src/lib/db/remote-engine.test.ts +0 -44
  198. package/src/lib/db/remote-engine.ts +0 -148
  199. package/src/lib/db/remote-sql.test.ts +0 -32
  200. package/src/lib/db/remote-sql.ts +0 -62
  201. package/src/lib/db/sql.test.ts +0 -106
  202. package/src/lib/db/sql.ts +0 -192
  203. package/src/lib/hq-cloud-dep.smoke.test.ts +0 -75
  204. package/src/lib/local-tree-diff.test.ts +0 -301
  205. package/src/lib/local-tree-diff.ts +0 -362
  206. package/src/lib/narrow-hint-banner.test.ts +0 -235
  207. package/src/lib/narrow-hint-banner.ts +0 -212
  208. package/src/lib/plan-limit-nag.test.ts +0 -317
  209. package/src/lib/plan-limit-nag.ts +0 -264
  210. package/src/main.ts +0 -371
  211. package/src/node-preflight.test.ts +0 -60
  212. package/src/node-preflight.ts +0 -67
  213. package/src/outpost/session-heartbeat-bounds.test.ts +0 -195
  214. package/src/outpost/session-heartbeat-guard.test.ts +0 -105
  215. package/src/outpost/session-heartbeat-publisher.test.ts +0 -178
  216. package/src/outpost/session-heartbeat-publisher.ts +0 -186
  217. package/src/outpost/session-heartbeat-retain-guard.test.ts +0 -126
  218. package/src/outpost/session-heartbeat.test.ts +0 -459
  219. package/src/outpost/session-heartbeat.ts +0 -877
  220. package/src/packaging.test.ts +0 -109
  221. package/src/run/__fixtures__/discover-schemas/example.env.schema +0 -4
  222. package/src/run/discover-schemas.test.ts +0 -153
  223. package/src/run/discover-schemas.ts +0 -79
  224. package/src/run/hq-plugin.test.ts +0 -371
  225. package/src/run/hq-plugin.ts +0 -277
  226. package/src/run/varlock-shape.test.ts +0 -57
  227. package/src/schemas/hq-package.schema.json +0 -155
  228. package/src/sentry-before-send.test.ts +0 -359
  229. package/src/sentry-before-send.ts +0 -221
  230. package/src/sentry-epipe.test.ts +0 -37
  231. package/src/sentry-release.test.ts +0 -54
  232. package/src/sentry.test.ts +0 -24
  233. package/src/sentry.ts +0 -54
  234. package/src/strategies/link.ts +0 -62
  235. package/src/strategies/merge.ts +0 -142
  236. package/src/types.ts +0 -146
  237. package/src/utils/__fixtures__/scan-packages.generated-block.sh +0 -23
  238. package/src/utils/auth-error.test.ts +0 -40
  239. package/src/utils/auth-error.ts +0 -42
  240. package/src/utils/billing-gate.test.ts +0 -95
  241. package/src/utils/billing-gate.ts +0 -228
  242. package/src/utils/breadcrumb-buffer.ts +0 -18
  243. package/src/utils/cli-telemetry.test.ts +0 -153
  244. package/src/utils/cli-telemetry.ts +0 -61
  245. package/src/utils/cognito-session.machine.test.ts +0 -109
  246. package/src/utils/cognito-session.refresh.test.ts +0 -84
  247. package/src/utils/cognito-session.test.ts +0 -328
  248. package/src/utils/cognito-session.ts +0 -448
  249. package/src/utils/company-selection-error.test.ts +0 -42
  250. package/src/utils/company-selection-error.ts +0 -45
  251. package/src/utils/contribution-table.ts +0 -83
  252. package/src/utils/environmental-error.test.ts +0 -45
  253. package/src/utils/environmental-error.ts +0 -39
  254. package/src/utils/epipe.test.ts +0 -28
  255. package/src/utils/epipe.ts +0 -29
  256. package/src/utils/expected-cli-error.test.ts +0 -28
  257. package/src/utils/expected-cli-error.ts +0 -39
  258. package/src/utils/feedback-diagnostics.test.ts +0 -183
  259. package/src/utils/feedback-diagnostics.ts +0 -123
  260. package/src/utils/feedback-screenshots.test.ts +0 -134
  261. package/src/utils/feedback-screenshots.ts +0 -124
  262. package/src/utils/feedback-versions.test.ts +0 -98
  263. package/src/utils/feedback-versions.ts +0 -68
  264. package/src/utils/git.ts +0 -74
  265. package/src/utils/integrity.ts +0 -59
  266. package/src/utils/intercepted-process-exit.test.ts +0 -37
  267. package/src/utils/intercepted-process-exit.ts +0 -36
  268. package/src/utils/login-provider.test.ts +0 -42
  269. package/src/utils/login-provider.ts +0 -30
  270. package/src/utils/manifest.test.ts +0 -167
  271. package/src/utils/manifest.ts +0 -131
  272. package/src/utils/pack-contributions.test.ts +0 -603
  273. package/src/utils/pack-contributions.ts +0 -450
  274. package/src/utils/people.ts +0 -215
  275. package/src/utils/registry-client.ts +0 -204
  276. package/src/utils/registry.ts +0 -90
  277. package/src/utils/resolve-vault-credential.test.ts +0 -69
  278. package/src/utils/resolve-vault-credential.ts +0 -60
  279. package/src/utils/sandbox-runner-client.test.ts +0 -279
  280. package/src/utils/sandbox-runner-client.ts +0 -260
  281. package/src/utils/secrets-cache.ts +0 -183
  282. package/src/utils/sentry-identity.ts +0 -45
  283. package/src/utils/settle-with-timeout.test.ts +0 -21
  284. package/src/utils/settle-with-timeout.ts +0 -22
  285. package/src/utils/user-yaml-error.test.ts +0 -24
  286. package/src/utils/user-yaml-error.ts +0 -30
  287. package/src/utils/vault-api.test.ts +0 -536
  288. package/src/utils/vault-api.ts +0 -382
  289. package/src/utils/version-check.test.ts +0 -176
  290. package/src/utils/version-check.ts +0 -155
  291. package/src/utils/version-gate.test.ts +0 -1024
  292. package/src/utils/version-gate.ts +0 -702
  293. package/test/commands/db-tenant-isolation.test.ts +0 -94
  294. package/test/commands/db.test.ts +0 -85
  295. package/test/commands/signals.test.ts +0 -207
  296. package/test/commands/sources.test.ts +0 -231
  297. package/test/e2e/smoke-install-mcp.sh +0 -113
  298. package/test/fixtures/hq-pack-smoke-mcp/mcp/smoke-http.json +0 -1
  299. package/test/fixtures/hq-pack-smoke-mcp/package.yaml +0 -11
  300. package/test/fixtures/signals/action_item/sample.md +0 -16
  301. package/test/fixtures/signals/summary/sample.md +0 -12
  302. package/test/fixtures/sources/meetings/sample.md +0 -25
  303. package/test/helpers/cli-runner.ts +0 -150
  304. package/test/helpers/s3-list-mock.ts +0 -79
  305. package/test/helpers/vault-service-mock.ts +0 -295
  306. package/test/sources-signals/smoke.test.ts +0 -228
  307. package/tsconfig.json +0 -20
  308. package/vitest.config.ts +0 -11
  309. package/vitest.e2e.config.ts +0 -7
@@ -1,2050 +0,0 @@
1
- import {
2
- afterEach,
3
- beforeEach,
4
- describe,
5
- expect,
6
- it,
7
- vi,
8
- type MockInstance,
9
- } from "vitest";
10
- import { createHash } from "node:crypto";
11
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
12
- import { tmpdir } from "node:os";
13
- import { join } from "node:path";
14
-
15
- vi.mock("../utils/cognito-session.js", async (importOriginal) => {
16
- const original = (await importOriginal()) as Record<string, unknown>;
17
- return {
18
- ...original,
19
- ensureCognitoToken: vi.fn(async () => "test-token"),
20
- };
21
- });
22
-
23
- vi.mock("../utils/vault-api.js", async (importOriginal) => {
24
- const original = (await importOriginal()) as Record<string, unknown>;
25
- return {
26
- ...original,
27
- getEntityUid: vi.fn(async () => "prs_alice"),
28
- vaultApiFetch: vi.fn(async () =>
29
- new Response(
30
- JSON.stringify({
31
- url: "https://hq.example/secrets-input/tok_secret",
32
- expiresAt: "2026-05-12T12:00:00.000Z",
33
- secretName: "MY_KEY",
34
- }),
35
- { status: 200, headers: { "Content-Type": "application/json" } },
36
- ),
37
- ),
38
- };
39
- });
40
-
41
- vi.mock("../utils/secrets-cache.js", async (importOriginal) => {
42
- const original = (await importOriginal()) as Record<string, unknown>;
43
- return {
44
- ...original,
45
- readCache: vi.fn(() => null),
46
- writeCache: vi.fn(() => undefined),
47
- removeCacheEntry: vi.fn(() => undefined),
48
- };
49
- });
50
-
51
- vi.mock("node:child_process", () => ({
52
- spawn: vi.fn(() => ({
53
- on: vi.fn(),
54
- })),
55
- }));
56
-
57
- import { Command } from "commander";
58
- import {
59
- registerSecretsCommand,
60
- loadRevealedSecrets,
61
- type SecretUsageChannel,
62
- } from "./secrets.js";
63
- import { spawn } from "node:child_process";
64
- import { ensureCognitoToken } from "../utils/cognito-session.js";
65
- import { getEntityUid, vaultApiFetch } from "../utils/vault-api.js";
66
- import {
67
- readCache,
68
- removeCacheEntry,
69
- writeCache,
70
- } from "../utils/secrets-cache.js";
71
- import { SandboxRunnerClient } from "../utils/sandbox-runner-client.js";
72
-
73
- let logSpy: MockInstance<typeof console.log>;
74
- let errSpy: MockInstance<typeof console.error>;
75
- let tempDir: string;
76
-
77
- beforeEach(() => {
78
- vi.clearAllMocks();
79
- tempDir = mkdtempSync(join(tmpdir(), "hq-secrets-test-"));
80
- logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
81
- errSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
82
- });
83
-
84
- afterEach(() => {
85
- rmSync(tempDir, { recursive: true, force: true });
86
- vi.restoreAllMocks();
87
- });
88
-
89
- function buildProgram(): Command {
90
- const program = new Command();
91
- program.exitOverride();
92
- program.configureOutput({
93
- writeOut: () => undefined,
94
- writeErr: () => undefined,
95
- });
96
- registerSecretsCommand(program);
97
- return program;
98
- }
99
-
100
- function jsonRes(body: unknown, status = 200): Response {
101
- return new Response(JSON.stringify(body), {
102
- status,
103
- headers: { "Content-Type": "application/json" },
104
- });
105
- }
106
-
107
- describe("secrets sandbox", () => {
108
- let stdoutSpy: MockInstance<typeof process.stdout.write>;
109
- let stderrSpy: MockInstance<typeof process.stderr.write>;
110
- let exitSpy: MockInstance<typeof process.exit>;
111
- let startJobSpy: MockInstance<SandboxRunnerClient["startJob"]>;
112
- let pollJobSpy: MockInstance<SandboxRunnerClient["pollJob"]>;
113
- let getJobSpy: MockInstance<SandboxRunnerClient["getJob"]>;
114
-
115
- beforeEach(() => {
116
- stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
117
- stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
118
- startJobSpy = vi
119
- .spyOn(SandboxRunnerClient.prototype, "startJob")
120
- .mockResolvedValue({ jobId: "job_123", status: "queued" });
121
- pollJobSpy = vi
122
- .spyOn(SandboxRunnerClient.prototype, "pollJob")
123
- .mockResolvedValue({
124
- jobId: "job_123",
125
- status: "succeeded",
126
- output: "done\n",
127
- exitCode: 0,
128
- success: true,
129
- });
130
- getJobSpy = vi.spyOn(SandboxRunnerClient.prototype, "getJob");
131
- exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
132
- throw new Error("__exit__");
133
- }) as never);
134
- });
135
-
136
- it("registers the sandbox channel value", () => {
137
- const channel: SecretUsageChannel = "sandbox";
138
- expect(channel).toBe("sandbox");
139
- });
140
-
141
- it("runs a high-security secret in the sandbox without a local script attestation", async () => {
142
- const program = buildProgram();
143
- await program.parseAsync([
144
- "node",
145
- "hq",
146
- "secrets",
147
- "sandbox",
148
- "--only",
149
- "HIGH_SECURITY_KEY",
150
- "--",
151
- "env",
152
- ]);
153
-
154
- expect(startJobSpy).toHaveBeenCalledWith("test-token", {
155
- companyUid: "prs_alice",
156
- secretNames: ["HIGH_SECURITY_KEY"],
157
- command: "env",
158
- });
159
- expect(vaultApiFetch).not.toHaveBeenCalledWith(
160
- expect.objectContaining({ path: expect.stringContaining("/load") }),
161
- );
162
- });
163
-
164
- it("parses --company, --only, and joins args after -- into a command", async () => {
165
- const program = buildProgram();
166
- await program.parseAsync([
167
- "node",
168
- "hq",
169
- "secrets",
170
- "sandbox",
171
- "--company",
172
- "acme",
173
- "--only",
174
- "API_KEY,OTHER_KEY",
175
- "--",
176
- "node",
177
- "-e",
178
- "console.log('hi')",
179
- "--days",
180
- "7",
181
- ]);
182
-
183
- expect(startJobSpy).toHaveBeenCalledWith("test-token", {
184
- companyUid: "prs_alice",
185
- secretNames: ["API_KEY", "OTHER_KEY"],
186
- command: "node -e console.log('hi') --days 7",
187
- });
188
- expect(stdoutSpy).toHaveBeenCalledWith("done\n");
189
- });
190
-
191
- it("accumulates repeated --only flags instead of silently keeping only the last", async () => {
192
- const program = buildProgram();
193
- await program.parseAsync([
194
- "node",
195
- "hq",
196
- "secrets",
197
- "sandbox",
198
- "--company",
199
- "acme",
200
- "--only",
201
- "API_KEY,OTHER_KEY",
202
- "--only",
203
- "THIRD_KEY",
204
- "--",
205
- "env",
206
- ]);
207
-
208
- expect(startJobSpy).toHaveBeenCalledWith("test-token", {
209
- companyUid: "prs_alice",
210
- secretNames: ["API_KEY", "OTHER_KEY", "THIRD_KEY"],
211
- command: "env",
212
- });
213
- });
214
-
215
- it("requires --only", async () => {
216
- const program = buildProgram();
217
-
218
- await expect(
219
- program.parseAsync([
220
- "node",
221
- "hq",
222
- "secrets",
223
- "sandbox",
224
- "--",
225
- "env",
226
- ]),
227
- ).rejects.toThrow("__exit__");
228
-
229
- expect(exitSpy).toHaveBeenCalledWith(1);
230
- expect(errSpy.mock.calls.flat().join(" ")).toMatch(/--only is required/i);
231
- expect(startJobSpy).not.toHaveBeenCalled();
232
- });
233
-
234
- it("requires a command after --", async () => {
235
- const program = buildProgram();
236
-
237
- await expect(
238
- program.parseAsync([
239
- "node",
240
- "hq",
241
- "secrets",
242
- "sandbox",
243
- "--only",
244
- "API_KEY",
245
- ]),
246
- ).rejects.toThrow("__exit__");
247
-
248
- expect(exitSpy).toHaveBeenCalledWith(1);
249
- expect(errSpy.mock.calls.flat().join(" ")).toMatch(/no command specified/i);
250
- expect(startJobSpy).not.toHaveBeenCalled();
251
- });
252
-
253
- it("resolves identity before posting the runner job", async () => {
254
- const program = buildProgram();
255
- await program.parseAsync([
256
- "node",
257
- "hq",
258
- "secrets",
259
- "--company",
260
- "parent-co",
261
- "sandbox",
262
- "--only",
263
- "API_KEY",
264
- "--",
265
- "env",
266
- ]);
267
-
268
- expect(ensureCognitoToken).toHaveBeenCalled();
269
- expect(getEntityUid).toHaveBeenCalledWith("test-token", {
270
- personal: false,
271
- companySlug: "parent-co",
272
- });
273
- expect(startJobSpy).toHaveBeenCalledWith("test-token", {
274
- companyUid: "prs_alice",
275
- secretNames: ["API_KEY"],
276
- command: "env",
277
- });
278
- });
279
-
280
- it("prints server-scrubbed output and never batch-loads secrets locally", async () => {
281
- pollJobSpy.mockResolvedValueOnce({
282
- jobId: "job_123",
283
- status: "succeeded",
284
- output: "token [REDACTED]\nAPI_KEY=[REDACTED]\n",
285
- exitCode: 0,
286
- success: true,
287
- });
288
-
289
- const program = buildProgram();
290
- await program.parseAsync([
291
- "node",
292
- "hq",
293
- "secrets",
294
- "sandbox",
295
- "--only",
296
- "API_KEY",
297
- "--",
298
- "my-skill",
299
- ]);
300
-
301
- expect(vaultApiFetch).not.toHaveBeenCalledWith(
302
- expect.objectContaining({ path: expect.stringContaining("/load") }),
303
- );
304
- expect(vaultApiFetch).not.toHaveBeenCalledWith(
305
- expect.objectContaining({ path: expect.stringContaining("/name/") }),
306
- );
307
- const rendered = [
308
- ...stdoutSpy.mock.calls.flat().map(String),
309
- ...stderrSpy.mock.calls.flat().map(String),
310
- ...logSpy.mock.calls.flat().map(String),
311
- ...errSpy.mock.calls.flat().map(String),
312
- ].join("\n");
313
- expect(rendered).toContain("[REDACTED]");
314
- expect(stdoutSpy).toHaveBeenCalledWith("token [REDACTED]\nAPI_KEY=[REDACTED]\n");
315
- });
316
-
317
- it("terminates sandbox output with exactly one newline when output is present", async () => {
318
- pollJobSpy.mockResolvedValueOnce({
319
- jobId: "job_123",
320
- status: "succeeded",
321
- output: "123",
322
- exitCode: 0,
323
- success: true,
324
- });
325
-
326
- const program = buildProgram();
327
- await program.parseAsync([
328
- "node",
329
- "hq",
330
- "secrets",
331
- "sandbox",
332
- "--only",
333
- "API_KEY",
334
- "--",
335
- "my-skill",
336
- ]);
337
-
338
- expect(stdoutSpy.mock.calls.flat().join("")).toBe("123\n");
339
-
340
- stdoutSpy.mockClear();
341
- pollJobSpy.mockResolvedValueOnce({
342
- jobId: "job_123",
343
- status: "succeeded",
344
- output: "123\n",
345
- exitCode: 0,
346
- success: true,
347
- });
348
-
349
- await buildProgram().parseAsync([
350
- "node",
351
- "hq",
352
- "secrets",
353
- "sandbox",
354
- "--only",
355
- "API_KEY",
356
- "--",
357
- "my-skill",
358
- ]);
359
-
360
- expect(stdoutSpy.mock.calls.flat().join("")).toBe("123\n");
361
-
362
- stdoutSpy.mockClear();
363
- pollJobSpy.mockResolvedValueOnce({
364
- jobId: "job_123",
365
- status: "succeeded",
366
- output: "",
367
- exitCode: 0,
368
- success: true,
369
- });
370
-
371
- await buildProgram().parseAsync([
372
- "node",
373
- "hq",
374
- "secrets",
375
- "sandbox",
376
- "--only",
377
- "API_KEY",
378
- "--",
379
- "my-skill",
380
- ]);
381
-
382
- expect(stdoutSpy).not.toHaveBeenCalled();
383
-
384
- stdoutSpy.mockClear();
385
- pollJobSpy.mockResolvedValueOnce({
386
- jobId: "job_123",
387
- status: "succeeded",
388
- exitCode: 0,
389
- success: true,
390
- });
391
-
392
- await buildProgram().parseAsync([
393
- "node",
394
- "hq",
395
- "secrets",
396
- "sandbox",
397
- "--only",
398
- "API_KEY",
399
- "--",
400
- "my-skill",
401
- ]);
402
-
403
- expect(stdoutSpy).not.toHaveBeenCalled();
404
- });
405
-
406
- it("renders the server error without inventing an exit code when sandbox execution fails", async () => {
407
- pollJobSpy.mockResolvedValueOnce({
408
- jobId: "job_123",
409
- status: "failed",
410
- error: "Cloudflare worker timed out with API_KEY=secret-value",
411
- success: false,
412
- });
413
-
414
- const program = buildProgram();
415
- await expect(
416
- program.parseAsync([
417
- "node",
418
- "hq",
419
- "secrets",
420
- "sandbox",
421
- "--only",
422
- "API_KEY",
423
- "--",
424
- "my-skill",
425
- ]),
426
- ).rejects.toThrow("__exit__");
427
-
428
- const renderedError = errSpy.mock.calls.flat().join(" ");
429
- expect(renderedError).toContain("Cloudflare worker timed out with API_KEY=[REDACTED]");
430
- // The redacted form appearing is not enough — the raw value must be gone.
431
- expect(renderedError).not.toContain("secret-value");
432
- expect(renderedError).not.toMatch(/exit code 1/i);
433
- expect(exitSpy).toHaveBeenCalledWith(1);
434
- });
435
-
436
- it("still explains a failure that carries neither an exit code nor a reason", async () => {
437
- pollJobSpy.mockResolvedValueOnce({
438
- jobId: "job_123",
439
- status: "failed",
440
- success: false,
441
- });
442
-
443
- const program = buildProgram();
444
- await expect(
445
- program.parseAsync([
446
- "node",
447
- "hq",
448
- "secrets",
449
- "sandbox",
450
- "--only",
451
- "API_KEY",
452
- "--",
453
- "my-skill",
454
- ]),
455
- ).rejects.toThrow("__exit__");
456
-
457
- const renderedError = errSpy.mock.calls.flat().join(" ");
458
- expect(renderedError).toMatch(/sandbox execution failed/i);
459
- expect(renderedError).not.toMatch(/exit code 1/i);
460
- expect(exitSpy).toHaveBeenCalledWith(1);
461
- });
462
-
463
- it("preserves the real exit code when the sandbox command exits non-zero", async () => {
464
- pollJobSpy.mockResolvedValueOnce({
465
- jobId: "job_123",
466
- status: "failed",
467
- output: "boom\n",
468
- exitCode: 2,
469
- success: false,
470
- });
471
-
472
- const program = buildProgram();
473
- await expect(
474
- program.parseAsync([
475
- "node",
476
- "hq",
477
- "secrets",
478
- "sandbox",
479
- "--only",
480
- "API_KEY",
481
- "--",
482
- "my-skill",
483
- ]),
484
- ).rejects.toThrow("__exit__");
485
-
486
- expect(stdoutSpy).toHaveBeenCalledWith("boom\n");
487
- expect(errSpy.mock.calls.flat().join(" ")).toMatch(/exit code 2/i);
488
- expect(exitSpy).toHaveBeenCalledWith(2);
489
- expect(getJobSpy).not.toHaveBeenCalled();
490
- });
491
- });
492
-
493
- // HQ-4H: `hq secrets exists` — HEAD existence probe with shell-chaining exit
494
- // codes (0=present, 1=absent, 2=error). process.exit is spied so the command's
495
- // terminal exit doesn't kill the runner; we assert the code it requested.
496
- describe("secrets exists (HQ-4H HEAD probe)", () => {
497
- let exitSpy: MockInstance<typeof process.exit>;
498
-
499
- beforeEach(() => {
500
- // Throw so the command stops at its first process.exit (the real runtime
501
- // terminates there). The action's own try/catch re-invokes exit(2) on the
502
- // thrown sentinel, so we assert on the FIRST recorded exit code — the one
503
- // the command actually intended — not the last.
504
- exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
505
- throw new Error("__exit__");
506
- }) as never);
507
- });
508
-
509
- async function firstExitCode(name: string): Promise<number | undefined> {
510
- const program = buildProgram();
511
- try {
512
- await program.parseAsync(["node", "hq", "secrets", "exists", name]);
513
- } catch {
514
- // sentinel(s) from the exit spy
515
- }
516
- return exitSpy.mock.calls[0]?.[0] as number | undefined;
517
- }
518
-
519
- it("issues a HEAD and intends exit 0 when the secret exists (200)", async () => {
520
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
521
- new Response(null, { status: 200 }),
522
- );
523
-
524
- const code = await firstExitCode("MY_KEY");
525
-
526
- expect(vaultApiFetch).toHaveBeenCalledWith({
527
- token: "test-token",
528
- method: "HEAD",
529
- path: "/secrets/prs_alice/name/MY_KEY",
530
- });
531
- expect(code).toBe(0);
532
- });
533
-
534
- it("intends exit 1 (absent, not an error) on 404", async () => {
535
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
536
- new Response(
537
- JSON.stringify({ error: "Secret not found", name: "MISSING" }),
538
- { status: 404, headers: { "Content-Type": "application/json" } },
539
- ),
540
- );
541
-
542
- const code = await firstExitCode("MISSING");
543
-
544
- expect(code).toBe(1);
545
- });
546
-
547
- it("intends exit 2 (real failure, distinct from absence) on a 5xx", async () => {
548
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
549
- new Response("boom", { status: 503 }),
550
- );
551
-
552
- const code = await firstExitCode("MY_KEY");
553
-
554
- expect(code).toBe(2);
555
- });
556
- });
557
-
558
- // US-003 (secrets-server-proxy): the CLI surfaces the SERVER's refusal of a
559
- // high-security ("nuclear") secret on the local-injection path as a clear,
560
- // actionable sandbox/proxy error — and never prints the value. The server-side
561
- // deny is the real control (it returns 403 + highSecurity:true and NO
562
- // plaintext); these tests assert the CLI's surfacing behavior.
563
- describe("US-003 — CLI refuses high-security secrets on local injection", () => {
564
- // The server's 403 refusal shape for a high-security secret.
565
- function highSecurityDenied(): Response {
566
- return new Response(
567
- JSON.stringify({
568
- error:
569
- "Secret 'ANTHROPIC_API_KEY' is high-security and cannot be retrieved via local injection. Use the server-side proxy.",
570
- highSecurity: true,
571
- }),
572
- { status: 403, headers: { "Content-Type": "application/json" } },
573
- );
574
- }
575
-
576
- function highSecuritySandboxOnly(): Response {
577
- return jsonRes({
578
- secrets: [],
579
- errors: [
580
- {
581
- name: "ANTHROPIC_API_KEY",
582
- code: "high_security_sandbox_only",
583
- message:
584
- "High-security-tier secrets can run only in the sandbox (`hq secrets sandbox`) or through the secret proxy. Local injection and script locks (`--script`) are not supported.",
585
- },
586
- ],
587
- });
588
- }
589
-
590
- let exitSpy: MockInstance<typeof process.exit>;
591
- beforeEach(() => {
592
- exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
593
- throw new Error("__exit__");
594
- }) as never);
595
- });
596
-
597
- it("E2E: `secrets get --reveal` is denied — clear proxy-pointing error, no value printed", async () => {
598
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(highSecurityDenied());
599
-
600
- const program = buildProgram();
601
- try {
602
- await program.parseAsync([
603
- "node",
604
- "hq",
605
- "secrets",
606
- "get",
607
- "ANTHROPIC_API_KEY",
608
- "--reveal",
609
- ]);
610
- } catch {
611
- // exit sentinel
612
- }
613
- const exitCode = exitSpy.mock.calls[0]?.[0] as number | undefined;
614
-
615
- expect(exitCode).toBe(1);
616
- // A clear, actionable error names the sandbox/proxy boundary and rules
617
- // out script-lock bypasses.
618
- const errText = errSpy.mock.calls.flat().join(" ");
619
- expect(errText).toMatch(/high-security/i);
620
- expect(errText).toMatch(/hq secrets sandbox/i);
621
- expect(errText).toMatch(/proxy/i);
622
- expect(errText).toMatch(/--script/);
623
- // The value is NEVER printed — no "Value:" line carrying plaintext.
624
- const logText = logSpy.mock.calls.flat().join(" ");
625
- expect(logText).not.toMatch(/sk-ant/i);
626
- });
627
-
628
- it("E2E: `secrets exec --script <path>` is denied — sandbox guidance, command not run", async () => {
629
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(highSecuritySandboxOnly());
630
- const scriptPath = join(tempDir, "deploy.sh");
631
- writeFileSync(scriptPath, "#!/usr/bin/env bash\necho deploy\n");
632
-
633
- const program = buildProgram();
634
- try {
635
- await program.parseAsync([
636
- "node",
637
- "hq",
638
- "secrets",
639
- "exec",
640
- "--only",
641
- "ANTHROPIC_API_KEY",
642
- "--script",
643
- scriptPath,
644
- "--script-id",
645
- "script.deploy",
646
- "--",
647
- "env",
648
- ]);
649
- } catch {
650
- // exit sentinel
651
- }
652
- const exitCode = exitSpy.mock.calls[0]?.[0] as number | undefined;
653
-
654
- expect(exitCode).toBe(1);
655
- const errText = errSpy.mock.calls.flat().join(" ");
656
- expect(errText).toMatch(/high-security/i);
657
- expect(errText).toMatch(/hq secrets sandbox/i);
658
- expect(errText).toMatch(/proxy/i);
659
- expect(errText).toMatch(/--script/);
660
- expect(spawn).not.toHaveBeenCalled();
661
- });
662
- });
663
-
664
- // secrets-proxy-per-secret-destination US-006: hq-cli creation-side parity.
665
- // `hq secrets set NAME --high-security --destination <url> [--auth-style ...]`
666
- // POSTs `highSecurity`/`destinations`/`injection` to the vault API — the CLI
667
- // counterpart to the console create-form (US-005) and the server contract
668
- // (US-001/US-004). Value input is exercised via --from-stdin (unaffected by
669
- // this story) so these tests isolate the new flag-handling/validation.
670
- describe("US-006 — hq secrets set --high-security --destination parity", () => {
671
- let exitSpy: MockInstance<typeof process.exit>;
672
- let stdinIsTTYSpy: MockInstance<() => boolean> | undefined;
673
-
674
- beforeEach(() => {
675
- exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
676
- throw new Error("__exit__");
677
- }) as never);
678
- });
679
-
680
- afterEach(() => {
681
- stdinIsTTYSpy?.mockRestore();
682
- stdinIsTTYSpy = undefined;
683
- });
684
-
685
- // Drives the value through the existing --from-stdin path (unchanged by
686
- // this story) by feeding a piped-stdin double: mocks isTTY=false and
687
- // replaces the data/end listeners `readFromPipedStdin` attaches.
688
- function stubPipedStdin(value: string): void {
689
- Object.defineProperty(process.stdin, "isTTY", {
690
- configurable: true,
691
- value: false,
692
- });
693
- vi.spyOn(process.stdin, "on").mockImplementation(((
694
- event: string,
695
- cb: (...args: unknown[]) => void,
696
- ) => {
697
- if (event === "data") cb(value);
698
- if (event === "end") cb();
699
- return process.stdin;
700
- }) as never);
701
- }
702
-
703
- it("with no flags, the POST body is byte-for-byte unchanged (just name+value)", async () => {
704
- stubPipedStdin("plain-value");
705
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
706
-
707
- const program = buildProgram();
708
- await program.parseAsync([
709
- "node",
710
- "hq",
711
- "secrets",
712
- "set",
713
- "MY_KEY",
714
- "--from-stdin",
715
- ]);
716
-
717
- expect(vaultApiFetch).toHaveBeenCalledWith({
718
- token: "test-token",
719
- path: "/secrets/prs_alice",
720
- method: "POST",
721
- body: { name: "MY_KEY", value: "plain-value" },
722
- });
723
- expect(errSpy).not.toHaveBeenCalled();
724
- });
725
-
726
- it("--high-security with a KNOWN destination auto-resolves the recipe (no --auth-style needed)", async () => {
727
- stubPipedStdin("sk-secret-value");
728
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
729
-
730
- const program = buildProgram();
731
- await program.parseAsync([
732
- "node",
733
- "hq",
734
- "secrets",
735
- "set",
736
- "OPENAI_KEY",
737
- "--from-stdin",
738
- "--high-security",
739
- "--destination",
740
- "https://api.openai.com",
741
- ]);
742
-
743
- expect(vaultApiFetch).toHaveBeenCalledWith({
744
- token: "test-token",
745
- path: "/secrets/prs_alice",
746
- method: "POST",
747
- body: {
748
- name: "OPENAI_KEY",
749
- value: "sk-secret-value",
750
- highSecurity: true,
751
- destinations: ["https://api.openai.com"],
752
- },
753
- });
754
- expect(errSpy).not.toHaveBeenCalled();
755
- expect(logSpy.mock.calls.flat().join(" ")).toMatch(/high-security/i);
756
- });
757
-
758
- it("--auth-style bearer maps to {header: authorization, scheme: bearer}", async () => {
759
- stubPipedStdin("bearer-token-value");
760
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
761
-
762
- const program = buildProgram();
763
- await program.parseAsync([
764
- "node",
765
- "hq",
766
- "secrets",
767
- "set",
768
- "SOME_BEARER_KEY",
769
- "--from-stdin",
770
- "--high-security",
771
- "--destination",
772
- "https://api.example.com",
773
- "--auth-style",
774
- "bearer",
775
- ]);
776
-
777
- expect(vaultApiFetch).toHaveBeenCalledWith({
778
- token: "test-token",
779
- path: "/secrets/prs_alice",
780
- method: "POST",
781
- body: {
782
- name: "SOME_BEARER_KEY",
783
- value: "bearer-token-value",
784
- highSecurity: true,
785
- destinations: ["https://api.example.com"],
786
- injection: { header: "authorization", scheme: "bearer" },
787
- },
788
- });
789
- });
790
-
791
- it("--auth-style x-api-key maps to {header: x-api-key, scheme: raw}", async () => {
792
- stubPipedStdin("raw-key-value");
793
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
794
-
795
- const program = buildProgram();
796
- await program.parseAsync([
797
- "node",
798
- "hq",
799
- "secrets",
800
- "set",
801
- "SOME_RAW_KEY",
802
- "--from-stdin",
803
- "--high-security",
804
- "--destination",
805
- "https://api.example.com",
806
- "--auth-style",
807
- "x-api-key",
808
- ]);
809
-
810
- expect(vaultApiFetch).toHaveBeenCalledWith({
811
- token: "test-token",
812
- path: "/secrets/prs_alice",
813
- method: "POST",
814
- body: {
815
- name: "SOME_RAW_KEY",
816
- value: "raw-key-value",
817
- highSecurity: true,
818
- destinations: ["https://api.example.com"],
819
- injection: { header: "x-api-key", scheme: "raw" },
820
- },
821
- });
822
- });
823
-
824
- it("--auth-style header:NAME maps to a custom raw header", async () => {
825
- stubPipedStdin("custom-header-value");
826
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
827
-
828
- const program = buildProgram();
829
- await program.parseAsync([
830
- "node",
831
- "hq",
832
- "secrets",
833
- "set",
834
- "CUSTOM_HEADER_KEY",
835
- "--from-stdin",
836
- "--high-security",
837
- "--destination",
838
- "https://api.example.com",
839
- "--auth-style",
840
- "header:X-Custom-Key",
841
- ]);
842
-
843
- expect(vaultApiFetch).toHaveBeenCalledWith({
844
- token: "test-token",
845
- path: "/secrets/prs_alice",
846
- method: "POST",
847
- body: {
848
- name: "CUSTOM_HEADER_KEY",
849
- value: "custom-header-value",
850
- highSecurity: true,
851
- destinations: ["https://api.example.com"],
852
- injection: { header: "X-Custom-Key", scheme: "raw" },
853
- },
854
- });
855
- });
856
-
857
- it("--high-security with an UNKNOWN host and no --auth-style errors clearly, client-side (no request sent)", async () => {
858
- const program = buildProgram();
859
- await expect(
860
- program.parseAsync([
861
- "node",
862
- "hq",
863
- "secrets",
864
- "set",
865
- "UNKNOWN_HOST_KEY",
866
- "--from-stdin",
867
- "--high-security",
868
- "--destination",
869
- "https://api.unknown-vendor.example",
870
- ]),
871
- ).rejects.toThrow("__exit__");
872
-
873
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
874
- const errText = errSpy.mock.calls.flat().join(" ");
875
- expect(errText).toMatch(/unknown destination host/i);
876
- expect(errText).toMatch(/--auth-style/);
877
- // Client-side rejection — never reaches the network.
878
- expect(vaultApiFetch).not.toHaveBeenCalled();
879
- });
880
-
881
- it("--high-security with no --destination errors clearly (non-zero exit, no request sent)", async () => {
882
- const program = buildProgram();
883
- await expect(
884
- program.parseAsync([
885
- "node",
886
- "hq",
887
- "secrets",
888
- "set",
889
- "MISSING_DEST_KEY",
890
- "--from-stdin",
891
- "--high-security",
892
- ]),
893
- ).rejects.toThrow("__exit__");
894
-
895
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
896
- const errText = errSpy.mock.calls.flat().join(" ");
897
- expect(errText).toMatch(/--high-security/);
898
- expect(errText).toMatch(/--destination/);
899
- expect(vaultApiFetch).not.toHaveBeenCalled();
900
- });
901
-
902
- it("--destination without --high-security errors clearly (non-zero exit, no request sent)", async () => {
903
- const program = buildProgram();
904
- await expect(
905
- program.parseAsync([
906
- "node",
907
- "hq",
908
- "secrets",
909
- "set",
910
- "STRAY_DEST_KEY",
911
- "--from-stdin",
912
- "--destination",
913
- "https://api.openai.com",
914
- ]),
915
- ).rejects.toThrow("__exit__");
916
-
917
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
918
- expect(vaultApiFetch).not.toHaveBeenCalled();
919
- });
920
-
921
- it("an invalid --destination URL (path segment) errors clearly, client-side", async () => {
922
- const program = buildProgram();
923
- await expect(
924
- program.parseAsync([
925
- "node",
926
- "hq",
927
- "secrets",
928
- "set",
929
- "BAD_URL_KEY",
930
- "--from-stdin",
931
- "--high-security",
932
- "--destination",
933
- "https://api.openai.com/v1",
934
- ]),
935
- ).rejects.toThrow("__exit__");
936
-
937
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
938
- const errText = errSpy.mock.calls.flat().join(" ");
939
- expect(errText).toMatch(/no path, query, or fragment/i);
940
- expect(vaultApiFetch).not.toHaveBeenCalled();
941
- });
942
-
943
- it("surfaces the server's rejection message when the backend 400s (e.g. unknown host drift)", async () => {
944
- stubPipedStdin("value");
945
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
946
- jsonRes(
947
- {
948
- error:
949
- "unknown destination host api.newer-vendor.com: provide an injection recipe (header + scheme)",
950
- },
951
- 400,
952
- ),
953
- );
954
-
955
- const program = buildProgram();
956
- // A host absent from the CLI's own known-set copy but WOULD be flagged
957
- // client-side too (this asserts the server-error surfacing path itself
958
- // stays intact, using --auth-style to bypass the client-side check and
959
- // reach the network).
960
- await expect(
961
- program.parseAsync([
962
- "node",
963
- "hq",
964
- "secrets",
965
- "set",
966
- "DRIFT_KEY",
967
- "--from-stdin",
968
- "--high-security",
969
- "--destination",
970
- "https://api.newer-vendor.com",
971
- "--auth-style",
972
- "bearer",
973
- ]),
974
- ).rejects.toThrow("__exit__");
975
-
976
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
977
- const errText = errSpy.mock.calls.flat().join(" ");
978
- expect(errText).toMatch(/unknown destination host/i);
979
- });
980
- });
981
-
982
- describe("secrets generate-link", () => {
983
- it("mints one-time submission links for personal secrets", async () => {
984
- const program = buildProgram();
985
-
986
- await program.parseAsync([
987
- "node",
988
- "hq",
989
- "secrets",
990
- "--personal",
991
- "generate-link",
992
- "MY_KEY",
993
- "--expires",
994
- "30m",
995
- ]);
996
-
997
- expect(getEntityUid).toHaveBeenCalledWith("test-token", {
998
- personal: true,
999
- companySlug: undefined,
1000
- });
1001
- expect(vaultApiFetch).toHaveBeenCalledWith({
1002
- token: "test-token",
1003
- path: "/secrets/prs_alice/name/MY_KEY",
1004
- method: "POST",
1005
- body: { expiresInMs: 30 * 60 * 1000 },
1006
- query: { action: "generate-token" },
1007
- });
1008
- expect(logSpy).toHaveBeenCalledWith(
1009
- expect.stringContaining("Secret input link generated"),
1010
- );
1011
- expect(errSpy).not.toHaveBeenCalled();
1012
- });
1013
- });
1014
-
1015
- describe("secrets share ACL principals", () => {
1016
- it("grants a secret to a group principal", async () => {
1017
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1018
-
1019
- const program = buildProgram();
1020
- await program.parseAsync([
1021
- "node",
1022
- "hq",
1023
- "secrets",
1024
- "share",
1025
- "MY_KEY",
1026
- "--with",
1027
- "grp_ops",
1028
- "--permission",
1029
- "read",
1030
- ]);
1031
-
1032
- expect(vaultApiFetch).toHaveBeenCalledWith({
1033
- token: "test-token",
1034
- path: "/secrets/prs_alice/acl/grant",
1035
- method: "POST",
1036
- body: {
1037
- path: "MY_KEY",
1038
- granteeType: "group",
1039
- granteeId: "grp_ops",
1040
- permission: "read",
1041
- },
1042
- });
1043
- });
1044
-
1045
- it("grants a secret company-wide with @all", async () => {
1046
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1047
-
1048
- const program = buildProgram();
1049
- await program.parseAsync([
1050
- "node",
1051
- "hq",
1052
- "secrets",
1053
- "share",
1054
- "MY_KEY",
1055
- "--with",
1056
- "@all",
1057
- "--permission",
1058
- "read",
1059
- ]);
1060
-
1061
- expect(vaultApiFetch).toHaveBeenCalledWith({
1062
- token: "test-token",
1063
- path: "/secrets/prs_alice/acl/grant",
1064
- method: "POST",
1065
- body: {
1066
- path: "MY_KEY",
1067
- granteeType: "company-wide",
1068
- granteeId: "",
1069
- permission: "read",
1070
- },
1071
- });
1072
- });
1073
-
1074
- it("revokes a company-wide grant with @all", async () => {
1075
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1076
-
1077
- const program = buildProgram();
1078
- await program.parseAsync([
1079
- "node",
1080
- "hq",
1081
- "secrets",
1082
- "unshare",
1083
- "MY_KEY",
1084
- "--from",
1085
- "@all",
1086
- ]);
1087
-
1088
- expect(vaultApiFetch).toHaveBeenCalledWith({
1089
- token: "test-token",
1090
- path: "/secrets/prs_alice/acl/revoke",
1091
- method: "POST",
1092
- body: {
1093
- path: "MY_KEY",
1094
- granteeType: "company-wide",
1095
- granteeId: "",
1096
- },
1097
- });
1098
- });
1099
- });
1100
-
1101
- // HQ-4H — `hq secrets exec`/`env` load secrets through the BATCH-LOAD endpoint
1102
- // (`POST /secrets/{uid}/load`), which returns 200 + per-name `errors[]` and
1103
- // never fires the server's "Secret not found" Sentry warning. The old per-key
1104
- // path single-GET'd `/secrets/{uid}/name/{name}?reveal=true`, and EVERY such
1105
- // 404 made vault-service capture an (unattributable) warning. These tests pin
1106
- // that the caller no longer touches the capturing GET route — the differential
1107
- // at the client boundary that "stops the caller from emitting the error event".
1108
- describe("secrets exec/env batch-load (HQ-4H)", () => {
1109
- function jsonRes(body: unknown, status = 200): Response {
1110
- return new Response(JSON.stringify(body), {
1111
- status,
1112
- headers: { "Content-Type": "application/json" },
1113
- });
1114
- }
1115
-
1116
- // A path that contains the single-secret GET segment — the route whose 404
1117
- // fires the capture. The whole fix is that we never call it from exec/env.
1118
- const CAPTURING_GET = expect.objectContaining({
1119
- path: expect.stringContaining("/name/"),
1120
- });
1121
-
1122
- beforeEach(() => {
1123
- vi.mocked(readCache).mockReturnValue(null);
1124
- });
1125
-
1126
- it("loads via /load (POST) and never the capturing single-secret GET", async () => {
1127
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1128
- jsonRes({
1129
- secrets: [
1130
- { name: "MY_KEY", value: "v1", cacheTtlMs: 300000 },
1131
- { name: "OTHER", value: "v2", cacheTtlMs: 300000 },
1132
- ],
1133
- errors: [],
1134
- }),
1135
- );
1136
-
1137
- const out = await loadRevealedSecrets("test-token", "prs_alice", [
1138
- "MY_KEY",
1139
- "OTHER",
1140
- ]);
1141
-
1142
- expect(out.get("MY_KEY")).toBe("v1");
1143
- expect(out.get("OTHER")).toBe("v2");
1144
- expect(vaultApiFetch).toHaveBeenCalledTimes(1);
1145
- expect(vaultApiFetch).toHaveBeenCalledWith({
1146
- token: "test-token",
1147
- path: "/secrets/prs_alice/load",
1148
- method: "POST",
1149
- body: { names: ["MY_KEY", "OTHER"] },
1150
- signal: expect.any(AbortSignal),
1151
- });
1152
- // The crux: the capturing GET route is never touched.
1153
- expect(vaultApiFetch).not.toHaveBeenCalledWith(CAPTURING_GET);
1154
- expect(writeCache).toHaveBeenCalledWith("prs_alice", "MY_KEY", "v1", 300000);
1155
- expect(writeCache).toHaveBeenCalledWith("prs_alice", "OTHER", "v2", 300000);
1156
- });
1157
-
1158
- it("controlled policy metadata overrides a malformed positive cache TTL", async () => {
1159
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1160
- jsonRes({
1161
- secrets: [
1162
- {
1163
- name: "LOCKED",
1164
- value: "v1",
1165
- tier: "sensitive",
1166
- scriptLock: { mode: "enforced" },
1167
- cacheTtlMs: 300000,
1168
- },
1169
- ],
1170
- errors: [],
1171
- }),
1172
- );
1173
-
1174
- const out = await loadRevealedSecrets("test-token", "prs_alice", [
1175
- "LOCKED",
1176
- ]);
1177
-
1178
- expect(out.get("LOCKED")).toBe("v1");
1179
- expect(writeCache).not.toHaveBeenCalled();
1180
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1181
- });
1182
-
1183
- it("treats a malformed cache TTL as zero instead of defaulting to a warm cache", async () => {
1184
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1185
- jsonRes({
1186
- secrets: [{ name: "LOCKED", value: "v1", cacheTtlMs: "300000" }],
1187
- errors: [],
1188
- }),
1189
- );
1190
-
1191
- const out = await loadRevealedSecrets("test-token", "prs_alice", [
1192
- "LOCKED",
1193
- ]);
1194
-
1195
- expect(out.get("LOCKED")).toBe("v1");
1196
- expect(writeCache).not.toHaveBeenCalled();
1197
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1198
- });
1199
-
1200
- it("evicts a stale cache entry when the server returns metadata without plaintext", async () => {
1201
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1202
- jsonRes({
1203
- secrets: [{ name: "LOCKED", cacheTtlMs: 0 }],
1204
- errors: [],
1205
- }),
1206
- );
1207
-
1208
- await expect(
1209
- loadRevealedSecrets("test-token", "prs_alice", ["LOCKED"]),
1210
- ).rejects.toThrow("Secret 'LOCKED' has no value");
1211
-
1212
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1213
- });
1214
-
1215
- it("evicts every unresolved cache entry before reporting the first batch failure", async () => {
1216
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1217
- jsonRes({
1218
- secrets: [{ name: "VALUELESS", cacheTtlMs: 0 }],
1219
- errors: [
1220
- { name: "DENIED", code: "forbidden", message: "No read permission" },
1221
- ],
1222
- }),
1223
- );
1224
-
1225
- await expect(
1226
- loadRevealedSecrets("test-token", "prs_alice", [
1227
- "VALUELESS",
1228
- "DENIED",
1229
- "OMITTED",
1230
- ]),
1231
- ).rejects.toThrow("Secret 'VALUELESS' has no value");
1232
-
1233
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "VALUELESS");
1234
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "DENIED");
1235
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "OMITTED");
1236
- });
1237
-
1238
- it("a missing key fails cleanly WITHOUT hitting the GET-404 capture path", async () => {
1239
- // Batch-load reports absence as a 200 body `errors[]` entry — no 404, no
1240
- // server capture. The old code GET'd `/name/MISSING` → 404 → warning.
1241
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1242
- jsonRes({
1243
- secrets: [],
1244
- errors: [{ name: "MISSING", code: "not_found" }],
1245
- }),
1246
- );
1247
-
1248
- await expect(
1249
- loadRevealedSecrets("test-token", "prs_alice", ["MISSING"]),
1250
- ).rejects.toThrow("Failed to fetch secret 'MISSING': Secret not found");
1251
-
1252
- expect(vaultApiFetch).toHaveBeenCalledTimes(1);
1253
- expect(vaultApiFetch).toHaveBeenCalledWith(
1254
- expect.objectContaining({ path: "/secrets/prs_alice/load", method: "POST" }),
1255
- );
1256
- expect(vaultApiFetch).not.toHaveBeenCalledWith(CAPTURING_GET);
1257
- });
1258
-
1259
- it("a forbidden key surfaces as a clean per-key error", async () => {
1260
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1261
- jsonRes({
1262
- secrets: [],
1263
- errors: [
1264
- { name: "LOCKED", code: "forbidden", message: "No read permission" },
1265
- ],
1266
- }),
1267
- );
1268
-
1269
- await expect(
1270
- loadRevealedSecrets("test-token", "prs_alice", ["LOCKED"]),
1271
- ).rejects.toThrow("Failed to fetch secret 'LOCKED': No read permission");
1272
- expect(vaultApiFetch).not.toHaveBeenCalledWith(CAPTURING_GET);
1273
- });
1274
-
1275
- it("revalidates a previously cached secret and evicts it after remote ACL revocation", async () => {
1276
- vi.mocked(vaultApiFetch)
1277
- .mockResolvedValueOnce(
1278
- jsonRes({
1279
- secrets: [
1280
- { name: "CACHED", value: "cached-value", cacheTtlMs: 300000 },
1281
- ],
1282
- errors: [],
1283
- }),
1284
- )
1285
- .mockResolvedValueOnce(
1286
- jsonRes({
1287
- secrets: [],
1288
- errors: [
1289
- {
1290
- name: "CACHED",
1291
- code: "forbidden",
1292
- message: "No read permission",
1293
- },
1294
- ],
1295
- }),
1296
- );
1297
-
1298
- const first = await loadRevealedSecrets("test-token", "prs_alice", [
1299
- "CACHED",
1300
- ]);
1301
- expect(first.get("CACHED")).toBe("cached-value");
1302
- expect(writeCache).toHaveBeenCalledWith(
1303
- "prs_alice",
1304
- "CACHED",
1305
- "cached-value",
1306
- 300000,
1307
- );
1308
-
1309
- // Model the encrypted disk entry left by the first call. A pre-fix warm
1310
- // lookup would return this value without contacting the server.
1311
- vi.mocked(readCache).mockReturnValue("cached-value");
1312
-
1313
- await expect(
1314
- loadRevealedSecrets("test-token", "prs_alice", ["CACHED"]),
1315
- ).rejects.toThrow("Failed to fetch secret 'CACHED': No read permission");
1316
-
1317
- expect(vaultApiFetch).toHaveBeenCalledTimes(2);
1318
- expect(readCache).not.toHaveBeenCalled();
1319
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "CACHED");
1320
- });
1321
-
1322
- it("evicts every requested entry when a stale session is rejected", async () => {
1323
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1324
- jsonRes({ error: "Unauthorized", code: "session_expired" }, 401),
1325
- );
1326
-
1327
- await expect(
1328
- loadRevealedSecrets("stale-token", "prs_alice", ["FIRST", "SECOND"]),
1329
- ).rejects.toThrow("Unauthorized");
1330
-
1331
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "FIRST");
1332
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "SECOND");
1333
- });
1334
-
1335
- it("fails closed and evicts every entry on an offline network failure", async () => {
1336
- vi.mocked(vaultApiFetch).mockRejectedValueOnce(
1337
- new TypeError("fetch failed: ENETUNREACH"),
1338
- );
1339
-
1340
- await expect(
1341
- loadRevealedSecrets("test-token", "prs_alice", ["FIRST", "SECOND"]),
1342
- ).rejects.toThrow("ENETUNREACH");
1343
-
1344
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "FIRST");
1345
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "SECOND");
1346
- });
1347
-
1348
- it("fails closed and evicts every entry when authorization times out", async () => {
1349
- vi.mocked(vaultApiFetch).mockRejectedValueOnce(
1350
- new DOMException("The operation was aborted due to timeout", "TimeoutError"),
1351
- );
1352
-
1353
- await expect(
1354
- loadRevealedSecrets("test-token", "prs_alice", ["FIRST", "SECOND"]),
1355
- ).rejects.toThrow("timeout");
1356
-
1357
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "FIRST");
1358
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "SECOND");
1359
- });
1360
-
1361
- it("evicts earlier successful chunks when a later authorization chunk fails", async () => {
1362
- const keys = Array.from({ length: 101 }, (_, i) => `KEY_${i}`);
1363
- vi.mocked(vaultApiFetch)
1364
- .mockResolvedValueOnce(
1365
- jsonRes({
1366
- secrets: keys.slice(0, 100).map((name) => ({
1367
- name,
1368
- value: `value-for-${name}`,
1369
- cacheTtlMs: 300000,
1370
- })),
1371
- errors: [],
1372
- }),
1373
- )
1374
- .mockResolvedValueOnce(
1375
- jsonRes({ error: "No read permission", code: "forbidden" }, 403),
1376
- );
1377
-
1378
- await expect(
1379
- loadRevealedSecrets("test-token", "prs_alice", keys),
1380
- ).rejects.toThrow("No read permission");
1381
-
1382
- expect(writeCache).toHaveBeenCalledWith(
1383
- "prs_alice",
1384
- "KEY_0",
1385
- "value-for-KEY_0",
1386
- 300000,
1387
- );
1388
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "KEY_0");
1389
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "KEY_100");
1390
- });
1391
-
1392
- it("rejects mixed success/error rows and evicts without exposing the value", async () => {
1393
- const secretValue = "sentinel-secret-value";
1394
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1395
- jsonRes({
1396
- secrets: [{ name: "MIXED", value: secretValue, cacheTtlMs: 300000 }],
1397
- errors: [{ name: "MIXED", code: "forbidden", message: "Denied" }],
1398
- }),
1399
- );
1400
-
1401
- let failure: Error | undefined;
1402
- try {
1403
- await loadRevealedSecrets("test-token", "prs_alice", ["MIXED"]);
1404
- } catch (err) {
1405
- failure = err as Error;
1406
- }
1407
-
1408
- expect(failure?.message).toBe("Invalid secret load response from vault");
1409
- expect(failure?.message).not.toContain(secretValue);
1410
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "MIXED");
1411
- });
1412
-
1413
- it("rejects malformed response envelopes and evicts every requested entry", async () => {
1414
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1415
- jsonRes({ secrets: { name: "FIRST", value: "hidden" }, errors: [] }),
1416
- );
1417
-
1418
- await expect(
1419
- loadRevealedSecrets("test-token", "prs_alice", ["FIRST", "SECOND"]),
1420
- ).rejects.toThrow("Invalid secret load response from vault");
1421
-
1422
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "FIRST");
1423
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "SECOND");
1424
- });
1425
-
1426
- it("a non-2xx batch response throws the batch-load error", async () => {
1427
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1428
- jsonRes({ error: "Internal server error" }, 500),
1429
- );
1430
-
1431
- await expect(
1432
- loadRevealedSecrets("test-token", "prs_alice", ["K"]),
1433
- ).rejects.toThrow("Failed to batch-load secrets: Internal server error");
1434
- });
1435
- });
1436
-
1437
- describe("secrets script usage", () => {
1438
- it("exec hashes the script and sends usage metadata on /load", async () => {
1439
- const scriptPath = join(tempDir, "exec-script.sh");
1440
- const scriptBody = "#!/usr/bin/env bash\necho exec\n";
1441
- writeFileSync(scriptPath, scriptBody);
1442
- const expectedSha = createHash("sha256").update(scriptBody).digest("hex");
1443
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1444
- jsonRes({
1445
- secrets: [{ name: "MY_KEY", value: "v1", cacheTtlMs: 300000 }],
1446
- errors: [],
1447
- }),
1448
- );
1449
-
1450
- const program = buildProgram();
1451
- await program.parseAsync([
1452
- "node",
1453
- "hq",
1454
- "secrets",
1455
- "exec",
1456
- "--only",
1457
- "MY_KEY",
1458
- "--script",
1459
- scriptPath,
1460
- "--script-id",
1461
- "scripts/exec-script.sh",
1462
- "--",
1463
- "env",
1464
- ]);
1465
-
1466
- expect(vaultApiFetch).toHaveBeenCalledWith({
1467
- token: "test-token",
1468
- path: "/secrets/prs_alice/load",
1469
- method: "POST",
1470
- body: {
1471
- names: ["MY_KEY"],
1472
- usage: {
1473
- channel: "exec",
1474
- script: {
1475
- scriptId: "scripts/exec-script.sh",
1476
- path: scriptPath,
1477
- sha256: expectedSha,
1478
- attestationLevel: "self-asserted-hash",
1479
- },
1480
- },
1481
- },
1482
- signal: expect.any(AbortSignal),
1483
- });
1484
- expect(spawn).toHaveBeenCalledWith(
1485
- "env",
1486
- [],
1487
- expect.objectContaining({
1488
- stdio: "inherit",
1489
- env: expect.objectContaining({ MY_KEY: "v1" }),
1490
- }),
1491
- );
1492
- });
1493
-
1494
- it("env hashes the script and sends usage metadata on /load", async () => {
1495
- const scriptPath = join(tempDir, "env-script.sh");
1496
- const scriptBody = "#!/usr/bin/env bash\necho env\n";
1497
- writeFileSync(scriptPath, scriptBody);
1498
- const expectedSha = createHash("sha256").update(scriptBody).digest("hex");
1499
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1500
- jsonRes({
1501
- secrets: [{ name: "MY_KEY", value: "v1", cacheTtlMs: 300000 }],
1502
- errors: [],
1503
- }),
1504
- );
1505
-
1506
- const stdoutWriteSpy = vi
1507
- .spyOn(process.stdout, "write")
1508
- .mockImplementation(() => true);
1509
-
1510
- const program = buildProgram();
1511
- await program.parseAsync([
1512
- "node",
1513
- "hq",
1514
- "secrets",
1515
- "env",
1516
- "--only",
1517
- "MY_KEY",
1518
- "--script",
1519
- scriptPath,
1520
- ]);
1521
-
1522
- expect(vaultApiFetch).toHaveBeenCalledWith({
1523
- token: "test-token",
1524
- path: "/secrets/prs_alice/load",
1525
- method: "POST",
1526
- body: {
1527
- names: ["MY_KEY"],
1528
- usage: {
1529
- channel: "env",
1530
- script: {
1531
- scriptId: scriptPath,
1532
- path: scriptPath,
1533
- sha256: expectedSha,
1534
- attestationLevel: "self-asserted-hash",
1535
- },
1536
- },
1537
- },
1538
- signal: expect.any(AbortSignal),
1539
- });
1540
- expect(stdoutWriteSpy).toHaveBeenCalledWith("export MY_KEY='v1'\n");
1541
- });
1542
- });
1543
-
1544
- describe("secrets reveal and policy controls", () => {
1545
- it("get --reveal prints the backend denial message from a controlled secret", async () => {
1546
- const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
1547
- throw new Error("__exit__");
1548
- }) as never);
1549
- vi.mocked(vaultApiFetch)
1550
- .mockResolvedValueOnce(
1551
- jsonRes({
1552
- secret: {
1553
- name: "LOCKED",
1554
- companyUid: "prs_alice",
1555
- tier: "nuclear",
1556
- scriptLock: { mode: "enforced" },
1557
- },
1558
- }),
1559
- )
1560
- .mockResolvedValueOnce(
1561
- jsonRes(
1562
- {
1563
- code: "reveal_disabled",
1564
- message: "Reveal is disabled for this secret.",
1565
- },
1566
- 403,
1567
- ),
1568
- );
1569
-
1570
- const program = buildProgram();
1571
- await expect(
1572
- program.parseAsync([
1573
- "node",
1574
- "hq",
1575
- "secrets",
1576
- "get",
1577
- "LOCKED",
1578
- "--reveal",
1579
- ]),
1580
- ).rejects.toThrow("__exit__");
1581
-
1582
- expect(exitSpy.mock.calls[0]?.[0]).toBe(1);
1583
- expect(logSpy).toHaveBeenCalledWith(" Tier: nuclear");
1584
- expect(logSpy).toHaveBeenCalledWith(" Script Lock: enforced");
1585
- expect(errSpy.mock.calls.some((call) =>
1586
- call.some((arg) => String(arg).includes("Reveal is disabled for this secret.")),
1587
- )).toBe(true);
1588
- });
1589
-
1590
- it("policy get hits the policy endpoint and renders tier/lock", async () => {
1591
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1592
- jsonRes({
1593
- policy: {
1594
- path: "LOCKED",
1595
- tier: "nuclear",
1596
- scriptLock: { mode: "enforced" },
1597
- },
1598
- }),
1599
- );
1600
-
1601
- const program = buildProgram();
1602
- await program.parseAsync([
1603
- "node",
1604
- "hq",
1605
- "secrets",
1606
- "policy",
1607
- "get",
1608
- "LOCKED",
1609
- ]);
1610
-
1611
- expect(vaultApiFetch).toHaveBeenCalledWith({
1612
- token: "test-token",
1613
- path: "/secrets/prs_alice/policy",
1614
- query: { path: "LOCKED" },
1615
- });
1616
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Policy: LOCKED"));
1617
- expect(logSpy).toHaveBeenCalledWith(" Tier: nuclear");
1618
- expect(logSpy).toHaveBeenCalledWith(" Script Lock: enforced");
1619
- });
1620
-
1621
- it("list renders tier and script lock columns", async () => {
1622
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1623
- jsonRes({
1624
- secrets: [
1625
- {
1626
- name: "LOCKED",
1627
- permission: "read",
1628
- tier: "nuclear",
1629
- scriptLock: { mode: "enforced" },
1630
- lastModifiedDate: "2026-06-18T00:00:00.000Z",
1631
- },
1632
- ],
1633
- }),
1634
- );
1635
-
1636
- const program = buildProgram();
1637
- await program.parseAsync(["node", "hq", "secrets", "list"]);
1638
-
1639
- expect(logSpy).toHaveBeenCalledWith(
1640
- expect.stringContaining("SCRIPT LOCK"),
1641
- );
1642
- expect(logSpy).toHaveBeenCalledWith(
1643
- expect.stringContaining("nuclear"),
1644
- );
1645
- expect(logSpy).toHaveBeenCalledWith(
1646
- expect.stringContaining("enforced"),
1647
- );
1648
- });
1649
-
1650
- it("policy set hits the policy endpoint with tier and script lock", async () => {
1651
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1652
- jsonRes({
1653
- policy: {
1654
- path: "LOCKED",
1655
- tier: "nuclear",
1656
- scriptLock: { mode: "enforced" },
1657
- },
1658
- }),
1659
- );
1660
-
1661
- const program = buildProgram();
1662
- await program.parseAsync([
1663
- "node",
1664
- "hq",
1665
- "secrets",
1666
- "policy",
1667
- "set",
1668
- "LOCKED",
1669
- "--tier",
1670
- "nuclear",
1671
- "--lock-script",
1672
- "enforce",
1673
- ]);
1674
-
1675
- expect(vaultApiFetch).toHaveBeenCalledWith({
1676
- token: "test-token",
1677
- path: "/secrets/prs_alice/policy",
1678
- method: "PUT",
1679
- body: {
1680
- path: "LOCKED",
1681
- tier: "nuclear",
1682
- scriptLock: { mode: "enforced" },
1683
- },
1684
- });
1685
- expect(logSpy).toHaveBeenCalledWith(" Tier: nuclear");
1686
- expect(logSpy).toHaveBeenCalledWith(" Script Lock: enforced");
1687
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1688
- });
1689
-
1690
- it("script approve hashes the local file and hits the approval endpoint", async () => {
1691
- const scriptPath = join(tempDir, "approved.sh");
1692
- const scriptBody = "#!/usr/bin/env bash\necho approved\n";
1693
- writeFileSync(scriptPath, scriptBody);
1694
- const expectedSha = createHash("sha256").update(scriptBody).digest("hex");
1695
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1696
-
1697
- const program = buildProgram();
1698
- await program.parseAsync([
1699
- "node",
1700
- "hq",
1701
- "secrets",
1702
- "script",
1703
- "approve",
1704
- "LOCKED",
1705
- "--id",
1706
- "deploy-script",
1707
- "--script",
1708
- scriptPath,
1709
- ]);
1710
-
1711
- expect(vaultApiFetch).toHaveBeenCalledWith({
1712
- token: "test-token",
1713
- path: "/secrets/prs_alice/policy/scripts",
1714
- method: "POST",
1715
- body: {
1716
- path: "LOCKED",
1717
- scriptId: "deploy-script",
1718
- scriptPath,
1719
- sha256: expectedSha,
1720
- attestationLevel: "self-asserted-hash",
1721
- },
1722
- });
1723
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1724
- });
1725
-
1726
- it("script approve hashes the local file while approving a remote runtime path", async () => {
1727
- const scriptPath = join(tempDir, "approved.sh");
1728
- const remotePath =
1729
- "/home/ec2-user/hq-agent/companies/acme/scripts/approved.sh";
1730
- const scriptBody = "#!/usr/bin/env bash\necho approved remotely\n";
1731
- writeFileSync(scriptPath, scriptBody);
1732
- const expectedSha = createHash("sha256").update(scriptBody).digest("hex");
1733
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1734
-
1735
- const program = buildProgram();
1736
- await program.parseAsync([
1737
- "node",
1738
- "hq",
1739
- "secrets",
1740
- "script",
1741
- "approve",
1742
- "LOCKED",
1743
- "--id",
1744
- "deploy-script",
1745
- "--script",
1746
- scriptPath,
1747
- "--remote-path",
1748
- remotePath,
1749
- ]);
1750
-
1751
- expect(vaultApiFetch).toHaveBeenCalledWith({
1752
- token: "test-token",
1753
- path: "/secrets/prs_alice/policy/scripts",
1754
- method: "POST",
1755
- body: {
1756
- path: "LOCKED",
1757
- scriptId: "deploy-script",
1758
- scriptPath: remotePath,
1759
- sha256: expectedSha,
1760
- attestationLevel: "self-asserted-hash",
1761
- },
1762
- });
1763
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1764
- });
1765
-
1766
- it("script revoke hits the revoke endpoint", async () => {
1767
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(jsonRes({ ok: true }));
1768
-
1769
- const program = buildProgram();
1770
- await program.parseAsync([
1771
- "node",
1772
- "hq",
1773
- "secrets",
1774
- "script",
1775
- "revoke",
1776
- "LOCKED",
1777
- "--id",
1778
- "deploy-script",
1779
- ]);
1780
-
1781
- expect(vaultApiFetch).toHaveBeenCalledWith({
1782
- token: "test-token",
1783
- path: "/secrets/prs_alice/policy/scripts",
1784
- method: "DELETE",
1785
- body: {
1786
- path: "LOCKED",
1787
- scriptId: "deploy-script",
1788
- },
1789
- });
1790
- expect(removeCacheEntry).toHaveBeenCalledWith("prs_alice", "LOCKED");
1791
- });
1792
-
1793
- it("script list maps the server's scriptLock.approvedScripts response shape", async () => {
1794
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1795
- jsonRes({
1796
- policy: {
1797
- path: "LOCKED",
1798
- tier: "nuclear",
1799
- scriptLock: {
1800
- mode: "enforced",
1801
- requiredAttestation: "self-asserted-hash",
1802
- approvedScripts: [
1803
- {
1804
- scriptId: "deploy-script",
1805
- path: "/tmp/deploy.sh",
1806
- sha256: "abc123",
1807
- attestationLevel: "self-asserted-hash",
1808
- approvedAt: "2026-01-01T00:00:00.000Z",
1809
- approvedBy: "prs_owner",
1810
- },
1811
- {
1812
- scriptId: "revoked-script",
1813
- path: "/tmp/old.sh",
1814
- sha256: "def456",
1815
- attestationLevel: "self-asserted-hash",
1816
- approvedAt: "2025-12-01T00:00:00.000Z",
1817
- approvedBy: "prs_owner",
1818
- revokedAt: "2026-01-02T00:00:00.000Z",
1819
- },
1820
- ],
1821
- },
1822
- },
1823
- }),
1824
- );
1825
-
1826
- const program = buildProgram();
1827
- await program.parseAsync([
1828
- "node",
1829
- "hq",
1830
- "secrets",
1831
- "script",
1832
- "list",
1833
- "LOCKED",
1834
- ]);
1835
-
1836
- expect(vaultApiFetch).toHaveBeenCalledWith({
1837
- token: "test-token",
1838
- path: "/secrets/prs_alice/policy",
1839
- query: { path: "LOCKED" },
1840
- });
1841
- expect(logSpy).toHaveBeenCalledWith(" Tier: nuclear");
1842
- expect(logSpy).toHaveBeenCalledWith(" Script Lock: enforced");
1843
- expect(logSpy).toHaveBeenCalledWith(
1844
- expect.stringContaining("deploy-script"),
1845
- );
1846
- expect(logSpy).toHaveBeenCalledWith(
1847
- expect.stringContaining("/tmp/deploy.sh"),
1848
- );
1849
- expect(logSpy).not.toHaveBeenCalledWith(
1850
- expect.stringContaining("revoked-script"),
1851
- );
1852
- });
1853
-
1854
- it("script list ignores malformed modern rows without falling back to stale legacy rows", async () => {
1855
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1856
- jsonRes({
1857
- policy: {
1858
- path: "LOCKED",
1859
- tier: "sensitive",
1860
- scriptLock: {
1861
- mode: "enforced",
1862
- approvedScripts: [
1863
- null,
1864
- { scriptId: "missing-path", attestationLevel: "self-asserted-hash" },
1865
- {
1866
- scriptId: "active-modern",
1867
- path: "/tmp/active.sh",
1868
- attestationLevel: "self-asserted-hash",
1869
- },
1870
- ],
1871
- },
1872
- scripts: [
1873
- {
1874
- scriptId: "stale-legacy",
1875
- scriptPath: "/tmp/stale.sh",
1876
- sha256: "stale",
1877
- attestationLevel: "self-asserted-hash",
1878
- },
1879
- ],
1880
- },
1881
- }),
1882
- );
1883
-
1884
- const program = buildProgram();
1885
- await program.parseAsync([
1886
- "node",
1887
- "hq",
1888
- "secrets",
1889
- "script",
1890
- "list",
1891
- "LOCKED",
1892
- ]);
1893
-
1894
- expect(logSpy).toHaveBeenCalledWith(
1895
- expect.stringContaining("active-modern"),
1896
- );
1897
- expect(logSpy).not.toHaveBeenCalledWith(
1898
- expect.stringContaining("missing-path"),
1899
- );
1900
- expect(logSpy).not.toHaveBeenCalledWith(
1901
- expect.stringContaining("stale-legacy"),
1902
- );
1903
- });
1904
- });
1905
-
1906
- describe("HQ_API_KEY consume path", () => {
1907
- let exitSpy: MockInstance<typeof process.exit>;
1908
-
1909
- beforeEach(() => {
1910
- exitSpy = vi
1911
- .spyOn(process, "exit")
1912
- .mockImplementation(((code?: number) => {
1913
- throw new Error(`__EXIT__:${code ?? 0}`);
1914
- }) as never);
1915
- });
1916
-
1917
- afterEach(() => {
1918
- delete process.env.HQ_API_KEY;
1919
- });
1920
-
1921
- it("rejects secrets list when HQ_API_KEY is set (no Cognito fallback)", async () => {
1922
- process.env.HQ_API_KEY = "hqk_probe";
1923
- const program = buildProgram();
1924
- await expect(
1925
- program.parseAsync(["node", "hq", "secrets", "list"]),
1926
- ).rejects.toThrow(/__EXIT__:1/);
1927
- expect(ensureCognitoToken).not.toHaveBeenCalled();
1928
- expect(vaultApiFetch).not.toHaveBeenCalled();
1929
- const errText = errSpy.mock.calls
1930
- .map((call) => call.map(String).join(" "))
1931
- .join("\n");
1932
- expect(errText).toMatch(/not supported for API keys/);
1933
- });
1934
-
1935
- it("rejects invalid HQ_API_KEY prefix without Cognito fallback", async () => {
1936
- process.env.HQ_API_KEY = "hqd_not_a_vault_key";
1937
- const program = buildProgram();
1938
- await expect(
1939
- program.parseAsync(["node", "hq", "secrets", "get", "FOO"]),
1940
- ).rejects.toThrow(/__EXIT__:1/);
1941
- expect(ensureCognitoToken).not.toHaveBeenCalled();
1942
- const errText = errSpy.mock.calls
1943
- .map((call) => call.map(String).join(" "))
1944
- .join("\n");
1945
- expect(errText).toMatch(/must start with 'hqk_'/);
1946
- });
1947
-
1948
- it("rejects secrets get without --reveal when HQ_API_KEY is set", async () => {
1949
- process.env.HQ_API_KEY = "hqk_valid_key";
1950
- const program = buildProgram();
1951
- await expect(
1952
- program.parseAsync(["node", "hq", "secrets", "get", "FOO"]),
1953
- ).rejects.toThrow(/__EXIT__:1/);
1954
- expect(vaultApiFetch).not.toHaveBeenCalled();
1955
- const errText = errSpy.mock.calls
1956
- .map((call) => call.map(String).join(" "))
1957
- .join("\n");
1958
- expect(errText).toMatch(/without --reveal is not supported/);
1959
- });
1960
-
1961
- it("gets a secret via /v1/keys/secrets/fetch when HQ_API_KEY is set", async () => {
1962
- process.env.HQ_API_KEY = "hqk_valid_key";
1963
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
1964
- jsonRes({
1965
- secret: {
1966
- name: "FOO",
1967
- value: "secret-value",
1968
- version: 1,
1969
- tier: "standard",
1970
- },
1971
- }),
1972
- );
1973
-
1974
- const program = buildProgram();
1975
- await program.parseAsync([
1976
- "node",
1977
- "hq",
1978
- "secrets",
1979
- "get",
1980
- "FOO",
1981
- "--reveal",
1982
- ]);
1983
-
1984
- expect(ensureCognitoToken).not.toHaveBeenCalled();
1985
- expect(vaultApiFetch).toHaveBeenCalledWith(
1986
- expect.objectContaining({
1987
- token: "hqk_valid_key",
1988
- path: "/v1/keys/secrets/fetch",
1989
- method: "POST",
1990
- body: { name: "FOO" },
1991
- }),
1992
- );
1993
- const printed = logSpy.mock.calls
1994
- .map((call) => call.map(String).join(" "))
1995
- .join("\n");
1996
- expect(printed).toContain("FOO");
1997
- expect(printed).toContain("secret-value");
1998
- expect(exitSpy).not.toHaveBeenCalled();
1999
- });
2000
-
2001
- it("fails --reveal when API-key fetch omits secret.value", async () => {
2002
- process.env.HQ_API_KEY = "hqk_valid_key";
2003
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
2004
- jsonRes({
2005
- secret: {
2006
- name: "FOO",
2007
- version: 1,
2008
- tier: "standard",
2009
- },
2010
- }),
2011
- );
2012
-
2013
- const program = buildProgram();
2014
- await expect(
2015
- program.parseAsync([
2016
- "node",
2017
- "hq",
2018
- "secrets",
2019
- "get",
2020
- "FOO",
2021
- "--reveal",
2022
- ]),
2023
- ).rejects.toThrow(/__EXIT__:1/);
2024
- const errText = errSpy.mock.calls
2025
- .map((call) => call.map(String).join(" "))
2026
- .join("\n");
2027
- expect(errText).toMatch(/omitted secret\.value/);
2028
- const printed = logSpy.mock.calls
2029
- .map((call) => call.map(String).join(" "))
2030
- .join("\n");
2031
- expect(printed).not.toContain("[REDACTED]");
2032
- });
2033
-
2034
- it("loadRevealedSecrets uses fetch endpoint for hqk_ tokens", async () => {
2035
- vi.mocked(vaultApiFetch).mockResolvedValueOnce(
2036
- jsonRes({
2037
- secret: { name: "A", value: "va" },
2038
- }),
2039
- );
2040
- const out = await loadRevealedSecrets("hqk_tok", "cmp_x", ["A"]);
2041
- expect(out.get("A")).toBe("va");
2042
- expect(vaultApiFetch).toHaveBeenCalledWith(
2043
- expect.objectContaining({
2044
- path: "/v1/keys/secrets/fetch",
2045
- method: "POST",
2046
- body: { name: "A" },
2047
- }),
2048
- );
2049
- });
2050
- });