@indigoai-us/hq-cli 5.77.12 → 5.77.14

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 (34) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/commands/outposts-heartbeat.d.ts +96 -0
  3. package/dist/commands/outposts-heartbeat.js +188 -0
  4. package/dist/commands/outposts.js +3 -0
  5. package/dist/commands/pack-install.js +9 -0
  6. package/dist/commands/pkg-install.js +6 -0
  7. package/dist/commands/run.js +4 -0
  8. package/dist/commands/secrets.js +5 -0
  9. package/dist/outpost/session-heartbeat-publisher.d.ts +76 -0
  10. package/dist/outpost/session-heartbeat-publisher.js +117 -0
  11. package/dist/outpost/session-heartbeat.d.ts +210 -0
  12. package/dist/outpost/session-heartbeat.js +657 -0
  13. package/dist/utils/vault-api.d.ts +8 -1
  14. package/dist/utils/vault-api.js +3 -2
  15. package/package.json +3 -1
  16. package/src/commands/outposts-heartbeat.test.ts +299 -0
  17. package/src/commands/outposts-heartbeat.ts +310 -0
  18. package/src/commands/outposts.ts +4 -0
  19. package/src/commands/pack-install.ts +9 -0
  20. package/src/commands/packs-update-api-key.test.ts +105 -0
  21. package/src/commands/pkg-install.dispatch.test.ts +33 -1
  22. package/src/commands/pkg-install.ts +6 -0
  23. package/src/commands/run.ts +6 -0
  24. package/src/commands/secrets.test.ts +13 -0
  25. package/src/commands/secrets.ts +9 -0
  26. package/src/outpost/session-heartbeat-bounds.test.ts +195 -0
  27. package/src/outpost/session-heartbeat-guard.test.ts +105 -0
  28. package/src/outpost/session-heartbeat-publisher.test.ts +178 -0
  29. package/src/outpost/session-heartbeat-publisher.ts +186 -0
  30. package/src/outpost/session-heartbeat-retain-guard.test.ts +126 -0
  31. package/src/outpost/session-heartbeat.test.ts +459 -0
  32. package/src/outpost/session-heartbeat.ts +877 -0
  33. package/src/packaging.test.ts +45 -0
  34. package/src/utils/vault-api.ts +13 -2
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Tests for the on-box realtime publisher (mission-control US-009):
3
+ * - defaultRealtimeCredentialsFetcher POSTs the box's JWT to
4
+ * /v1/realtime/credentials and parses the response
5
+ * - createIotPublishPort vends scoped creds, builds an IoT client, publishes
6
+ * to the caller's topic, caches the client until near-expiry, and re-guards
7
+ * the no-secrets contract at the transport boundary
8
+ */
9
+
10
+ import { beforeEach, describe, expect, it, vi } from "vitest";
11
+ import { mockClient } from "aws-sdk-client-mock";
12
+ import {
13
+ IoTDataPlaneClient,
14
+ PublishCommand,
15
+ } from "@aws-sdk/client-iot-data-plane";
16
+ import {
17
+ createIotPublishPort,
18
+ defaultRealtimeCredentialsFetcher,
19
+ type RealtimeCredentialsResponse,
20
+ } from "./session-heartbeat-publisher";
21
+ import type { SessionsHeartbeatPayload } from "./session-heartbeat";
22
+
23
+ const PERSON = "prs_alice";
24
+ const TOPIC = `hq/${PERSON}/sessions`;
25
+ const NOW = new Date("2026-06-15T18:55:00.000Z");
26
+
27
+ function credsResponse(
28
+ expiresInMs: number,
29
+ ): RealtimeCredentialsResponse {
30
+ return {
31
+ credentials: {
32
+ accessKeyId: "ASIAEXAMPLE",
33
+ secretAccessKey: "secret",
34
+ sessionToken: "token",
35
+ expiration: new Date(NOW.getTime() + expiresInMs).toISOString(),
36
+ },
37
+ iotEndpoint: "abc123-ats.iot.us-east-1.amazonaws.com",
38
+ region: "us-east-1",
39
+ topic: TOPIC,
40
+ expiresAt: new Date(NOW.getTime() + expiresInMs).toISOString(),
41
+ };
42
+ }
43
+
44
+ function cleanPayload(): SessionsHeartbeatPayload {
45
+ return {
46
+ type: "sessions",
47
+ origin: "outpost",
48
+ emittedAt: NOW.toISOString(),
49
+ sessions: [
50
+ {
51
+ id: "x",
52
+ tool: "claude",
53
+ origin: "outpost",
54
+ cwd: "/home/ec2-user/hq",
55
+ project: "hq",
56
+ company: null,
57
+ model: "claude-opus-4",
58
+ status: "running",
59
+ startedAt: null,
60
+ lastActivityAt: NOW.toISOString(),
61
+ source: "/home/ec2-user/.claude/projects/p/x.jsonl",
62
+ },
63
+ ],
64
+ };
65
+ }
66
+
67
+ describe("defaultRealtimeCredentialsFetcher", () => {
68
+ it("POSTs the JWT to /v1/realtime/credentials and returns the parsed body", async () => {
69
+ const body = credsResponse(3_600_000);
70
+ const fetchImpl = vi.fn().mockResolvedValue({
71
+ ok: true,
72
+ status: 200,
73
+ statusText: "OK",
74
+ json: async () => body,
75
+ } as Response);
76
+ const fetcher = defaultRealtimeCredentialsFetcher({
77
+ apiBaseUrl: "https://hqapi.hq.computer",
78
+ getJwt: async () => "JWT123",
79
+ fetchImpl: fetchImpl as unknown as typeof fetch,
80
+ });
81
+ const out = await fetcher();
82
+ expect(out).toEqual(body);
83
+ const [url, init] = fetchImpl.mock.calls[0];
84
+ expect(url).toBe("https://hqapi.hq.computer/v1/realtime/credentials");
85
+ expect(init.method).toBe("POST");
86
+ expect(init.headers.authorization).toBe("Bearer JWT123");
87
+ });
88
+
89
+ it("throws on a non-ok response", async () => {
90
+ const fetchImpl = vi.fn().mockResolvedValue({
91
+ ok: false,
92
+ status: 403,
93
+ statusText: "Forbidden",
94
+ json: async () => ({}),
95
+ } as Response);
96
+ const fetcher = defaultRealtimeCredentialsFetcher({
97
+ apiBaseUrl: "https://hqapi.hq.computer",
98
+ getJwt: async () => "JWT",
99
+ fetchImpl: fetchImpl as unknown as typeof fetch,
100
+ });
101
+ await expect(fetcher()).rejects.toThrow(/403/);
102
+ });
103
+ });
104
+
105
+ describe("createIotPublishPort", () => {
106
+ const iotMock = mockClient(IoTDataPlaneClient);
107
+ beforeEach(() => iotMock.reset());
108
+
109
+ it("publishes the payload to the caller's topic via IoT", async () => {
110
+ iotMock.on(PublishCommand).resolves({});
111
+ const fetchCredentials = vi.fn().mockResolvedValue(credsResponse(3_600_000));
112
+ const publish = createIotPublishPort({
113
+ fetchCredentials,
114
+ makeClient: () => iotMock as unknown as IoTDataPlaneClient,
115
+ now: () => NOW,
116
+ });
117
+
118
+ const payload = cleanPayload();
119
+ await publish(TOPIC, payload);
120
+
121
+ const call = iotMock.commandCalls(PublishCommand)[0];
122
+ expect(call.args[0].input.topic).toBe(TOPIC);
123
+ const sent = JSON.parse(
124
+ Buffer.from(call.args[0].input.payload as Uint8Array).toString("utf8"),
125
+ );
126
+ expect(sent.type).toBe("sessions");
127
+ expect(sent.sessions[0].id).toBe("x");
128
+ });
129
+
130
+ it("caches the vended creds/client until near expiry, then re-vends", async () => {
131
+ iotMock.on(PublishCommand).resolves({});
132
+ const fetchCredentials = vi
133
+ .fn()
134
+ .mockResolvedValueOnce(credsResponse(3_600_000))
135
+ .mockResolvedValueOnce(credsResponse(3_600_000));
136
+ const publish = createIotPublishPort({
137
+ fetchCredentials,
138
+ makeClient: () => iotMock as unknown as IoTDataPlaneClient,
139
+ now: () => NOW,
140
+ });
141
+
142
+ await publish(TOPIC, cleanPayload());
143
+ await publish(TOPIC, cleanPayload());
144
+ // Second publish reuses the cached client — creds vended once.
145
+ expect(fetchCredentials).toHaveBeenCalledTimes(1);
146
+ });
147
+
148
+ it("re-vends when the cached creds are within the refresh skew of expiry", async () => {
149
+ iotMock.on(PublishCommand).resolves({});
150
+ const fetchCredentials = vi
151
+ .fn()
152
+ // expires in 30s — inside the 60s refresh skew, so every call re-vends
153
+ .mockResolvedValue(credsResponse(30_000));
154
+ const publish = createIotPublishPort({
155
+ fetchCredentials,
156
+ makeClient: () => iotMock as unknown as IoTDataPlaneClient,
157
+ now: () => NOW,
158
+ });
159
+ await publish(TOPIC, cleanPayload());
160
+ await publish(TOPIC, cleanPayload());
161
+ expect(fetchCredentials).toHaveBeenCalledTimes(2);
162
+ });
163
+
164
+ it("re-guards the no-secrets contract at the transport boundary", async () => {
165
+ iotMock.on(PublishCommand).resolves({});
166
+ const fetchCredentials = vi.fn().mockResolvedValue(credsResponse(3_600_000));
167
+ const publish = createIotPublishPort({
168
+ fetchCredentials,
169
+ makeClient: () => iotMock as unknown as IoTDataPlaneClient,
170
+ now: () => NOW,
171
+ });
172
+ const dirty = cleanPayload();
173
+ // Smuggle a secret into a whitelisted field — the publisher must refuse.
174
+ dirty.sessions[0].model = "sk-ant-leaked-key";
175
+ await expect(publish(TOPIC, dirty)).rejects.toThrow(/secret marker/);
176
+ expect(iotMock.commandCalls(PublishCommand)).toHaveLength(0);
177
+ });
178
+ });
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Outpost on-box realtime publisher — mission-control US-009.
3
+ *
4
+ * The box already holds a Cognito session (seeded from the caller's refresh
5
+ * token in user-data, kept fresh by the box's auth timers — see provision.ts).
6
+ * This module turns that session into a `PublishPort` for the session-heartbeat
7
+ * emitter using the EXACT on-box credential pattern the rest of the realtime
8
+ * fabric uses (docs/realtime-fabric.md):
9
+ *
10
+ * 1. POST {HQAPI}/v1/realtime/credentials with the box's Cognito JWT.
11
+ * The Lambda resolves the caller's `personUid` from the verified JWT
12
+ * (never request input) and vends short-lived STS creds whose session
13
+ * policy scopes `iot:Connect/Publish/...` to `hq/{personUid}/*` only.
14
+ * 2. SigV4-sign an IoT Data-plane publish with those creds to
15
+ * `hq/{personUid}/sessions`.
16
+ *
17
+ * No new auth surface, no embedded long-lived key, no per-device cert — the
18
+ * per-identity STS session policy is the isolation boundary (US-010).
19
+ *
20
+ * The HTTP fetch + IoT client are injected so this is unit-testable without a
21
+ * live endpoint; `defaultRealtimeCredentialsFetcher` and the IoT publish are
22
+ * the production wiring.
23
+ */
24
+
25
+ import {
26
+ IoTDataPlaneClient,
27
+ PublishCommand,
28
+ } from "@aws-sdk/client-iot-data-plane";
29
+ import type {
30
+ PublishPort,
31
+ SessionsHeartbeatPayload,
32
+ } from "./session-heartbeat.js";
33
+ import {
34
+ assertNoSecretsInPayload,
35
+ sessionsTopicForPerson,
36
+ } from "./session-heartbeat.js";
37
+
38
+ /** Shape returned by `POST /v1/realtime/credentials` (mirrors the handler). */
39
+ export interface RealtimeCredentialsResponse {
40
+ credentials: {
41
+ accessKeyId: string;
42
+ secretAccessKey: string;
43
+ sessionToken: string;
44
+ expiration: string;
45
+ };
46
+ iotEndpoint: string;
47
+ region: string;
48
+ /** The caller's own topic — `hq/{personUid}/...`. */
49
+ topic: string;
50
+ expiresAt: string;
51
+ }
52
+
53
+ /** Fetches scoped realtime credentials for the box. Injected for tests. */
54
+ export type RealtimeCredentialsFetcher = () => Promise<RealtimeCredentialsResponse>;
55
+
56
+ /** Ceiling on a single credentials request. */
57
+ export const DEFAULT_CREDENTIALS_TIMEOUT_MS = 10_000;
58
+
59
+ /**
60
+ * Build the production credentials fetcher. Reads the box's current Cognito
61
+ * id/access token via the injected `getJwt` and POSTs it to the
62
+ * realtime-credentials endpoint.
63
+ */
64
+ export function defaultRealtimeCredentialsFetcher(opts: {
65
+ apiBaseUrl: string;
66
+ getJwt: () => Promise<string>;
67
+ fetchImpl?: typeof fetch;
68
+ /** Bound the request. Defaults to {@link DEFAULT_CREDENTIALS_TIMEOUT_MS}. */
69
+ timeoutMs?: number;
70
+ }): RealtimeCredentialsFetcher {
71
+ const doFetch = opts.fetchImpl ?? fetch;
72
+ return async () => {
73
+ const jwt = await opts.getJwt();
74
+ const res = await doFetch(`${opts.apiBaseUrl}/v1/realtime/credentials`, {
75
+ method: "POST",
76
+ // Bounded. An endpoint that accepts the connection but never answers
77
+ // would otherwise park the tick forever: the loop stops beating, the
78
+ // liveness marker goes stale, and SIGTERM cannot finish the in-flight
79
+ // tick — a hang that reads exactly like a healthy quiet box.
80
+ signal: AbortSignal.timeout(
81
+ opts.timeoutMs ?? DEFAULT_CREDENTIALS_TIMEOUT_MS,
82
+ ),
83
+ headers: {
84
+ authorization: `Bearer ${jwt}`,
85
+ "content-type": "application/json",
86
+ },
87
+ });
88
+ if (!res.ok) {
89
+ throw new Error(
90
+ `realtime/credentials returned ${res.status} ${res.statusText}`,
91
+ );
92
+ }
93
+ return (await res.json()) as RealtimeCredentialsResponse;
94
+ };
95
+ }
96
+
97
+ /** A cached IoT client keyed by endpoint+creds so we don't rebuild per tick. */
98
+ interface CachedClient {
99
+ client: IoTDataPlaneClient;
100
+ endpoint: string;
101
+ accessKeyId: string;
102
+ expiresAtMs: number;
103
+ }
104
+
105
+ /**
106
+ * Create a `PublishPort` that vends scoped creds (refreshing before expiry) and
107
+ * publishes the compact payload to the box's own sessions topic over MQTT/IoT.
108
+ *
109
+ * @param fetchCredentials vends per-identity-scoped STS creds + IoT endpoint
110
+ * @param makeClient builds an IoT client from creds (injected for tests)
111
+ * @param now clock injection
112
+ */
113
+ export function createIotPublishPort(opts: {
114
+ fetchCredentials: RealtimeCredentialsFetcher;
115
+ makeClient?: (args: {
116
+ endpoint: string;
117
+ region: string;
118
+ credentials: RealtimeCredentialsResponse["credentials"];
119
+ }) => IoTDataPlaneClient;
120
+ now?: () => Date;
121
+ }): PublishPort {
122
+ const now = opts.now ?? (() => new Date());
123
+ const makeClient =
124
+ opts.makeClient ??
125
+ (({ endpoint, region, credentials }) => {
126
+ const url = endpoint.startsWith("http")
127
+ ? endpoint
128
+ : `https://${endpoint}`;
129
+ return new IoTDataPlaneClient({
130
+ endpoint: url,
131
+ region,
132
+ credentials: {
133
+ accessKeyId: credentials.accessKeyId,
134
+ secretAccessKey: credentials.secretAccessKey,
135
+ sessionToken: credentials.sessionToken,
136
+ },
137
+ });
138
+ });
139
+
140
+ let cached: CachedClient | null = null;
141
+ // Refresh creds this many ms before they actually expire so a publish never
142
+ // races expiry mid-flight.
143
+ const REFRESH_SKEW_MS = 60_000;
144
+
145
+ async function clientFor(): Promise<{
146
+ client: IoTDataPlaneClient;
147
+ }> {
148
+ const nowMs = now().getTime();
149
+ if (cached && cached.expiresAtMs - REFRESH_SKEW_MS > nowMs) {
150
+ return { client: cached.client };
151
+ }
152
+ const vended = await opts.fetchCredentials();
153
+ const client = makeClient({
154
+ endpoint: vended.iotEndpoint,
155
+ region: vended.region,
156
+ credentials: vended.credentials,
157
+ });
158
+ cached = {
159
+ client,
160
+ endpoint: vended.iotEndpoint,
161
+ accessKeyId: vended.credentials.accessKeyId,
162
+ expiresAtMs: Date.parse(vended.credentials.expiration),
163
+ };
164
+ return { client };
165
+ }
166
+
167
+ return async (
168
+ topic: string,
169
+ payload: SessionsHeartbeatPayload,
170
+ ): Promise<void> => {
171
+ // Re-guard at the transport boundary — a publisher must never ship a
172
+ // payload that fails the no-secrets contract, regardless of caller.
173
+ assertNoSecretsInPayload(payload);
174
+ const { client } = await clientFor();
175
+ await client.send(
176
+ new PublishCommand({
177
+ topic,
178
+ qos: 0,
179
+ payload: Buffer.from(JSON.stringify(payload)),
180
+ }),
181
+ );
182
+ };
183
+ }
184
+
185
+ /** Re-export for the runner so it imports one module. */
186
+ export { sessionsTopicForPerson };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * company-work-corpus US-006 AC7 — no retained MQTT publishes for transcript
3
+ * objects.
4
+ *
5
+ * Session transcripts are pulled on demand via the presign GET path (structural
6
+ * owner+creator gate); they are NEVER pushed as message bodies over the realtime
7
+ * fabric. The on-box sessions publisher emits only a COMPACT liveness heartbeat
8
+ * (`SessionsHeartbeatPayload` — path-only session summaries, guarded by
9
+ * `assertNoSecretsInPayload`), and it must publish NON-RETAINED so a stale
10
+ * summary is never re-delivered from the broker to a late subscriber.
11
+ *
12
+ * This is a GUARD suite: it asserts the current (correct) behavior so a future
13
+ * change that (a) turns on `retain` for the sessions topic, or (b) starts
14
+ * shipping transcript/vault-file bytes over MQTT, fails loudly. No product code
15
+ * change is expected from US-006 here.
16
+ */
17
+
18
+ import { beforeEach, describe, expect, it, vi } from "vitest";
19
+ import { readFileSync } from "node:fs";
20
+ import { mockClient } from "aws-sdk-client-mock";
21
+ import {
22
+ IoTDataPlaneClient,
23
+ PublishCommand,
24
+ } from "@aws-sdk/client-iot-data-plane";
25
+ import {
26
+ createIotPublishPort,
27
+ type RealtimeCredentialsResponse,
28
+ } from "./session-heartbeat-publisher";
29
+ import type { SessionsHeartbeatPayload } from "./session-heartbeat";
30
+
31
+ const PERSON = "prs_alice";
32
+ const TOPIC = `hq/${PERSON}/sessions`;
33
+ const NOW = new Date("2026-07-11T18:55:00.000Z");
34
+
35
+ function credsResponse(): RealtimeCredentialsResponse {
36
+ return {
37
+ credentials: {
38
+ accessKeyId: "ASIAEXAMPLE",
39
+ secretAccessKey: "secret",
40
+ sessionToken: "token",
41
+ expiration: new Date(NOW.getTime() + 3_600_000).toISOString(),
42
+ },
43
+ iotEndpoint: "abc123-ats.iot.us-east-1.amazonaws.com",
44
+ region: "us-east-1",
45
+ topic: TOPIC,
46
+ expiresAt: new Date(NOW.getTime() + 3_600_000).toISOString(),
47
+ };
48
+ }
49
+
50
+ function cleanPayload(): SessionsHeartbeatPayload {
51
+ return {
52
+ type: "sessions",
53
+ origin: "outpost",
54
+ emittedAt: NOW.toISOString(),
55
+ sessions: [
56
+ {
57
+ id: "x",
58
+ tool: "claude",
59
+ origin: "outpost",
60
+ cwd: "/home/ec2-user/hq",
61
+ project: "hq",
62
+ company: null,
63
+ model: "claude-opus-4",
64
+ status: "running",
65
+ startedAt: null,
66
+ lastActivityAt: NOW.toISOString(),
67
+ source: "/home/ec2-user/.claude/projects/p/x.jsonl",
68
+ },
69
+ ],
70
+ };
71
+ }
72
+
73
+ describe("US-006 AC7 — sessions heartbeat is published NON-RETAINED", () => {
74
+ const iotMock = mockClient(IoTDataPlaneClient);
75
+ beforeEach(() => iotMock.reset());
76
+
77
+ it("the PublishCommand never sets retain=true", async () => {
78
+ iotMock.on(PublishCommand).resolves({});
79
+ const publish = createIotPublishPort({
80
+ fetchCredentials: vi.fn().mockResolvedValue(credsResponse()),
81
+ makeClient: () => iotMock as unknown as IoTDataPlaneClient,
82
+ now: () => NOW,
83
+ });
84
+
85
+ await publish(TOPIC, cleanPayload());
86
+
87
+ const call = iotMock.commandCalls(PublishCommand)[0];
88
+ // retain must be absent or explicitly false — never true (no broker
89
+ // re-delivery of a stale session summary; transcripts are pull-only).
90
+ expect(call.args[0].input.retain).not.toBe(true);
91
+ // The wire body is the compact summary envelope — no transcript body field.
92
+ const sent = JSON.parse(
93
+ Buffer.from(call.args[0].input.payload as Uint8Array).toString("utf8"),
94
+ ) as Record<string, unknown> & {
95
+ sessions: Array<Record<string, unknown>>;
96
+ };
97
+ expect(sent.type).toBe("sessions");
98
+ // The session summary carries a `source` PATH only, never file/transcript
99
+ // content — assert no body/content/transcript key ever rides the wire.
100
+ for (const s of sent.sessions) {
101
+ expect(s).not.toHaveProperty("body");
102
+ expect(s).not.toHaveProperty("content");
103
+ expect(s).not.toHaveProperty("transcript");
104
+ }
105
+ });
106
+ });
107
+
108
+ describe("US-006 AC7 — static guard: sessions/realtime publishers never retain", () => {
109
+ // The sessions publisher is the ONLY realtime path in this package that
110
+ // touches session data, and it may never set retain=true — a retained
111
+ // message would leave the last session summary sitting on the broker after
112
+ // the box goes away. (The server-side DM-wake publisher is guarded by the
113
+ // matching test in hq-pro, which is where that file lives.)
114
+ const guardedSources = [
115
+ new URL("./session-heartbeat-publisher.ts", import.meta.url),
116
+ new URL("./session-heartbeat.ts", import.meta.url),
117
+ ];
118
+
119
+ it("no guarded publisher sets retain: true", () => {
120
+ for (const url of guardedSources) {
121
+ const src = readFileSync(url, "utf8");
122
+ // Tolerate any whitespace between `retain` and `true`.
123
+ expect(src).not.toMatch(/retain\s*:\s*true/);
124
+ }
125
+ });
126
+ });