@indigoai-us/hq-cli 5.60.0 → 5.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/agents.d.ts +109 -0
- package/dist/commands/agents.js +385 -0
- package/dist/commands/db-migrate.d.ts +6 -0
- package/dist/commands/db-migrate.js +42 -0
- package/dist/commands/db-provision.d.ts +15 -0
- package/dist/commands/db-provision.js +78 -0
- package/dist/commands/db-sql.d.ts +9 -0
- package/dist/commands/db-sql.js +81 -0
- package/dist/commands/db-status.d.ts +7 -0
- package/dist/commands/db-status.js +70 -0
- package/dist/commands/db.d.ts +9 -0
- package/dist/commands/db.js +23 -0
- package/dist/commands/integrations.d.ts +78 -0
- package/dist/commands/integrations.js +309 -0
- package/dist/commands/members.js +4 -4
- package/dist/commands/outposts.d.ts +60 -0
- package/dist/commands/outposts.js +255 -0
- package/dist/commands/pack-install.d.ts +7 -1
- package/dist/commands/pack-install.js +86 -15
- package/dist/commands/packs.d.ts +2 -1
- package/dist/commands/packs.js +13 -8
- package/dist/commands/secrets.d.ts +13 -0
- package/dist/commands/secrets.js +149 -10
- package/dist/commands/skill.d.ts +153 -0
- package/dist/commands/skill.js +593 -0
- package/dist/commands/workers.d.ts +48 -0
- package/dist/commands/workers.js +229 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +14 -240
- package/dist/lib/db/control-plane.d.ts +45 -0
- package/dist/lib/db/control-plane.js +81 -0
- package/dist/lib/db/local.d.ts +49 -0
- package/dist/lib/db/local.js +106 -0
- package/dist/lib/db/migrate.d.ts +41 -0
- package/dist/lib/db/migrate.js +104 -0
- package/dist/lib/db/paths.d.ts +56 -0
- package/dist/lib/db/paths.js +103 -0
- package/dist/lib/db/remote-engine.d.ts +58 -0
- package/dist/lib/db/remote-engine.js +90 -0
- package/dist/lib/db/remote-sql.d.ts +22 -0
- package/dist/lib/db/remote-sql.js +39 -0
- package/dist/lib/db/sql.d.ts +49 -0
- package/dist/lib/db/sql.js +132 -0
- package/dist/main.d.ts +7 -0
- package/dist/main.js +272 -0
- package/dist/utils/cognito-session.js +3 -3
- package/dist/utils/sandbox-runner-client.d.ts +13 -0
- package/dist/utils/sandbox-runner-client.js +83 -6
- package/dist/utils/version-check.d.ts +6 -0
- package/dist/utils/version-check.js +78 -2
- package/package.json +9 -1
- package/pnpm-workspace.yaml +2 -0
- package/src/commands/agents.test.ts +297 -0
- package/src/commands/agents.ts +561 -0
- package/src/commands/db-migrate.ts +55 -0
- package/src/commands/db-provision.ts +102 -0
- package/src/commands/db-sql.ts +124 -0
- package/src/commands/db-status.ts +100 -0
- package/src/commands/db.ts +26 -0
- package/src/commands/integrations.test.ts +284 -0
- package/src/commands/integrations.ts +438 -0
- package/src/commands/members.ts +2 -2
- package/src/commands/outposts.test.ts +177 -0
- package/src/commands/outposts.ts +338 -0
- package/src/commands/pack-install.ts +115 -18
- package/src/commands/pack-update-cache.test.ts +149 -0
- package/src/commands/packs.ts +28 -7
- package/src/commands/secrets.parse-destination.test.ts +38 -0
- package/src/commands/secrets.test.ts +342 -0
- package/src/commands/secrets.ts +227 -13
- package/src/commands/skill.test.ts +770 -0
- package/src/commands/skill.ts +796 -0
- package/src/commands/workers.test.ts +158 -0
- package/src/commands/workers.ts +298 -0
- package/src/index.test.ts +32 -0
- package/src/index.ts +11 -274
- package/src/lib/db/control-plane.test.ts +59 -0
- package/src/lib/db/control-plane.ts +113 -0
- package/src/lib/db/local.test.ts +81 -0
- package/src/lib/db/local.ts +148 -0
- package/src/lib/db/migrate.test.ts +133 -0
- package/src/lib/db/migrate.ts +137 -0
- package/src/lib/db/paths.test.ts +112 -0
- package/src/lib/db/paths.ts +128 -0
- package/src/lib/db/remote-engine.test.ts +44 -0
- package/src/lib/db/remote-engine.ts +148 -0
- package/src/lib/db/remote-sql.test.ts +32 -0
- package/src/lib/db/remote-sql.ts +62 -0
- package/src/lib/db/sql.test.ts +106 -0
- package/src/lib/db/sql.ts +192 -0
- package/src/main.ts +314 -0
- package/src/utils/cognito-session.ts +1 -1
- package/src/utils/sandbox-runner-client.test.ts +128 -0
- package/src/utils/sandbox-runner-client.ts +100 -4
- package/src/utils/version-check.test.ts +30 -0
- package/src/utils/version-check.ts +72 -0
- package/test/commands/db-tenant-isolation.test.ts +94 -0
- package/test/commands/db.test.ts +85 -0
package/src/index.ts
CHANGED
|
@@ -1,283 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* HQ CLI - Module management, package management, and cloud sync for HQ
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
3
|
// MUST be first: guard the Node version before any dependency that needs a
|
|
8
4
|
// Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
|
|
9
5
|
import "./node-preflight.js";
|
|
10
|
-
import { Command } from "commander";
|
|
11
|
-
import { initSentry, Sentry } from "./sentry.js";
|
|
12
|
-
import { registerAddCommand } from "./commands/add.js";
|
|
13
|
-
import { registerSyncCommand } from "./commands/sync.js";
|
|
14
|
-
import { registerListCommand } from "./commands/list.js";
|
|
15
|
-
import { registerUpdateCommand } from "./commands/update.js";
|
|
16
|
-
import { registerCloudCommands } from "./commands/cloud.js";
|
|
17
|
-
import { registerSyncModeCommand } from "./commands/sync-mode.js";
|
|
18
|
-
import { registerSyncNarrowCommand } from "./commands/sync-narrow.js";
|
|
19
|
-
import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
|
|
20
|
-
import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
|
|
21
|
-
import { registerLoginCommand } from "./commands/login.js";
|
|
22
|
-
import { registerLogoutCommand } from "./commands/logout.js";
|
|
23
|
-
import { registerWhoamiCommand } from "./commands/whoami.js";
|
|
24
|
-
import { registerOnboardCommand } from "./commands/onboard.js";
|
|
25
|
-
import { registerPackageInstallCommand } from "./commands/pkg-install.js";
|
|
26
|
-
import { registerPackageRemoveCommand } from "./commands/pkg-remove.js";
|
|
27
|
-
import { registerPackageUpdateCommand } from "./commands/pkg-update.js";
|
|
28
|
-
import { registerPackageListCommand } from "./commands/pkg-list.js";
|
|
29
|
-
import { registerPacksCommand } from "./commands/packs.js";
|
|
30
|
-
import { registerPublishCommand } from "./commands/publish.js";
|
|
31
|
-
import { registerCreatorsCommand } from "./commands/creators.js";
|
|
32
|
-
import { registerTeamSyncCommand } from "./commands/team-sync.js";
|
|
33
|
-
import { registerAuthCommands } from "./commands/auth.js";
|
|
34
|
-
import { registerApiKeysCommand } from "./commands/api-keys.js";
|
|
35
|
-
import { registerSecretsCommand } from "./commands/secrets.js";
|
|
36
|
-
import { registerRunCommand } from "./commands/run.js";
|
|
37
|
-
import { registerGroupsCommand } from "./commands/groups.js";
|
|
38
|
-
import { registerGroupGrantsCommand } from "./commands/group-grants.js";
|
|
39
|
-
import { registerFilesCommand } from "./commands/files.js";
|
|
40
|
-
import { registerFilesBrowseCommands } from "./commands/files-browse.js";
|
|
41
|
-
import { registerMembersCommand } from "./commands/members.js";
|
|
42
|
-
import { registerPeopleCommand } from "./commands/people.js";
|
|
43
|
-
import { registerDmCommand } from "./commands/dm.js";
|
|
44
|
-
import { registerChannelsCommand } from "./commands/channels.js";
|
|
45
|
-
import { registerFeedbackCommand } from "./commands/feedback.js";
|
|
46
|
-
import { registerMeetingsCommand } from "./commands/meetings.js";
|
|
47
|
-
import { registerSourcesCommand } from "./commands/sources.js";
|
|
48
|
-
import { registerSignalsCommand } from "./commands/signals.js";
|
|
49
|
-
import { registerReindexCommand } from "./commands/reindex.js";
|
|
50
|
-
import { registerRescueCommand } from "./commands/rescue.js";
|
|
51
|
-
import { registerMcpCommand } from "./commands/mcp-status.js";
|
|
52
|
-
import { registerCrmCommand } from "./commands/crm.js";
|
|
53
|
-
import { registerCompanyCommand } from "./commands/company.js";
|
|
54
|
-
import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
|
|
55
|
-
import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
|
|
56
|
-
import { isEpipe } from "./utils/epipe.js";
|
|
57
|
-
import { isInterceptedProcessExit } from "./utils/intercepted-process-exit.js";
|
|
58
|
-
import {
|
|
59
|
-
maybeWarnNewVersion,
|
|
60
|
-
refreshVersionCache,
|
|
61
|
-
} from "./utils/version-check.js";
|
|
62
|
-
import {
|
|
63
|
-
enforceVersionGate,
|
|
64
|
-
shouldSkipGate,
|
|
65
|
-
} from "./utils/version-gate.js";
|
|
66
6
|
import { CLI_VERSION } from "./cli-version.js";
|
|
67
7
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
// share `isEpipe` (HQ-6B).
|
|
73
|
-
const onPipeError = (err: NodeJS.ErrnoException): void => {
|
|
74
|
-
if (isEpipe(err)) {
|
|
75
|
-
process.exit(0);
|
|
76
|
-
}
|
|
77
|
-
throw err;
|
|
78
|
-
};
|
|
79
|
-
process.stdout.on("error", onPipeError);
|
|
80
|
-
process.stderr.on("error", onPipeError);
|
|
81
|
-
|
|
82
|
-
initSentry();
|
|
83
|
-
maybeWarnNewVersion();
|
|
84
|
-
|
|
85
|
-
const program = new Command();
|
|
86
|
-
|
|
87
|
-
program
|
|
88
|
-
.name("hq")
|
|
89
|
-
.description("HQ management CLI — modules, packages, and cloud sync")
|
|
90
|
-
.version(CLI_VERSION);
|
|
91
|
-
|
|
92
|
-
// Module management subcommand group
|
|
93
|
-
const modulesCmd = program
|
|
94
|
-
.command("modules")
|
|
95
|
-
.description("Module management commands");
|
|
96
|
-
|
|
97
|
-
registerAddCommand(modulesCmd);
|
|
98
|
-
registerSyncCommand(modulesCmd);
|
|
99
|
-
registerListCommand(modulesCmd);
|
|
100
|
-
registerUpdateCommand(modulesCmd);
|
|
101
|
-
|
|
102
|
-
// Package management subcommand group
|
|
103
|
-
const packagesCmd = program
|
|
104
|
-
.command("packages")
|
|
105
|
-
.description("Package management commands");
|
|
106
|
-
|
|
107
|
-
registerPackageInstallCommand(packagesCmd);
|
|
108
|
-
registerPackageRemoveCommand(packagesCmd);
|
|
109
|
-
registerPackageUpdateCommand(packagesCmd);
|
|
110
|
-
registerPackageListCommand(packagesCmd);
|
|
111
|
-
|
|
112
|
-
// Content-pack lifecycle (core/packages/hq-pack-*). Distinct from the registry
|
|
113
|
-
// `packages` system above. Available as both `hq packages packs …` (grouped)
|
|
114
|
-
// and `hq packs …` (top-level convenience).
|
|
115
|
-
registerPacksCommand(packagesCmd);
|
|
116
|
-
registerPacksCommand(program);
|
|
117
|
-
|
|
118
|
-
// Top-level shortcuts for package commands
|
|
119
|
-
// "hq install <slug>" = "hq packages install <slug>"
|
|
120
|
-
// "hq remove <slug>" = "hq packages remove <slug>"
|
|
121
|
-
registerPackageInstallCommand(program);
|
|
122
|
-
registerPackageRemoveCommand(program);
|
|
123
|
-
|
|
124
|
-
// Marketplace publish (top-level — packer + authenticated upload, US-004)
|
|
125
|
-
// "hq publish <skill-or-worker-path>" packages and submits a pack to the
|
|
126
|
-
// marketplace via POST /v1/listings.
|
|
127
|
-
registerPublishCommand(program);
|
|
128
|
-
// `hq creators apply` — request verified-creator access (required to publish).
|
|
129
|
-
registerCreatorsCommand(program);
|
|
130
|
-
|
|
131
|
-
// Cloud sync subcommand group
|
|
132
|
-
const syncCmd = program
|
|
133
|
-
.command("sync")
|
|
134
|
-
.description("Cloud sync commands — sync HQ to S3 for mobile access");
|
|
135
|
-
|
|
136
|
-
registerCloudCommands(syncCmd);
|
|
137
|
-
registerSyncModeCommand(syncCmd);
|
|
138
|
-
registerSyncNarrowCommand(syncCmd);
|
|
139
|
-
|
|
140
|
-
// Cloud provisioning subcommand group (entity + bucket + initial sync)
|
|
141
|
-
// Distinct from `hq sync` which assumes provisioning has already happened.
|
|
142
|
-
const cloudCmd = program
|
|
143
|
-
.command("cloud")
|
|
144
|
-
.description(
|
|
145
|
-
"Cloud commands — provision entities and manage cloud-backed companies",
|
|
146
|
-
);
|
|
147
|
-
|
|
148
|
-
registerCloudProvisionCommands(cloudCmd);
|
|
149
|
-
registerCloudDemoteCommands(cloudCmd);
|
|
150
|
-
|
|
151
|
-
// Team commands (top-level)
|
|
152
|
-
registerTeamSyncCommand(program);
|
|
153
|
-
|
|
154
|
-
// Auth commands (top-level — Cognito OAuth)
|
|
155
|
-
registerLoginCommand(program);
|
|
156
|
-
registerLogoutCommand(program);
|
|
157
|
-
registerWhoamiCommand(program);
|
|
158
|
-
registerAuthCommands(program);
|
|
159
|
-
|
|
160
|
-
// Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
|
|
161
|
-
registerSecretsCommand(program);
|
|
162
|
-
|
|
163
|
-
// API key management (subcommand group — hq api-keys create|list|revoke)
|
|
164
|
-
registerApiKeysCommand(program);
|
|
165
|
-
|
|
166
|
-
// Schema-driven dev runner — hq run [options] -- <cmd>
|
|
167
|
-
registerRunCommand(program);
|
|
168
|
-
|
|
169
|
-
// Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
|
|
170
|
-
registerGroupsCommand(program);
|
|
171
|
-
|
|
172
|
-
// Cross-company group grants (subcommand group —
|
|
173
|
-
// hq group-grants grant|revoke|outbound|inbound)
|
|
174
|
-
registerGroupGrantsCommand(program);
|
|
175
|
-
|
|
176
|
-
// Files ACL management (subcommand group — hq files share|unshare|acl)
|
|
177
|
-
// `registerFilesCommand` returns the `files` group so we can attach the
|
|
178
|
-
// browse-vs-sync subcommands (`hq files browse`/`cat`) onto the same group.
|
|
179
|
-
const filesCmd = registerFilesCommand(program);
|
|
180
|
-
registerFilesBrowseCommands(filesCmd);
|
|
181
|
-
|
|
182
|
-
// Membership management (subcommand group — hq members invite|list|revoke)
|
|
183
|
-
registerMembersCommand(program);
|
|
184
|
-
// People directory (subcommand group — hq people list|search|resolve), reading
|
|
185
|
-
// the local companies/<co>/people store scoped to one company.
|
|
186
|
-
registerPeopleCommand(program);
|
|
187
|
-
registerDmCommand(program);
|
|
188
|
-
registerChannelsCommand(program);
|
|
189
|
-
|
|
190
|
-
// Onboarding (top-level — Cognito + vault-service provisioning)
|
|
191
|
-
registerOnboardCommand(program);
|
|
192
|
-
|
|
193
|
-
// Feedback (subcommand group — hq feedback bug|feature)
|
|
194
|
-
registerFeedbackCommand(program);
|
|
195
|
-
|
|
196
|
-
// Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
|
|
197
|
-
registerMeetingsCommand(program);
|
|
198
|
-
|
|
199
|
-
// Sources read surface (subcommand group — hq sources list|get|channels|entities)
|
|
200
|
-
registerSourcesCommand(program);
|
|
201
|
-
|
|
202
|
-
// Signals read surface (subcommand group — hq signals list|get|types|entities)
|
|
203
|
-
registerSignalsCommand(program);
|
|
204
|
-
|
|
205
|
-
// Skill/personal-overlay mirroring + workers-registry regen. Invoked by the
|
|
206
|
-
// hq-core reindex hook shim (Stop / PostToolUse) and by sync()/rescue() after
|
|
207
|
-
// they change on-disk sources. Keeps a `master-sync` alias for one release.
|
|
208
|
-
// Implementation lives in @indigoai-us/hq-cloud.
|
|
209
|
-
registerReindexCommand(program);
|
|
210
|
-
|
|
211
|
-
// Drift-preserving HQ-core re-sync (top-level — `hq rescue`). CLI sibling of
|
|
212
|
-
// the HQ Sync app's "Update / Restore" pill; drives the same replace-rescue.sh
|
|
213
|
-
// shipped from @indigoai-us/hq-cloud.
|
|
214
|
-
registerRescueCommand(program);
|
|
215
|
-
|
|
216
|
-
// MCP pack observability (subcommand group — `hq mcp status`). Read-only
|
|
217
|
-
// provenance-based status across BOTH Claude + Codex runtimes (reads `_hqPack`
|
|
218
|
-
// off the configs, NOT linkStatus), with secret-redacted output + `--json`.
|
|
219
|
-
registerMcpCommand(program);
|
|
220
|
-
|
|
221
|
-
// Native CRM entity upsert (subcommand group — `hq crm entity upsert`). Wraps
|
|
222
|
-
// POST /crm/entities (the ontology write gate) so an authenticated company
|
|
223
|
-
// member can create/update canonical CRM entities in the company vault.
|
|
224
|
-
registerCrmCommand(program);
|
|
8
|
+
function isVersionRequest(argv: readonly string[]): boolean {
|
|
9
|
+
const args = argv.slice(2);
|
|
10
|
+
return args.length === 1 && (args[0] === "--version" || args[0] === "-V" || args[0] === "-v");
|
|
11
|
+
}
|
|
225
12
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
13
|
+
if (isVersionRequest(process.argv)) {
|
|
14
|
+
process.stdout.write(`${CLI_VERSION}\n`);
|
|
15
|
+
} else {
|
|
16
|
+
const { runCli } = await import("./main.js");
|
|
17
|
+
await runCli();
|
|
18
|
+
}
|
|
229
19
|
|
|
230
|
-
|
|
231
|
-
try {
|
|
232
|
-
Sentry.addBreadcrumb({
|
|
233
|
-
category: "command",
|
|
234
|
-
message: sanitizeArgv(process.argv.slice(2)).join(" "),
|
|
235
|
-
level: "info",
|
|
236
|
-
});
|
|
237
|
-
// Hard version gate: ask hq-pro whether this CLI is below the floor and
|
|
238
|
-
// auto-update if so (exits the process on update). Skipped for inspection
|
|
239
|
-
// flags (`--version`, `--help`) so users debugging a broken install can
|
|
240
|
-
// still introspect what they have. Silent on any failure — never blocks
|
|
241
|
-
// the CLI on a flaky network or hq-pro hiccup. See `utils/version-gate.ts`.
|
|
242
|
-
if (!shouldSkipGate(process.argv)) {
|
|
243
|
-
await enforceVersionGate();
|
|
244
|
-
}
|
|
245
|
-
await program.parseAsync();
|
|
246
|
-
} catch (err) {
|
|
247
|
-
// A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
|
|
248
|
-
// (`hq … | head`, `source <(hq …)`, a parent that exited). That is normal
|
|
249
|
-
// Unix behavior with no user-facing degradation — exit cleanly (0) and
|
|
250
|
-
// skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
|
|
251
|
-
// `write EPIPE` thrown out of console.log lands here rather than on the
|
|
252
|
-
// stream 'error' listener above.
|
|
253
|
-
if (isEpipe(err)) {
|
|
254
|
-
process.exitCode = 0;
|
|
255
|
-
} else if (isInterceptedProcessExit(err)) {
|
|
256
|
-
// A security/audit FUZZ harness replaced `process.exit` with a throw so it
|
|
257
|
-
// can keep exercising the binary. Commander calling `process.exit` for
|
|
258
|
-
// normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
|
|
259
|
-
// here as that synthetic marker. It is a test-harness artifact, NOT an
|
|
260
|
-
// hq-cli defect — a real user's `process.exit` just exits, so nothing is
|
|
261
|
-
// thrown or captured. Skip Sentry capture (no signal, no user-facing
|
|
262
|
-
// degradation) and preserve the intended non-zero exit (HQ-CLI-3).
|
|
263
|
-
process.exitCode = 1;
|
|
264
|
-
} else {
|
|
265
|
-
// A full disk / exhausted quota / read-only filesystem is the user's
|
|
266
|
-
// machine, not an HQ code defect. Surface a clear, actionable message and
|
|
267
|
-
// skip Sentry capture so one full disk doesn't flood the tracker with
|
|
268
|
-
// identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
|
|
269
|
-
// to Sentry and still exit 1.
|
|
270
|
-
const envMsg = environmentalFsErrorMessage(err);
|
|
271
|
-
if (envMsg) {
|
|
272
|
-
process.stderr.write(`hq: ${envMsg}\n`);
|
|
273
|
-
} else {
|
|
274
|
-
Sentry.captureException(err);
|
|
275
|
-
}
|
|
276
|
-
process.exitCode = 1;
|
|
277
|
-
}
|
|
278
|
-
} finally {
|
|
279
|
-
// Release health: finalize the per-run session before the flush.
|
|
280
|
-
Sentry.endSession();
|
|
281
|
-
await Promise.allSettled([refreshVersionCache(), Sentry.flush(2000)]);
|
|
282
|
-
}
|
|
283
|
-
})();
|
|
20
|
+
export const __test__ = { isVersionRequest };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control-plane client tests (US-009).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it, vi } from "vitest";
|
|
6
|
+
|
|
7
|
+
import { ControlPlaneDbClient } from "./control-plane.js";
|
|
8
|
+
|
|
9
|
+
describe("ControlPlaneDbClient", () => {
|
|
10
|
+
it("provision success returns remote status without connection string", async () => {
|
|
11
|
+
const fetchImpl = vi.fn(async () => {
|
|
12
|
+
return new Response(
|
|
13
|
+
JSON.stringify({
|
|
14
|
+
ok: true,
|
|
15
|
+
companyUid: "cmp_x",
|
|
16
|
+
companySlug: "x",
|
|
17
|
+
engineId: "aurora-dsql",
|
|
18
|
+
resourceArn: "arn:aws:dsql:us-east-1:1:cluster/x",
|
|
19
|
+
region: "us-east-1",
|
|
20
|
+
status: "ready",
|
|
21
|
+
secretRef: "ssm:/hq/cmp_x/secrets/DB/REMOTE/X",
|
|
22
|
+
idempotent: false,
|
|
23
|
+
}),
|
|
24
|
+
{ status: 200 },
|
|
25
|
+
);
|
|
26
|
+
}) as unknown as typeof fetch;
|
|
27
|
+
|
|
28
|
+
const client = new ControlPlaneDbClient({
|
|
29
|
+
baseUrl: "https://api.example",
|
|
30
|
+
getAccessToken: async () => "tok",
|
|
31
|
+
fetchImpl,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const result = await client.provision({
|
|
35
|
+
companyUid: "cmp_x",
|
|
36
|
+
companySlug: "x",
|
|
37
|
+
});
|
|
38
|
+
expect(result.status).toBe("ready");
|
|
39
|
+
expect(JSON.stringify(result)).not.toMatch(/postgres:\/\//i);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("403 surfaces actionable error without secret", async () => {
|
|
43
|
+
const fetchImpl = vi.fn(async () => {
|
|
44
|
+
return new Response(JSON.stringify({ error: "Forbidden" }), {
|
|
45
|
+
status: 403,
|
|
46
|
+
});
|
|
47
|
+
}) as unknown as typeof fetch;
|
|
48
|
+
|
|
49
|
+
const client = new ControlPlaneDbClient({
|
|
50
|
+
baseUrl: "https://api.example",
|
|
51
|
+
getAccessToken: async () => "tok",
|
|
52
|
+
fetchImpl,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
await expect(
|
|
56
|
+
client.provision({ companyUid: "cmp_x", companySlug: "x" }),
|
|
57
|
+
).rejects.toThrow(/Forbidden|403/);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control-plane client for remote vault DB (US-009).
|
|
3
|
+
* Injectable fetch for tests — never logs response bodies that might hold secrets.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface RemoteProvisionResponse {
|
|
7
|
+
ok: boolean;
|
|
8
|
+
companyUid: string;
|
|
9
|
+
companySlug: string;
|
|
10
|
+
engineId: string;
|
|
11
|
+
resourceArn: string;
|
|
12
|
+
region: string;
|
|
13
|
+
status: string;
|
|
14
|
+
secretRef: string;
|
|
15
|
+
idempotent: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RemoteStatusResponse {
|
|
19
|
+
companyUid: string;
|
|
20
|
+
companySlug?: string;
|
|
21
|
+
remote: {
|
|
22
|
+
engineId: string;
|
|
23
|
+
resourceArn: string;
|
|
24
|
+
region: string;
|
|
25
|
+
status: string;
|
|
26
|
+
secretRef: string;
|
|
27
|
+
} | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ControlPlaneClientOptions {
|
|
31
|
+
baseUrl: string;
|
|
32
|
+
/** Bearer access token */
|
|
33
|
+
getAccessToken: () => Promise<string>;
|
|
34
|
+
fetchImpl?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function assertNoPostgresUrl(label: string, text: string): void {
|
|
38
|
+
if (/postgres:\/\//i.test(text) || /postgresql:\/\//i.test(text)) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`${label}: control plane returned a connection string (refusing to surface)`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ControlPlaneDbClient {
|
|
46
|
+
private readonly baseUrl: string;
|
|
47
|
+
private readonly getAccessToken: () => Promise<string>;
|
|
48
|
+
private readonly fetchImpl: typeof fetch;
|
|
49
|
+
|
|
50
|
+
constructor(opts: ControlPlaneClientOptions) {
|
|
51
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
52
|
+
this.getAccessToken = opts.getAccessToken;
|
|
53
|
+
this.fetchImpl = opts.fetchImpl ?? fetch;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async provision(input: {
|
|
57
|
+
companyUid: string;
|
|
58
|
+
companySlug: string;
|
|
59
|
+
region?: string;
|
|
60
|
+
}): Promise<RemoteProvisionResponse> {
|
|
61
|
+
const token = await this.getAccessToken();
|
|
62
|
+
const res = await this.fetchImpl(`${this.baseUrl}/v1/db/provision`, {
|
|
63
|
+
method: "POST",
|
|
64
|
+
headers: {
|
|
65
|
+
Authorization: `Bearer ${token}`,
|
|
66
|
+
"Content-Type": "application/json",
|
|
67
|
+
},
|
|
68
|
+
body: JSON.stringify(input),
|
|
69
|
+
});
|
|
70
|
+
const text = await res.text();
|
|
71
|
+
assertNoPostgresUrl("provision", text);
|
|
72
|
+
if (!res.ok) {
|
|
73
|
+
let msg = `provision failed (${res.status})`;
|
|
74
|
+
let code: string | undefined;
|
|
75
|
+
try {
|
|
76
|
+
const j = JSON.parse(text) as { error?: string; code?: string };
|
|
77
|
+
if (j.error) msg = j.error;
|
|
78
|
+
if (j.code) code = j.code;
|
|
79
|
+
} catch {
|
|
80
|
+
/* keep */
|
|
81
|
+
}
|
|
82
|
+
const err = new Error(msg) as Error & { status?: number; code?: string };
|
|
83
|
+
err.status = res.status;
|
|
84
|
+
if (code) err.code = code;
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
return JSON.parse(text) as RemoteProvisionResponse;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async status(companyUid: string): Promise<RemoteStatusResponse> {
|
|
91
|
+
const token = await this.getAccessToken();
|
|
92
|
+
const url = `${this.baseUrl}/v1/db/status?companyUid=${encodeURIComponent(companyUid)}`;
|
|
93
|
+
const res = await this.fetchImpl(url, {
|
|
94
|
+
method: "GET",
|
|
95
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
96
|
+
});
|
|
97
|
+
const text = await res.text();
|
|
98
|
+
assertNoPostgresUrl("status", text);
|
|
99
|
+
if (!res.ok) {
|
|
100
|
+
let msg = `status failed (${res.status})`;
|
|
101
|
+
try {
|
|
102
|
+
const j = JSON.parse(text) as { error?: string };
|
|
103
|
+
if (j.error) msg = j.error;
|
|
104
|
+
} catch {
|
|
105
|
+
/* keep */
|
|
106
|
+
}
|
|
107
|
+
const err = new Error(msg) as Error & { status?: number };
|
|
108
|
+
err.status = res.status;
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
return JSON.parse(text) as RemoteStatusResponse;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local vault SQLite open/status tests (vault-databases US-003).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
ensureAndStatusLocalDb,
|
|
13
|
+
openLocalDb,
|
|
14
|
+
readMigrationHead,
|
|
15
|
+
} from "./local.js";
|
|
16
|
+
import { resolveLocalDbPath } from "./paths.js";
|
|
17
|
+
|
|
18
|
+
const tempHomes: string[] = [];
|
|
19
|
+
|
|
20
|
+
function makeTempHome(): string {
|
|
21
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-db-local-"));
|
|
22
|
+
tempHomes.push(dir);
|
|
23
|
+
return dir;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
while (tempHomes.length > 0) {
|
|
28
|
+
const dir = tempHomes.pop();
|
|
29
|
+
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("openLocalDb / ensureAndStatusLocalDb", () => {
|
|
34
|
+
it("creates SQLite at canonical path with WAL on first open", () => {
|
|
35
|
+
const home = makeTempHome();
|
|
36
|
+
const status = ensureAndStatusLocalDb("fixture-co", { home });
|
|
37
|
+
const dbPath = resolveLocalDbPath("fixture-co", { home });
|
|
38
|
+
|
|
39
|
+
expect(status.healthy).toBe(true);
|
|
40
|
+
expect(status.tier).toBe("local");
|
|
41
|
+
expect(status.company).toBe("fixture-co");
|
|
42
|
+
expect(status.path).toBe(dbPath);
|
|
43
|
+
expect(status.journalMode?.toLowerCase()).toBe("wal");
|
|
44
|
+
expect(fs.existsSync(dbPath)).toBe(true);
|
|
45
|
+
expect(status.schemaVersion).toBeNull();
|
|
46
|
+
// Never a remote URL
|
|
47
|
+
expect(JSON.stringify(status)).not.toMatch(/postgres:\/\//i);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("second open is idempotent (file survives, no wipe)", () => {
|
|
51
|
+
const home = makeTempHome();
|
|
52
|
+
const dbPath = resolveLocalDbPath("idem", { home });
|
|
53
|
+
|
|
54
|
+
const db1 = openLocalDb("idem", { home });
|
|
55
|
+
db1.exec("CREATE TABLE smoke (id INTEGER PRIMARY KEY, v TEXT)");
|
|
56
|
+
db1.prepare("INSERT INTO smoke (v) VALUES (?)").run("keep-me");
|
|
57
|
+
db1.close();
|
|
58
|
+
|
|
59
|
+
const stat1 = fs.statSync(dbPath);
|
|
60
|
+
const status2 = ensureAndStatusLocalDb("idem", { home });
|
|
61
|
+
expect(status2.healthy).toBe(true);
|
|
62
|
+
|
|
63
|
+
const db2 = openLocalDb("idem", { home });
|
|
64
|
+
const row = db2.prepare("SELECT v FROM smoke WHERE id = 1").get() as {
|
|
65
|
+
v: string;
|
|
66
|
+
};
|
|
67
|
+
expect(row.v).toBe("keep-me");
|
|
68
|
+
db2.close();
|
|
69
|
+
|
|
70
|
+
const stat2 = fs.statSync(dbPath);
|
|
71
|
+
// Size should not collapse (recreate would lose data / shrink oddly)
|
|
72
|
+
expect(stat2.size).toBeGreaterThanOrEqual(stat1.size);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("readMigrationHead returns null without ledger table", () => {
|
|
76
|
+
const home = makeTempHome();
|
|
77
|
+
const db = openLocalDb("noleger", { home });
|
|
78
|
+
expect(readMigrationHead(db)).toBeNull();
|
|
79
|
+
db.close();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local vault SQLite open/create (C1).
|
|
3
|
+
*
|
|
4
|
+
* File lives at ~/.hq/db/{company}/vault.db with WAL journal mode.
|
|
5
|
+
* Never returns or logs remote connection strings.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
|
|
10
|
+
import Database from "better-sqlite3";
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ensureLocalDbDir,
|
|
14
|
+
resolveLocalDbPath,
|
|
15
|
+
type LocalDbPathEnv,
|
|
16
|
+
} from "./paths.js";
|
|
17
|
+
|
|
18
|
+
export type LocalDb = Database.Database;
|
|
19
|
+
|
|
20
|
+
export interface OpenLocalDbOptions extends LocalDbPathEnv {
|
|
21
|
+
/** When true, do not create the file if missing (throws). Default false. */
|
|
22
|
+
readonly?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface LocalDbStatus {
|
|
26
|
+
company: string;
|
|
27
|
+
tier: "local";
|
|
28
|
+
path: string;
|
|
29
|
+
exists: boolean;
|
|
30
|
+
healthy: boolean;
|
|
31
|
+
journalMode: string | null;
|
|
32
|
+
/** Migration ledger head when present; null if ledger not initialized. */
|
|
33
|
+
schemaVersion: string | null;
|
|
34
|
+
/** Fingerprint of path for logs that prefer not to echo full home paths. */
|
|
35
|
+
pathFingerprint: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const MIGRATIONS_TABLE = "hq_schema_migrations";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Short non-reversible fingerprint of a path (for status display).
|
|
42
|
+
* Not a secret — just avoids dumping full home paths when preferred.
|
|
43
|
+
*/
|
|
44
|
+
export function fingerprintPath(filePath: string): string {
|
|
45
|
+
let h = 2166136261;
|
|
46
|
+
for (let i = 0; i < filePath.length; i++) {
|
|
47
|
+
h ^= filePath.charCodeAt(i);
|
|
48
|
+
h = Math.imul(h, 16777619);
|
|
49
|
+
}
|
|
50
|
+
return `fp_${(h >>> 0).toString(16).padStart(8, "0")}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Open (and create if missing) the company local vault DB with WAL mode.
|
|
55
|
+
* Idempotent: reopening an existing file does not recreate or wipe it.
|
|
56
|
+
*/
|
|
57
|
+
export function openLocalDb(
|
|
58
|
+
companySlug: string,
|
|
59
|
+
opts?: OpenLocalDbOptions,
|
|
60
|
+
): LocalDb {
|
|
61
|
+
const dbPath = resolveLocalDbPath(companySlug, opts);
|
|
62
|
+
const exists = fs.existsSync(dbPath);
|
|
63
|
+
|
|
64
|
+
if (!exists) {
|
|
65
|
+
if (opts?.readonly) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`local vault DB not found for company ${JSON.stringify(companySlug)} at ${dbPath}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
ensureLocalDbDir(companySlug, opts);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const db = new Database(dbPath);
|
|
74
|
+
// WAL for concurrent readers; safe for agent/CLI workloads.
|
|
75
|
+
db.pragma("journal_mode = WAL");
|
|
76
|
+
db.pragma("foreign_keys = ON");
|
|
77
|
+
return db;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Read migration head from platform ledger if the table exists.
|
|
82
|
+
*/
|
|
83
|
+
export function readMigrationHead(db: LocalDb): string | null {
|
|
84
|
+
try {
|
|
85
|
+
const row = db
|
|
86
|
+
.prepare(
|
|
87
|
+
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
|
|
88
|
+
)
|
|
89
|
+
.get(MIGRATIONS_TABLE) as { name?: string } | undefined;
|
|
90
|
+
if (!row?.name) return null;
|
|
91
|
+
|
|
92
|
+
const head = db
|
|
93
|
+
.prepare(
|
|
94
|
+
`SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version DESC LIMIT 1`,
|
|
95
|
+
)
|
|
96
|
+
.get() as { version?: string } | undefined;
|
|
97
|
+
return head?.version ?? null;
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Ensure local DB exists (create if needed), report status, close handle.
|
|
105
|
+
* Safe for CLI status: never includes connection strings.
|
|
106
|
+
*/
|
|
107
|
+
export function ensureAndStatusLocalDb(
|
|
108
|
+
companySlug: string,
|
|
109
|
+
opts?: LocalDbPathEnv,
|
|
110
|
+
): LocalDbStatus {
|
|
111
|
+
const dbPath = resolveLocalDbPath(companySlug, opts);
|
|
112
|
+
const db = openLocalDb(companySlug, opts);
|
|
113
|
+
try {
|
|
114
|
+
const journalMode = String(db.pragma("journal_mode", { simple: true }));
|
|
115
|
+
const schemaVersion = readMigrationHead(db);
|
|
116
|
+
// Touch a trivial query to prove the handle is healthy.
|
|
117
|
+
db.prepare("SELECT 1 AS ok").get();
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
company: companySlug.trim().toLowerCase(),
|
|
121
|
+
tier: "local",
|
|
122
|
+
path: dbPath,
|
|
123
|
+
exists: true,
|
|
124
|
+
healthy: true,
|
|
125
|
+
journalMode,
|
|
126
|
+
schemaVersion,
|
|
127
|
+
pathFingerprint: fingerprintPath(dbPath),
|
|
128
|
+
};
|
|
129
|
+
} finally {
|
|
130
|
+
db.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Format status for CLI stdout (no secrets).
|
|
136
|
+
*/
|
|
137
|
+
export function formatLocalDbStatus(status: LocalDbStatus): string {
|
|
138
|
+
const lines = [
|
|
139
|
+
`company: ${status.company}`,
|
|
140
|
+
`tier: ${status.tier}`,
|
|
141
|
+
`healthy: ${status.healthy ? "yes" : "no"}`,
|
|
142
|
+
`path: ${status.path}`,
|
|
143
|
+
`pathFingerprint: ${status.pathFingerprint}`,
|
|
144
|
+
`journalMode: ${status.journalMode ?? "unknown"}`,
|
|
145
|
+
`schemaVersion: ${status.schemaVersion ?? "(none)"}`,
|
|
146
|
+
];
|
|
147
|
+
return lines.join("\n");
|
|
148
|
+
}
|