@indigoai-us/hq-cli 5.77.12 → 5.77.13

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.
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Payload bounding for the Outpost session heartbeat.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * The heartbeat enumerates every Claude transcript and Codex rollout on the
7
+ * box. On a long-lived Outpost that is an archive, not a status: the box this
8
+ * was first run against had **8,258 Claude transcripts and 1,082 Codex
9
+ * rollouts — 9,340 sessions — of which 15 had any activity in the last 15
10
+ * minutes.** Publishing all of them produced a payload of roughly 1.9 MB.
11
+ *
12
+ * AWS IoT Core rejects anything over 128 KB, so the very first real publish
13
+ * failed with `payload larger than 131072 bytes`. Every subsequent one would
14
+ * have too. The heartbeat is a liveness signal; it must carry what is live.
15
+ *
16
+ * Two rules, both tested here:
17
+ * 1. `ended` sessions are not published — they are history, and re-sending
18
+ * thousands of them every five seconds is the bug.
19
+ * 2. Whatever survives that filter is still bounded by BYTES, because a busy
20
+ * box could exceed the limit on live sessions alone. When the bound bites
21
+ * it is reported, never silent — a truncated payload that looks complete
22
+ * is how you get a wrong dashboard instead of a missing one.
23
+ */
24
+
25
+ import { describe, expect, it } from "vitest";
26
+ import {
27
+ DEFAULT_LIVENESS_THRESHOLDS,
28
+ IOT_PAYLOAD_BUDGET_BYTES,
29
+ collectSessions,
30
+ type DirEntry,
31
+ type FileStat,
32
+ type FileSystemPort,
33
+ } from "./session-heartbeat.js";
34
+
35
+ const NOW = new Date("2026-07-29T12:00:00.000Z");
36
+ const NOW_MS = NOW.getTime();
37
+
38
+ /**
39
+ * A fake Claude tree with `count` transcripts, each aged `ageSecondsFor(i)`.
40
+ * Codex enumeration sees an empty tree.
41
+ */
42
+ function claudeTreeFs(
43
+ count: number,
44
+ ageSecondsFor: (i: number) => number,
45
+ ): FileSystemPort {
46
+ const names = Array.from(
47
+ { length: count },
48
+ (_, i) =>
49
+ `${i.toString(16).padStart(8, "0")}-aaaa-bbbb-cccc-dddddddddddd.jsonl`,
50
+ );
51
+ const ageOf = new Map<string, number>();
52
+ names.forEach((n, i) => ageOf.set(n, ageSecondsFor(i)));
53
+
54
+ return {
55
+ async readDir(path: string): Promise<DirEntry[]> {
56
+ if (path.endsWith("/.claude/projects")) {
57
+ return [{ name: "-home-ec2-user-hq", isDirectory: true, isFile: false }];
58
+ }
59
+ if (path.endsWith("/.claude/projects/-home-ec2-user-hq")) {
60
+ return names.map((name) => ({
61
+ name,
62
+ isDirectory: false,
63
+ isFile: true,
64
+ }));
65
+ }
66
+ return [];
67
+ },
68
+ async stat(path: string): Promise<FileStat> {
69
+ const name = path.split("/").pop() ?? "";
70
+ const age = ageOf.get(name) ?? 0;
71
+ const mtimeMs = NOW_MS - age * 1000;
72
+ return { mtimeMs, birthtimeMs: mtimeMs, size: 1024 };
73
+ },
74
+ async readTextFile() {
75
+ return "";
76
+ },
77
+ async readBounded() {
78
+ // A realistic cwd/model sniff, so each record is a realistic size.
79
+ return JSON.stringify({
80
+ cwd: "/home/ec2-user/hq/repos/private/some-longish-repo-name",
81
+ model: "claude-opus-4-8",
82
+ });
83
+ },
84
+ };
85
+ }
86
+
87
+ const config = { personUid: "prs_01TEST", home: "/home/ec2-user", now: () => NOW };
88
+
89
+ describe("payload bounding", () => {
90
+ it("publishes live sessions and drops the ended archive", async () => {
91
+ // 500 sessions: the first 5 active, the rest ancient — the real shape of
92
+ // a box that has been running for weeks.
93
+ const fs = claudeTreeFs(500, (i) => (i < 5 ? 2 : 60 * 60 * 24 * 30));
94
+
95
+ const payload = await collectSessions(config, { fs });
96
+
97
+ expect(payload.sessions).toHaveLength(5);
98
+ expect(payload.sessions.every((s) => s.status !== "ended")).toBe(true);
99
+ });
100
+
101
+ it("reports how many sessions exist, not just how many it sent", async () => {
102
+ const fs = claudeTreeFs(500, (i) => (i < 5 ? 2 : 60 * 60 * 24 * 30));
103
+
104
+ const payload = await collectSessions(config, { fs });
105
+
106
+ // Silent filtering reads as "this box has 5 sessions". It has 500.
107
+ expect(payload.totalSessions).toBe(500);
108
+ expect(payload.sessions.length).toBeLessThan(payload.totalSessions);
109
+ });
110
+
111
+ it("keeps idle sessions — only `ended` is archive", async () => {
112
+ // 2s → running, 5min → idle, 30d → ended.
113
+ const fs = claudeTreeFs(3, (i) => [2, 300, 60 * 60 * 24 * 30][i]!);
114
+
115
+ const payload = await collectSessions(config, { fs });
116
+
117
+ const statuses = payload.sessions.map((s) => s.status).sort();
118
+ expect(statuses).toEqual(["idle", "running"]);
119
+ });
120
+
121
+ it("stays under the IoT limit even when every session is live", async () => {
122
+ // 5,000 sessions all active — the size bound, not the status filter, is
123
+ // what has to hold here.
124
+ const fs = claudeTreeFs(5000, () => 2);
125
+
126
+ const payload = await collectSessions(config, { fs });
127
+ const bytes = Buffer.byteLength(JSON.stringify(payload), "utf8");
128
+
129
+ expect(bytes).toBeLessThanOrEqual(IOT_PAYLOAD_BUDGET_BYTES);
130
+ // The real AWS IoT Core ceiling. The budget must leave headroom under it.
131
+ expect(bytes).toBeLessThan(131072);
132
+ });
133
+
134
+ it("flags truncation rather than quietly shortening the list", async () => {
135
+ const fs = claudeTreeFs(5000, () => 2);
136
+
137
+ const payload = await collectSessions(config, { fs });
138
+
139
+ expect(payload.truncated).toBe(true);
140
+ expect(payload.totalSessions).toBe(5000);
141
+ expect(payload.sessions.length).toBeLessThan(5000);
142
+ });
143
+
144
+ it("does not flag truncation when everything fits", async () => {
145
+ const fs = claudeTreeFs(3, () => 2);
146
+
147
+ const payload = await collectSessions(config, { fs });
148
+
149
+ expect(payload.truncated).toBe(false);
150
+ expect(payload.sessions).toHaveLength(3);
151
+ expect(payload.totalSessions).toBe(3);
152
+ });
153
+
154
+ it("reads transcript bodies ONLY for sessions it will publish", async () => {
155
+ // The enumerator statted every file AND did a 16 KiB bounded read on each,
156
+ // before anything was filtered. On the first real box that was 9,340 reads
157
+ // per tick, every 5 seconds — ~150 MB of disk for 15 useful records, on
158
+ // the exact resource that had already taken the machine down once.
159
+ const reads: string[] = [];
160
+ const base = claudeTreeFs(500, (i) => (i < 5 ? 2 : 60 * 60 * 24 * 30));
161
+ const fs: FileSystemPort = {
162
+ ...base,
163
+ async readBounded(path, maxBytes, from) {
164
+ reads.push(path);
165
+ return base.readBounded(path, maxBytes, from);
166
+ },
167
+ };
168
+
169
+ const payload = await collectSessions(config, { fs });
170
+
171
+ expect(payload.sessions).toHaveLength(5);
172
+ // Five live sessions ⇒ five reads, not five hundred.
173
+ expect(reads).toHaveLength(5);
174
+ });
175
+
176
+ it("keeps the MOST RECENTLY ACTIVE sessions when it has to choose", async () => {
177
+ // Index 0 is freshest, index N oldest — all still within `idle`.
178
+ const fs = claudeTreeFs(5000, (i) => 1 + i * (1 / 10));
179
+
180
+ const payload = await collectSessions(config, { fs });
181
+
182
+ expect(payload.truncated).toBe(true);
183
+ // Dropping the newest and keeping stale ones would make the live view
184
+ // wrong in the one way that matters.
185
+ const kept = payload.sessions
186
+ .map((s) => Date.parse(s.lastActivityAt!))
187
+ .sort((a, b) => a - b);
188
+ const oldestKept = kept[0]!;
189
+ const cutoff =
190
+ NOW_MS - DEFAULT_LIVENESS_THRESHOLDS.idleWithinSeconds * 1000;
191
+ expect(oldestKept).toBeGreaterThan(cutoff);
192
+ // The single freshest session must always survive.
193
+ expect(Math.max(...kept)).toBe(NOW_MS - 1000);
194
+ });
195
+ });
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The no-secrets guard must catch credentials WITHOUT catching ordinary paths.
3
+ *
4
+ * Both halves matter equally, and the second is easy to get wrong. The guard
5
+ * throws, and a throw fails the whole tick — so a pattern that matches a
6
+ * legitimate directory name silently disables reporting for the entire box
7
+ * until that session ages out.
8
+ *
9
+ * The original marker list held `sk-` and `asia` as bare substrings. `sk-`
10
+ * matches `task-runner`, `flask-app`, `disk-usage`, `risk-model`. Anyone who
11
+ * created a repo with one of those names would have taken the heartbeat down
12
+ * across the box, with the service still reporting active — the exact failure
13
+ * shape this whole change exists to remove.
14
+ */
15
+
16
+ import { describe, expect, it } from "vitest";
17
+ import {
18
+ assertNoSecretsInPayload,
19
+ type AgentSession,
20
+ type SessionsHeartbeatPayload,
21
+ } from "./session-heartbeat.js";
22
+
23
+ function payloadWith(over: Partial<AgentSession>): SessionsHeartbeatPayload {
24
+ const session: AgentSession = {
25
+ id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
26
+ tool: "claude",
27
+ origin: "outpost",
28
+ cwd: "/home/ec2-user/hq",
29
+ project: "hq",
30
+ company: null,
31
+ model: "claude-opus-4-8",
32
+ status: "running",
33
+ startedAt: "2026-07-29T12:00:00.000Z",
34
+ lastActivityAt: "2026-07-29T12:00:00.000Z",
35
+ source: "/home/ec2-user/.claude/projects/-home-ec2-user-hq/x.jsonl",
36
+ ...over,
37
+ };
38
+ return {
39
+ type: "sessions",
40
+ origin: "outpost",
41
+ emittedAt: "2026-07-29T12:00:00.000Z",
42
+ sessions: [session],
43
+ };
44
+ }
45
+
46
+ describe("ordinary paths must never trip the guard", () => {
47
+ // Every one of these contains `sk-` or `asia` and would have thrown before.
48
+ const innocentPaths = [
49
+ "/home/ec2-user/hq/repos/private/task-runner",
50
+ "/home/ec2-user/hq/repos/public/flask-app",
51
+ "/home/ec2-user/hq/tools/disk-usage",
52
+ "/home/ec2-user/hq/models/risk-model",
53
+ "/home/ec2-user/hq/regions/asia-pacific",
54
+ "/home/ec2-user/hq/repos/private/password-manager",
55
+ "/home/ec2-user/hq/kiosk-display",
56
+ ];
57
+
58
+ for (const cwd of innocentPaths) {
59
+ it(`allows ${cwd.split("/").pop()}`, () => {
60
+ const project = cwd.split("/").pop()!;
61
+ expect(() =>
62
+ assertNoSecretsInPayload(payloadWith({ cwd, project, source: `${cwd}/s.jsonl` })),
63
+ ).not.toThrow();
64
+ });
65
+ }
66
+
67
+ it("allows a model id that merely starts with the letters sk", () => {
68
+ expect(() =>
69
+ assertNoSecretsInPayload(payloadWith({ model: "sk-lite-preview" })),
70
+ ).not.toThrow();
71
+ });
72
+ });
73
+
74
+ describe("real credentials must still be caught", () => {
75
+ const leaks: [string, Partial<AgentSession>][] = [
76
+ ["an Anthropic key", { model: "sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv" }],
77
+ ["an OpenAI-style key", { model: "sk-AbCdEfGhIjKlMnOpQrStUvWxYz012345" }],
78
+ ["a long-lived AWS key id", { project: "AKIAIOSFODNN7EXAMPLE" }],
79
+ ["an STS temp key id", { project: "ASIAIOSFODNN7EXAMPLE" }],
80
+ ["a PEM private key", { cwd: "-----BEGIN RSA PRIVATE KEY-----" }],
81
+ ["an authorization header", { model: "authorization: xyz" }],
82
+ ["a bearer token", { model: "Bearer abcdefghijklmnop0123" }],
83
+ ["an instance token header", { project: "x-outpost-instance-token" }],
84
+ ["a refresh token field", { model: 'refresh_token="abc"' }],
85
+ ["a password field", { model: "password=hunter2" }],
86
+ ["a secret access key", { project: "secretaccesskey" }],
87
+ ["a session token", { project: "sessiontoken" }],
88
+ ];
89
+
90
+ for (const [what, over] of leaks) {
91
+ it(`rejects ${what}`, () => {
92
+ expect(() => assertNoSecretsInPayload(payloadWith(over))).toThrow(
93
+ /refusing to publish/,
94
+ );
95
+ });
96
+ }
97
+ });
98
+
99
+ describe("non-whitelisted fields are still rejected", () => {
100
+ it("refuses a payload carrying an extra field", () => {
101
+ const p = payloadWith({});
102
+ (p.sessions[0] as unknown as Record<string, unknown>).transcript = "secret";
103
+ expect(() => assertNoSecretsInPayload(p)).toThrow(/non-whitelisted/);
104
+ });
105
+ });
@@ -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 };