@h1r-ai/croche-cli 0.5.5 → 0.6.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 (44) hide show
  1. package/README.md +267 -148
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/dist/bin.js +29 -25
  4. package/dist/chunk-66EUX7EL.js +165 -0
  5. package/dist/chunk-DKT5HHSB.js +532 -0
  6. package/dist/chunk-K3UDT4EM.js +3110 -0
  7. package/dist/collector-credential.d.ts +9 -0
  8. package/dist/config-authoring.d.ts +19 -0
  9. package/dist/config-bases.d.ts +17 -0
  10. package/dist/config-push-base-35HX67AJ.js +2254 -0
  11. package/dist/config-push-base.d.ts +7 -0
  12. package/dist/control-address.d.ts +2 -0
  13. package/dist/control-server.d.ts +12 -15
  14. package/dist/control-server.js +9 -288
  15. package/dist/control-v2-auth.d.ts +24 -0
  16. package/dist/control-v2-capture.d.ts +34 -0
  17. package/dist/control-v2-json.d.ts +15 -0
  18. package/dist/control-v2-state.d.ts +90 -0
  19. package/dist/credentials.d.ts +2 -2
  20. package/dist/debugger/public/index.html +1 -0
  21. package/dist/debugger/public/stage-control.js +84 -0
  22. package/dist/debugger/public/stage-manifest.js +45 -0
  23. package/dist/debugger/public/stage-model.js +103 -0
  24. package/dist/debugger/public/stage-targets.js +18 -0
  25. package/dist/debugger/public/stage.css +459 -0
  26. package/dist/debugger/public/stage.html +17 -0
  27. package/dist/debugger/public/stage.js +113 -0
  28. package/dist/debugger/server/collector.js +42 -26
  29. package/dist/debugger/server/control-bridge.js +113 -0
  30. package/dist/debugger/server/server.js +10 -1
  31. package/dist/debugger/server/viewer-security.js +12 -0
  32. package/dist/debugger.d.ts +16 -6
  33. package/dist/index.d.ts +8 -1
  34. package/dist/index.js +17 -321
  35. package/dist/json-result.d.ts +2 -0
  36. package/package.json +2 -1
  37. package/dist/config.js +0 -100
  38. package/dist/control-client.js +0 -65
  39. package/dist/core-defaults.js +0 -2
  40. package/dist/credentials.js +0 -136
  41. package/dist/debug-keys.js +0 -141
  42. package/dist/debugger.js +0 -469
  43. package/dist/help.js +0 -158
  44. package/dist/text-file.js +0 -15
@@ -0,0 +1,532 @@
1
+ import {
2
+ ControlError,
3
+ body,
4
+ count,
5
+ id,
6
+ object,
7
+ record,
8
+ refuse,
9
+ remoteAddress,
10
+ reply,
11
+ same
12
+ } from "./chunk-66EUX7EL.js";
13
+
14
+ // src/control-server.ts
15
+ import { createServer } from "node:http";
16
+ import { Readable } from "node:stream";
17
+ import { isIP } from "node:net";
18
+
19
+ // src/control-v2-auth.ts
20
+ import { timingSafeEqual, randomUUID } from "node:crypto";
21
+ var equal = (a, b) => {
22
+ const x = Buffer.from(a), y = Buffer.from(b);
23
+ return x.length === y.length && timingSafeEqual(x, y);
24
+ };
25
+ var ControlAuth = class {
26
+ values = [];
27
+ constructor(options) {
28
+ const add = (token, role, attachments) => {
29
+ if (typeof token !== "string" || !/^[A-Za-z0-9._~-]{24,4096}$/.test(token) || this.values.some((value) => equal(value.token, token))) throw new Error("Control v2 requires distinct ingest, observe and controller credentials. Recreate the private v2 connection file.");
30
+ this.values.push({ token, principal: { id: "viewer-" + randomUUID(), role, attachments } });
31
+ };
32
+ add(options.token, "control", null);
33
+ add(options.ingestToken, "ingest", null);
34
+ if (options.observeToken !== void 0) add(options.observeToken, "observe", null);
35
+ for (const token of options.ingestTokens ?? []) add(token, "ingest", null);
36
+ for (const grant of options.grants ?? []) {
37
+ if (!["observe", "control"].includes(grant.role) || !Array.isArray(grant.attachments) || grant.attachments.some((a) => !id(a))) throw new Error("Invalid scoped control grant.");
38
+ add(grant.token, grant.role, new Set(grant.attachments));
39
+ }
40
+ if (this.values.length > 64) throw new Error("Too many control principals.");
41
+ }
42
+ authenticate(request, ingest, write) {
43
+ const header = request.headers.get("Authorization") ?? "", found = this.values.find((value) => equal(header, "Bearer " + value.token));
44
+ if (!found) refuse(401, "unauthorized");
45
+ const principal = found.principal;
46
+ if (principal.role === "ingest" !== ingest || !ingest && write && principal.role !== "control") refuse(403, "forbidden");
47
+ return principal;
48
+ }
49
+ permits(principal, attachmentId) {
50
+ return principal.attachments === null || principal.attachments.has(attachmentId);
51
+ }
52
+ redact(value) {
53
+ if (typeof value === "string") {
54
+ let text = value;
55
+ for (const entry of this.values) text = text.split(entry.token).join("[REDACTED]");
56
+ return text.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, "Bearer [REDACTED]").replace(/\b(?:sk-or-v1-|sk-|dk_|cdt_|cst_)[A-Za-z0-9_-]{16,}/g, "[REDACTED]").replace(/data:image\/[^\s"']+/gi, "[image omitted]");
57
+ }
58
+ if (Array.isArray(value)) return value.map((v) => this.redact(v));
59
+ if (value && typeof value === "object") {
60
+ const row = value, image = row.type === "image" || row.type === "image_url" || typeof row.mediaType === "string" && row.mediaType.startsWith("image/");
61
+ return Object.fromEntries(Object.entries(row).map(([key, v]) => [key, image && ["data", "bytes", "url", "uri", "image_url"].includes(key) ? "[image omitted]" : /^(?:authorization|cookie|password|secret|(?:api|ingest|access|refresh|runtime)[_-]?(?:key|token)|token)$/i.test(key) ? "[REDACTED]" : this.redact(v)]));
62
+ }
63
+ return value;
64
+ }
65
+ };
66
+
67
+ // src/control-v2-state.ts
68
+ var CAPS = /* @__PURE__ */ new Set(["agents.list", "status", "history", "send", "cancel", "tools"]);
69
+ function target(value) {
70
+ const t = record(value);
71
+ if (!id(t.agentId) || t.instance !== null && !id(t.instance) || !count(t.openSequence)) refuse(400, "invalid_command");
72
+ return { agentId: t.agentId, instance: t.instance, openSequence: t.openSequence };
73
+ }
74
+ function roster(value) {
75
+ const r = record(value);
76
+ if (!count(r.rosterRevision) || !Array.isArray(r.agents) || r.agents.length > 1e3) refuse(400, "invalid_registration");
77
+ const seen = /* @__PURE__ */ new Set();
78
+ const agents = r.agents.map((value2) => {
79
+ const a = record(value2);
80
+ if (!id(a.agentId) || a.instance !== null && !id(a.instance) || typeof a.open !== "boolean") refuse(400, "invalid_registration");
81
+ const pair = JSON.stringify([a.agentId, a.instance]);
82
+ if (seen.has(pair)) refuse(400, "invalid_registration");
83
+ seen.add(pair);
84
+ if (a.open) {
85
+ if (!id(a.runtimeInstanceId) || !count(a.openSequence)) refuse(400, "invalid_registration");
86
+ return { agentId: a.agentId, instance: a.instance, open: true, runtimeInstanceId: a.runtimeInstanceId, openSequence: a.openSequence };
87
+ }
88
+ if (a.runtimeInstanceId !== void 0 || a.openSequence !== void 0) refuse(400, "invalid_registration");
89
+ return { agentId: a.agentId, instance: a.instance, open: false };
90
+ });
91
+ return { rosterRevision: r.rosterRevision, agents };
92
+ }
93
+ var ControlState = class {
94
+ constructor(now, monotonic, project = (v) => v) {
95
+ this.now = now;
96
+ this.monotonic = monotonic;
97
+ this.project = project;
98
+ }
99
+ attachments = /* @__PURE__ */ new Map();
100
+ requests = /* @__PURE__ */ new Map();
101
+ fits(value) {
102
+ if (Math.max(Buffer.byteLength(JSON.stringify(value)), Buffer.byteLength(JSON.stringify(this.project(value)))) > 1024 * 1024 - 1024) refuse(413, "too_large");
103
+ }
104
+ used() {
105
+ return Buffer.byteLength(JSON.stringify([[...this.attachments.values()], [...this.requests.values()]])) + this.requests.size * 1024;
106
+ }
107
+ capacity(extra = 0) {
108
+ if (this.used() + extra > 8 * 1024 * 1024) refuse(429, "control_capacity");
109
+ }
110
+ rosterCapacity(candidate) {
111
+ const rows = [...this.attachments.values()].filter((a) => a.attachmentId !== candidate.attachmentId);
112
+ rows.push(candidate);
113
+ this.fits({ attachments: rows });
114
+ }
115
+ expire() {
116
+ for (const a of this.attachments.values()) if (a.state === "connected" && this.monotonic() >= a.expires) this.detach(a);
117
+ for (const [key, r] of this.requests) if (["completed", "failed"].includes(r.status) && this.now() - r.updated_at >= 30 * 60 * 1e3) this.requests.delete(key);
118
+ }
119
+ detach(a) {
120
+ a.state = "disconnected";
121
+ for (const request of this.requests.values()) if (request.attachmentId === a.attachmentId && ["queued", "dispatched"].includes(request.status)) {
122
+ request.error = { code: "runtime_detached", ...request.status === "dispatched" ? { uncertain: true } : {} };
123
+ request.status = "failed";
124
+ request.updated_at = this.now();
125
+ }
126
+ }
127
+ owned(value, p) {
128
+ if (!id(value)) refuse(400, "invalid_identity");
129
+ const a = this.attachments.get(value);
130
+ if (!a) refuse(409, "runtime_detached");
131
+ if (a.principal !== p.id) refuse(403, "forbidden");
132
+ return a;
133
+ }
134
+ live(value, p) {
135
+ const a = this.owned(value, p);
136
+ if (a.state !== "connected") refuse(409, "runtime_detached");
137
+ return a;
138
+ }
139
+ validateTarget(a, t, command = "send") {
140
+ if (command === "agents.list") {
141
+ if (t) refuse(400, "invalid_command");
142
+ return;
143
+ }
144
+ if (!t) refuse(400, "invalid_command");
145
+ const row = a.agents.find((r) => r.agentId === t.agentId && r.instance === t.instance);
146
+ if (!row) refuse(400, "invalid_command");
147
+ if (!row.open || row.openSequence !== t.openSequence) refuse(409, "target_closed");
148
+ }
149
+ checkRoster(a, value) {
150
+ const r = roster(value);
151
+ if (r.rosterRevision < a.rosterRevision) refuse(409, "roster_conflict");
152
+ if (r.rosterRevision === a.rosterRevision && !same(r.agents, a.agents)) refuse(409, "roster_conflict");
153
+ this.rosterCapacity({ ...a, ...r });
154
+ return r;
155
+ }
156
+ updateRoster(a, value) {
157
+ const r = this.checkRoster(a, value);
158
+ a.rosterRevision = r.rosterRevision;
159
+ a.agents = r.agents;
160
+ }
161
+ register(b, p) {
162
+ if (!id(b.attachmentId) || !object(b.runtime) || !Array.isArray(b.capabilities) || b.capabilities.length > 100 || b.capabilities.some((v) => typeof v !== "string" || v.length > 200)) refuse(400, "invalid_registration");
163
+ const f = b.runtime;
164
+ if (f.project !== null && !id(f.project) || typeof f.platform !== "string" || !f.platform || f.platform.length > 100 || f.coreVersion !== void 0 && (typeof f.coreVersion !== "string" || f.coreVersion.length > 100)) refuse(400, "invalid_registration");
165
+ const r = roster(b), runtime = { project: f.project, platform: f.platform, ...f.coreVersion === void 0 ? {} : { coreVersion: f.coreVersion } }, capabilities = [...new Set(b.capabilities)];
166
+ const previous = this.attachments.get(b.attachmentId);
167
+ if (previous) {
168
+ if (previous.principal !== p.id) refuse(403, "forbidden");
169
+ if (previous.state !== "connected") refuse(409, "runtime_detached");
170
+ if (!same(previous.runtime, runtime) || !same(previous.capabilities, capabilities)) refuse(409, "registration_conflict");
171
+ this.capacity(Math.max(0, Buffer.byteLength(JSON.stringify(r)) - Buffer.byteLength(JSON.stringify({ agents: previous.agents }))));
172
+ this.updateRoster(previous, r);
173
+ } else {
174
+ if (this.attachments.size >= 100) refuse(429, "control_capacity");
175
+ this.capacity(Buffer.byteLength(JSON.stringify(b)));
176
+ const candidate = { attachmentId: b.attachmentId, principal: p.id, runtime, capabilities, state: "connected", ...r, expires: this.monotonic() + 15e3 };
177
+ this.rosterCapacity(candidate);
178
+ this.attachments.set(b.attachmentId, candidate);
179
+ }
180
+ return { attachmentId: b.attachmentId, brokerVersion: "croche-control-v2", pollIntervalMs: 5e3, leaseMs: 15e3 };
181
+ }
182
+ queue(b, p, a) {
183
+ if (!id(b.request_id) || typeof b.command !== "string") refuse(400, "invalid_command");
184
+ if (!CAPS.has(b.command) || !a.capabilities.includes(b.command)) refuse(409, "unsupported_capability");
185
+ const t = b.target === void 0 ? void 0 : target(b.target), payload = record(b.payload), command = b.command;
186
+ if (command === "agents.list" && Object.keys(payload).length) refuse(400, "invalid_command");
187
+ if (command === "send") {
188
+ if (!id(payload.id) || typeof payload.text !== "string" || Object.hasOwn(payload, "kind") && !["user", "app_event", "app_state"].includes(payload.kind)) refuse(400, "invalid_command");
189
+ if (Object.hasOwn(payload, "kind") && !a.capabilities.includes("send.kind")) refuse(409, "unsupported_capability");
190
+ }
191
+ const previous = this.requests.get(b.request_id);
192
+ if (previous) {
193
+ if (!same([previous.attachmentId, previous.command, previous.target, previous.payload], [a.attachmentId, command, t, payload])) refuse(409, "request_conflict");
194
+ return previous;
195
+ }
196
+ if (a.state !== "connected") refuse(409, "runtime_detached");
197
+ this.validateTarget(a, t, command);
198
+ if (this.requests.size >= 1e3) refuse(429, "control_capacity");
199
+ this.capacity(Buffer.byteLength(JSON.stringify(b)) + 1024);
200
+ const entry = { attachmentId: a.attachmentId, request_id: b.request_id, command, ...t ? { target: t } : {}, payload, viewerId: p.id, status: "queued", created_at: this.now(), updated_at: this.now() };
201
+ this.fits({ request: entry });
202
+ this.requests.set(entry.request_id, entry);
203
+ return entry;
204
+ }
205
+ poll(a) {
206
+ a.expires = this.monotonic() + 15e3;
207
+ const commands = [];
208
+ for (const r of this.requests.values()) if (r.attachmentId === a.attachmentId && r.status === "queued") {
209
+ try {
210
+ this.validateTarget(a, r.target, r.command);
211
+ } catch {
212
+ r.status = "failed";
213
+ r.error = { code: "target_closed" };
214
+ r.updated_at = this.now();
215
+ continue;
216
+ }
217
+ if (Buffer.byteLength(JSON.stringify({ attachmentId: a.attachmentId, commands: [...commands, r] })) > 1024 * 1024 - 1024) break;
218
+ r.status = "dispatched";
219
+ r.updated_at = this.now();
220
+ commands.push(r);
221
+ if (commands.length === 8) break;
222
+ }
223
+ return { attachmentId: a.attachmentId, commands: commands.map(({ attachmentId, request_id, command, target: target2, payload, viewerId }) => ({ attachmentId, request_id, command, ...target2 ? { target: target2 } : {}, payload, viewerId })) };
224
+ }
225
+ result(b, a) {
226
+ if (!id(b.request_id)) refuse(400, "invalid_identity");
227
+ const r = this.requests.get(b.request_id);
228
+ if (!r || r.attachmentId !== a.attachmentId) refuse(404, "not_found");
229
+ if (!same(r.target, b.target === void 0 ? void 0 : target(b.target))) refuse(409, "result_conflict");
230
+ if (r.status === "queued") refuse(409, "not_dispatched");
231
+ const hasResult = Object.hasOwn(b, "result"), hasError = Object.hasOwn(b, "error");
232
+ if (hasResult === hasError) refuse(400, "invalid_result");
233
+ let error;
234
+ if (hasError) {
235
+ const e = record(b.error);
236
+ if (typeof e.code !== "string" || !/^[a-z][a-z0-9_]{0,99}$/.test(e.code) || e.category !== void 0 && (typeof e.category !== "string" || e.category.length > 100) || e.uncertain !== void 0 && e.uncertain !== true) refuse(400, "invalid_result");
237
+ error = { code: e.code, ...e.category === void 0 ? {} : { category: e.category }, ...e.uncertain === true ? { uncertain: true } : {} };
238
+ }
239
+ if (r.status === "completed" || r.status === "failed") {
240
+ if (r.error?.code !== "runtime_detached" && !same([r.result, r.error], [hasResult ? b.result : void 0, error])) refuse(409, "result_conflict");
241
+ return { request_id: r.request_id, retained: true };
242
+ }
243
+ this.fits({ request: { ...r, status: hasError ? "failed" : "completed", ...hasError ? { error } : { result: b.result } } });
244
+ this.capacity(Buffer.byteLength(JSON.stringify(b)));
245
+ r.status = hasError ? "failed" : "completed";
246
+ if (hasError) r.error = error;
247
+ else r.result = b.result;
248
+ r.updated_at = this.now();
249
+ return { request_id: r.request_id, retained: true };
250
+ }
251
+ };
252
+
253
+ // src/control-v2-capture.ts
254
+ import { createHash } from "node:crypto";
255
+ var canonical = (v) => Array.isArray(v) ? "[" + v.map(canonical).join(",") + "]" : object(v) ? "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canonical(v[k])).join(",") + "}" : JSON.stringify(v);
256
+ var digest = (v) => createHash("sha256").update(canonical(v)).digest("hex");
257
+ function publicEvent(event) {
258
+ if (event.type === "roster") {
259
+ const r = roster(event);
260
+ return { type: "roster", ...r };
261
+ }
262
+ if (event.visibility !== "runtime") return null;
263
+ if (event.type === "model.request" && object(event.data) && ["messages", "body", "prompt", "system", "instructions"].some((k) => Object.hasOwn(event.data, k))) return null;
264
+ return event;
265
+ }
266
+ var ControlCapture = class {
267
+ streams = /* @__PURE__ */ new Map();
268
+ used() {
269
+ let total = 0;
270
+ for (const s of this.streams.values()) total += s.bytes + s.seen.size * 96 + Buffer.byteLength(JSON.stringify(s.gaps));
271
+ return total;
272
+ }
273
+ ingest(b, redact, capacity, validateRoster) {
274
+ if (!count(b.firstSeq) || b.firstSeq < 1 || !count(b.lastSeq) || !Array.isArray(b.events) || !b.events.length || b.events.length > 100 || b.lastSeq !== b.firstSeq + b.events.length - 1) refuse(400, "invalid_events");
275
+ const key = String(b.attachmentId), prior = this.streams.get(key) ?? { through: 0, cursor: 0, entries: [], seen: /* @__PURE__ */ new Map(), gaps: [], bytes: 0 };
276
+ let latest = b.roster === void 0 ? void 0 : roster(b.roster);
277
+ const captures = b.events.map((value, index) => {
278
+ const c = record(value);
279
+ if (c.seq !== Number(b.firstSeq) + index || !object(c.event)) refuse(400, "invalid_events");
280
+ if (Buffer.byteLength(JSON.stringify(c.event)) > 128 * 1024) refuse(413, "event_too_large");
281
+ if (c.event.type === "roster") {
282
+ const next = roster(c.event);
283
+ if (latest && next.rosterRevision === latest.rosterRevision && !same(next.agents, latest.agents)) refuse(409, "roster_conflict");
284
+ if (!latest || next.rosterRevision > latest.rosterRevision) latest = next;
285
+ }
286
+ return { seq: Number(c.seq), event: c.event };
287
+ });
288
+ for (const capture of captures) if (capture.seq <= prior.through && prior.seen.get(capture.seq) !== digest(capture)) refuse(409, "event_conflict");
289
+ const fresh = captures.filter((c) => c.seq > prior.through);
290
+ if (!fresh.length) return { through: prior.through, events: [] };
291
+ const first = fresh[0].seq, missing = first - prior.through - 1;
292
+ if ((prior.through === 0 || missing > 0) && !latest) refuse(400, "roster_required");
293
+ if (missing > 0) {
294
+ const gap = record(b.gap);
295
+ if (gap.from !== prior.through + 1 || gap.through !== first - 1 || typeof gap.reason !== "string" || !gap.reason || gap.reason.length > 100) refuse(400, "invalid_gap");
296
+ } else if (b.gap !== void 0) refuse(400, "invalid_gap");
297
+ if (latest) validateRoster(latest);
298
+ capacity(Buffer.byteLength(JSON.stringify(b)) + fresh.length * 96);
299
+ const s = prior, delivered = [];
300
+ if (missing > 0) {
301
+ s.gaps.push({ from: s.cursor + 1, through: s.cursor + missing, reason: "source_dropped" });
302
+ s.cursor += missing;
303
+ }
304
+ for (const capture of fresh) {
305
+ const projected = publicEvent(capture.event), safe = projected ? redact(projected) : null;
306
+ const kept = safe ? { seq: capture.seq, event: safe } : null, bytes = Buffer.byteLength(JSON.stringify(kept));
307
+ s.entries.push({ cursor: ++s.cursor, capture: kept, bytes });
308
+ s.bytes += bytes;
309
+ s.seen.set(capture.seq, digest(capture));
310
+ if (safe && safe.type !== "roster") delivered.push(safe);
311
+ while (s.entries.length > 2e3 || s.bytes > 4 * 1024 * 1024) {
312
+ s.bytes -= s.entries.shift().bytes;
313
+ }
314
+ }
315
+ s.through = Number(b.lastSeq);
316
+ this.streams.set(key, s);
317
+ return { through: s.through, ...latest ? { roster: latest } : {}, events: delivered };
318
+ }
319
+ read(attachmentId, after) {
320
+ if (!count(after)) refuse(400, "invalid_cursor");
321
+ const s = this.streams.get(attachmentId);
322
+ if (!s) return { attachmentId, entries: [], through: 0, gaps: [] };
323
+ if (after > s.cursor) refuse(409, "cursor_ahead");
324
+ const low = s.entries[0]?.cursor ?? s.cursor + 1;
325
+ const entries = [], gaps = s.gaps.filter((g) => g.through >= low && g.through > after).map((g) => ({ ...g, from: Math.max(g.from, after + 1, low) }));
326
+ let through = after, bytes = 0;
327
+ if (after + 1 < low) gaps.push({ from: after + 1, through: low - 1, reason: "evicted" });
328
+ for (const row of s.entries) if (row.cursor > after) {
329
+ if (bytes + row.bytes > 512 * 1024) break;
330
+ bytes += row.bytes;
331
+ through = row.cursor;
332
+ if (row.capture) entries.push({ cursor: row.cursor, capture: row.capture });
333
+ else gaps.push({ from: row.cursor, through: row.cursor, reason: "withheld" });
334
+ }
335
+ return { attachmentId, entries, through, gaps: gaps.filter((g) => g.from <= through) };
336
+ }
337
+ };
338
+
339
+ // src/control-server.ts
340
+ var ControlBroker = class {
341
+ constructor(options) {
342
+ this.options = options;
343
+ this.auth = new ControlAuth(options);
344
+ this.origins = new Set((options.origins ?? []).map((origin) => {
345
+ const u = new URL(origin);
346
+ if (!["http:", "https:"].includes(u.protocol) || u.origin !== origin) throw Error("Control origins must be exact HTTP(S) origins.");
347
+ return origin;
348
+ }));
349
+ if (options.remoteAddress !== void 0) {
350
+ const normalized = remoteAddress(options.remoteAddress);
351
+ if (!normalized || !this.origins.size) throw Error("Remote viewers require an explicit non-loopback IP address and an origin allowlist; wildcard binds are refused.");
352
+ this.options = { ...options, remoteAddress: normalized };
353
+ }
354
+ this.state = new ControlState(options.now ?? Date.now, options.monotonic ?? options.now ?? (() => performance.now()), (v) => this.auth.redact(v));
355
+ this.timer = setInterval(() => this.state.expire(), 1e3);
356
+ this.timer.unref?.();
357
+ }
358
+ auth;
359
+ state;
360
+ capture = new ControlCapture();
361
+ origins;
362
+ timer;
363
+ close() {
364
+ clearInterval(this.timer);
365
+ for (const a of this.state.attachments.values()) this.state.detach(a);
366
+ }
367
+ async handle(request, remoteViewer = false) {
368
+ let allowedOrigin;
369
+ try {
370
+ const url = new URL(request.url), host = request.headers.get("Host") ?? url.host;
371
+ let h;
372
+ try {
373
+ h = new URL("http://" + host);
374
+ } catch {
375
+ return refuse(403, "host_forbidden");
376
+ }
377
+ const allowedHosts = remoteViewer && this.options.remoteAddress ? [new URL("http://" + (isIP(this.options.remoteAddress) === 6 ? "[" + this.options.remoteAddress + "]" : this.options.remoteAddress)).hostname] : remoteViewer ? [] : ["localhost", "127.0.0.1", "[::1]"];
378
+ if (url.protocol !== "http:" || !allowedHosts.includes(url.hostname) || !allowedHosts.includes(h.hostname) || h.host !== url.host || h.username || h.password || h.pathname !== "/") refuse(403, "host_forbidden");
379
+ const origin = request.headers.get("Origin");
380
+ if (origin) {
381
+ if (!this.origins.has(origin)) refuse(403, "origin_forbidden");
382
+ allowedOrigin = origin;
383
+ }
384
+ if (remoteViewer && !allowedOrigin) refuse(403, "origin_forbidden");
385
+ if (url.search || url.hash) refuse(404, "not_found");
386
+ if (request.method === "OPTIONS") {
387
+ if (!allowedOrigin) refuse(403, "origin_forbidden");
388
+ return new Response(null, { status: 204, headers: { "Cache-Control": "no-store", "Access-Control-Allow-Origin": allowedOrigin, "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Authorization, Content-Type", "Access-Control-Allow-Private-Network": "true", "Vary": "Origin" } });
389
+ }
390
+ if (/^\/v\d+\/control(?:\/|$)/.test(url.pathname) && !url.pathname.startsWith("/v2/control/")) refuse(409, "protocol_mismatch");
391
+ const ingest = /^\/v2\/control\/(register|poll|results|events|unregister)$/.test(url.pathname);
392
+ if (remoteViewer && ingest) refuse(403, "remote_ingest_forbidden");
393
+ const p = this.auth.authenticate(request, ingest, !ingest && url.pathname === "/v2/control/commands");
394
+ this.state.expire();
395
+ let result;
396
+ if (request.method === "GET" && url.pathname === "/v2/control/attachments") {
397
+ result = reply({ viewer: { id: p.id, role: p.role }, attachments: [...this.state.attachments.values()].filter((a) => this.auth.permits(p, a.attachmentId)).map(({ principal, expires, ...a }) => a) });
398
+ } else if (request.method === "GET" && url.pathname.startsWith("/v2/control/requests/")) {
399
+ const key = url.pathname.slice("/v2/control/requests/".length), r = id(key) ? this.state.requests.get(key) : void 0;
400
+ if (!r || !this.auth.permits(p, r.attachmentId)) refuse(404, "not_found");
401
+ result = reply({ request: r });
402
+ } else if (request.method === "POST") {
403
+ const b = await body(request);
404
+ if (url.pathname === "/v2/control/register") result = reply(this.state.register(b, p));
405
+ else if (ingest) {
406
+ const a = this.state.owned(b.attachmentId, p);
407
+ if (url.pathname.endsWith("/unregister")) {
408
+ this.state.detach(a);
409
+ result = reply({ attachmentId: a.attachmentId, detached: true });
410
+ } else if (url.pathname.endsWith("/results")) result = reply(this.state.result(b, a));
411
+ else if (url.pathname.endsWith("/poll")) {
412
+ this.state.live(a.attachmentId, p);
413
+ result = reply(this.state.poll(a));
414
+ } else if (url.pathname.endsWith("/events")) {
415
+ this.state.live(a.attachmentId, p);
416
+ const captured = this.capture.ingest(b, (v) => this.auth.redact(v), (extra) => this.state.capacity(this.capture.used() + extra), (r) => {
417
+ if (r.rosterRevision >= a.rosterRevision) this.state.checkRoster(a, r);
418
+ });
419
+ if (captured.roster && captured.roster.rosterRevision >= a.rosterRevision) this.state.updateRoster(a, captured.roster);
420
+ result = reply({ attachmentId: a.attachmentId, through: captured.through });
421
+ } else refuse(404, "not_found");
422
+ } else if (url.pathname === "/v2/control/commands") {
423
+ if (!id(b.attachmentId) || !this.auth.permits(p, b.attachmentId)) refuse(404, "not_found");
424
+ const a = this.state.attachments.get(b.attachmentId);
425
+ if (!a) refuse(404, "not_found");
426
+ const r = this.state.queue(b, p, a);
427
+ result = reply({ request: r }, ["queued", "dispatched"].includes(r.status) ? 202 : 200);
428
+ } else if (url.pathname === "/v2/control/read") {
429
+ if (!id(b.attachmentId) || !this.auth.permits(p, b.attachmentId) || !this.state.attachments.has(b.attachmentId)) refuse(404, "not_found");
430
+ result = reply(this.capture.read(b.attachmentId, b.after));
431
+ } else refuse(404, "not_found");
432
+ } else refuse(404, "not_found");
433
+ if (allowedOrigin) {
434
+ result.headers.set("Access-Control-Allow-Origin", allowedOrigin);
435
+ result.headers.set("Vary", "Origin");
436
+ }
437
+ if (ingest) return result;
438
+ const safe = reply(this.auth.redact(await result.json()), result.status);
439
+ result.headers.forEach((value, key) => safe.headers.set(key, value));
440
+ return safe;
441
+ } catch (e) {
442
+ const issue = e instanceof ControlError ? e : new ControlError(500, "internal_error");
443
+ const result = reply({ error: { code: issue.code } }, issue.status);
444
+ if (allowedOrigin) {
445
+ result.headers.set("Access-Control-Allow-Origin", allowedOrigin);
446
+ result.headers.set("Vary", "Origin");
447
+ }
448
+ return result;
449
+ }
450
+ }
451
+ };
452
+ async function startControlServer(options) {
453
+ const broker = new ControlBroker(options);
454
+ const create = (remoteViewer) => {
455
+ const server2 = createServer(async (incoming, outgoing) => {
456
+ try {
457
+ const address = server2.address();
458
+ if (!incoming.url?.startsWith("/")) {
459
+ outgoing.writeHead(400);
460
+ outgoing.end();
461
+ return;
462
+ }
463
+ const headers = new Headers();
464
+ for (const [key, value] of Object.entries(incoming.headers)) if (value !== void 0) headers.set(key, Array.isArray(value) ? value.join(",") : value);
465
+ const init = { method: incoming.method, headers };
466
+ if (!["GET", "HEAD"].includes(incoming.method ?? "GET")) {
467
+ init.body = Readable.toWeb(incoming);
468
+ init.duplex = "half";
469
+ }
470
+ const host = remoteViewer ? isIP(options.remoteAddress) === 6 ? "[" + options.remoteAddress + "]" : options.remoteAddress : "127.0.0.1";
471
+ const receivedHost = incoming.headers.host ?? `${host}:${address.port}`;
472
+ let received;
473
+ try {
474
+ received = new URL("http://" + receivedHost);
475
+ } catch {
476
+ outgoing.writeHead(403).end();
477
+ return;
478
+ }
479
+ if (Number(received.port || 80) !== address.port) {
480
+ outgoing.writeHead(403).end();
481
+ return;
482
+ }
483
+ const result = await broker.handle(new Request(`http://${receivedHost}${incoming.url}`, init), remoteViewer), responseHeaders = {};
484
+ result.headers.forEach((value, key) => {
485
+ responseHeaders[key] = value;
486
+ });
487
+ outgoing.writeHead(result.status, responseHeaders);
488
+ outgoing.end(Buffer.from(await result.arrayBuffer()));
489
+ } catch {
490
+ outgoing.writeHead(500, { "Content-Type": "application/json", "Cache-Control": "no-store" });
491
+ outgoing.end('{"error":{"code":"internal_error"}}');
492
+ }
493
+ });
494
+ server2.requestTimeout = 6e3;
495
+ server2.headersTimeout = 5e3;
496
+ return server2;
497
+ };
498
+ const server = create(false), viewer = options.remoteAddress ? create(true) : void 0;
499
+ await new Promise((resolve, reject) => {
500
+ server.once("error", reject);
501
+ server.listen(options.port ?? 8791, "127.0.0.1", () => {
502
+ server.off("error", reject);
503
+ resolve();
504
+ });
505
+ });
506
+ const port = server.address().port;
507
+ const close = async () => {
508
+ broker.close();
509
+ for (const s of [viewer, server]) if (s?.listening) {
510
+ s.closeAllConnections();
511
+ await new Promise((resolve, reject) => s.close((e) => e ? reject(e) : resolve()));
512
+ }
513
+ };
514
+ try {
515
+ if (viewer) await new Promise((resolve, reject) => {
516
+ viewer.once("error", reject);
517
+ viewer.listen(port, options.remoteAddress, () => {
518
+ viewer.off("error", reject);
519
+ resolve();
520
+ });
521
+ });
522
+ } catch (e) {
523
+ await close();
524
+ throw e;
525
+ }
526
+ return { url: `http://127.0.0.1:${port}`, ...viewer ? { remoteUrl: `http://${isIP(options.remoteAddress) === 6 ? "[" + options.remoteAddress + "]" : options.remoteAddress}:${port}` } : {}, broker, close };
527
+ }
528
+
529
+ export {
530
+ ControlBroker,
531
+ startControlServer
532
+ };