@openparachute/agent 0.2.0 → 0.2.3-rc.10

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 (70) hide show
  1. package/.parachute/module.json +3 -3
  2. package/package.json +8 -1
  3. package/src/agent-defs.ts +9 -0
  4. package/src/auth.ts +182 -14
  5. package/src/backends/registry.ts +65 -27
  6. package/src/daemon.ts +311 -12
  7. package/src/def-vault-triggers.ts +317 -0
  8. package/src/preflight.ts +139 -0
  9. package/src/spawn-agent.ts +16 -0
  10. package/src/step-up.ts +316 -0
  11. package/src/terminal-ui.ts +73 -0
  12. package/src/transports/http-ui.ts +10 -8
  13. package/src/transports/vault.ts +40 -22
  14. package/src/ui-kit.ts +6 -3
  15. package/src/ui-ticket.ts +121 -0
  16. package/web/ui/dist/assets/index-Dhr5Kl_d.css +1 -0
  17. package/web/ui/dist/assets/index-Di5MmFZR.js +60 -0
  18. package/web/ui/dist/index.html +15 -0
  19. package/src/_parked/interactive-spawn.test.ts +0 -324
  20. package/src/_parked/interactive-spawn.ts +0 -701
  21. package/src/agent-defs.test.ts +0 -1504
  22. package/src/agent-mcp-config.test.ts +0 -115
  23. package/src/agents.test.ts +0 -360
  24. package/src/auth.test.ts +0 -46
  25. package/src/backends/attached-queue.test.ts +0 -376
  26. package/src/backends/programmatic.test.ts +0 -1715
  27. package/src/backends/registry.test.ts +0 -1494
  28. package/src/backends/stream-json.test.ts +0 -570
  29. package/src/channel-backend-wiring.test.ts +0 -237
  30. package/src/credentials.test.ts +0 -274
  31. package/src/cron.test.ts +0 -342
  32. package/src/daemon-agent-def-api.test.ts +0 -166
  33. package/src/daemon-agent-defs-api.test.ts +0 -953
  34. package/src/daemon-agent-env-api.test.ts +0 -338
  35. package/src/daemon-attached-queue-store.test.ts +0 -65
  36. package/src/daemon-config-api.test.ts +0 -962
  37. package/src/daemon-jobs-api.test.ts +0 -271
  38. package/src/daemon-vault-chat.test.ts +0 -250
  39. package/src/daemon.test.ts +0 -746
  40. package/src/def-vaults.test.ts +0 -136
  41. package/src/delivery-state.test.ts +0 -110
  42. package/src/effective-env.test.ts +0 -114
  43. package/src/grants.test.ts +0 -638
  44. package/src/hub-jwt.test.ts +0 -161
  45. package/src/jobs.test.ts +0 -245
  46. package/src/mcp-http.test.ts +0 -265
  47. package/src/mint-token.test.ts +0 -152
  48. package/src/module-manifest.test.ts +0 -158
  49. package/src/programmatic-wiring.test.ts +0 -838
  50. package/src/registry.test.ts +0 -227
  51. package/src/resolve-port.test.ts +0 -64
  52. package/src/routing.test.ts +0 -184
  53. package/src/runner.test.ts +0 -506
  54. package/src/sandbox/config.test.ts +0 -150
  55. package/src/sandbox/egress.test.ts +0 -113
  56. package/src/sandbox/live-seatbelt.test.ts +0 -277
  57. package/src/sandbox/mounts.test.ts +0 -154
  58. package/src/sandbox/sandbox.test.ts +0 -168
  59. package/src/services-manifest.test.ts +0 -106
  60. package/src/spa-serve.test.ts +0 -116
  61. package/src/spawn-agent-cli.test.ts +0 -172
  62. package/src/spawn-agent.test.ts +0 -1218
  63. package/src/spawn-deps.test.ts +0 -54
  64. package/src/terminal-assets.test.ts +0 -50
  65. package/src/terminal.test.ts +0 -530
  66. package/src/transports/http-ui.test.ts +0 -455
  67. package/src/transports/telegram.test.ts +0 -174
  68. package/src/transports/vault.test.ts +0 -2011
  69. package/src/ui-kit.test.ts +0 -178
  70. package/web/ui/tsconfig.json +0 -21
@@ -1,746 +0,0 @@
1
- /**
2
- * Daemon auth-gate tests (Layer 1, bridge-facing).
3
- *
4
- * Spins the real daemon fetch handler (`createFetchHandler`) on an ephemeral
5
- * `Bun.serve` with one http-ui channel, and asserts the bridge-facing endpoints
6
- * reject a request with no Authorization header (401) while the UI-facing /
7
- * discovery endpoints stay open (200).
8
- *
9
- * Crucially this needs NO live hub / JWKS: the no-token path in `requireScope`
10
- * short-circuits before any JWKS fetch. We deliberately do NOT mint or validate
11
- * a real JWT here — that's scope-guard's own tested surface. What we own is the
12
- * routing layer: which endpoints are guarded, which are exempt, and that the
13
- * no-token reject is wired in front of the guarded handlers.
14
- */
15
- import { describe, test, expect, beforeAll, afterAll } from "bun:test";
16
- import { createFetchHandler, resolveStartCmd, buildTurnEventSink } from "./daemon.ts";
17
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
18
- import { tmpdir } from "node:os";
19
- import { join } from "node:path";
20
- import { ClientRegistry } from "./routing.ts";
21
- import { HttpUiTransport } from "./transports/http-ui.ts";
22
- import { VaultTransport } from "./transports/vault.ts";
23
- import type { Channel } from "./registry.ts";
24
- import type { TransportContext, InboundMessage } from "./transport.ts";
25
-
26
- let server: ReturnType<typeof Bun.serve>;
27
- let base: string;
28
- let envHome: string | undefined;
29
- let envHubOrigin: string | undefined;
30
- let homeDir: string;
31
-
32
- beforeAll(async () => {
33
- // Pin PARACHUTE_HOME at an empty temp dir + clear PARACHUTE_HUB_ORIGIN so
34
- // `getHubOrigin()` resolves deterministically to loopback. Without this the
35
- // OAuth-discovery assertions below (which expect the loopback hub origin) flake
36
- // on any box that has a real `~/.parachute/expose-state.json` — `getHubOrigin`
37
- // now self-heals from expose-state's `hubOrigin` (channel#34), so a tailnet /
38
- // public state file would otherwise leak the exposed origin into the doc.
39
- envHome = process.env.PARACHUTE_HOME;
40
- envHubOrigin = process.env.PARACHUTE_HUB_ORIGIN;
41
- homeDir = mkdtempSync(join(tmpdir(), "agent-daemon-home-"));
42
- process.env.PARACHUTE_HOME = homeDir;
43
- delete process.env.PARACHUTE_HUB_ORIGIN;
44
-
45
- const registry = new ClientRegistry();
46
- const transport = new HttpUiTransport({ channel: "ui1" });
47
- const channels = new Map<string, Channel>([
48
- ["ui1", { name: "ui1", transport, entry: { name: "ui1", transport: "http-ui" } }],
49
- ]);
50
- // Wire the transport's ctx so its ingestHttp routes (open) work.
51
- await transport.start({
52
- channel: "ui1",
53
- emit: () => {},
54
- emitPermissionVerdict: () => {},
55
- });
56
-
57
- server = Bun.serve({
58
- port: 0,
59
- hostname: "127.0.0.1",
60
- idleTimeout: 0,
61
- fetch: createFetchHandler(channels, registry),
62
- });
63
- base = `http://127.0.0.1:${server.port}`;
64
- });
65
-
66
- afterAll(() => {
67
- server.stop(true);
68
- if (envHome === undefined) delete process.env.PARACHUTE_HOME;
69
- else process.env.PARACHUTE_HOME = envHome;
70
- if (envHubOrigin === undefined) delete process.env.PARACHUTE_HUB_ORIGIN;
71
- else process.env.PARACHUTE_HUB_ORIGIN = envHubOrigin;
72
- try {
73
- rmSync(homeDir, { recursive: true, force: true });
74
- } catch {}
75
- });
76
-
77
- describe("bridge-facing endpoints require a bearer token (401 with none)", () => {
78
- test("GET /events with no Authorization → 401", async () => {
79
- const res = await fetch(`${base}/events?channel=ui1`);
80
- expect(res.status).toBe(401);
81
- const body = (await res.json()) as { error: string };
82
- expect(body.error).toBe("unauthorized");
83
- // Make sure the SSE stream did NOT open — a 401 must short-circuit.
84
- expect(res.headers.get("content-type")).toContain("application/json");
85
- });
86
-
87
- test("POST /api/reply with no Authorization → 401", async () => {
88
- const res = await fetch(`${base}/api/reply`, {
89
- method: "POST",
90
- headers: { "content-type": "application/json" },
91
- body: JSON.stringify({ channel: "ui1", text: "hi" }),
92
- });
93
- expect(res.status).toBe(401);
94
- expect(((await res.json()) as { error: string }).error).toBe("unauthorized");
95
- });
96
-
97
- test("POST /api/react with no Authorization → 401", async () => {
98
- const res = await fetch(`${base}/api/react`, {
99
- method: "POST",
100
- headers: { "content-type": "application/json" },
101
- body: JSON.stringify({ channel: "ui1", message_id: "1", emoji: "👍" }),
102
- });
103
- expect(res.status).toBe(401);
104
- });
105
-
106
- test("POST /api/edit with no Authorization → 401", async () => {
107
- const res = await fetch(`${base}/api/edit`, {
108
- method: "POST",
109
- headers: { "content-type": "application/json" },
110
- body: JSON.stringify({ channel: "ui1", message_id: "1", text: "x" }),
111
- });
112
- expect(res.status).toBe(401);
113
- });
114
-
115
- test("POST /api/permission with no Authorization → 401", async () => {
116
- const res = await fetch(`${base}/api/permission`, {
117
- method: "POST",
118
- headers: { "content-type": "application/json" },
119
- body: JSON.stringify({
120
- channel: "ui1",
121
- request_id: "r1",
122
- tool_name: "Bash",
123
- description: "",
124
- input_preview: "",
125
- }),
126
- });
127
- expect(res.status).toBe(401);
128
- });
129
-
130
- test("POST /api/download with no Authorization → 401", async () => {
131
- const res = await fetch(`${base}/api/download`, {
132
- method: "POST",
133
- headers: { "content-type": "application/json" },
134
- body: JSON.stringify({ channel: "ui1", file_id: "f1" }),
135
- });
136
- expect(res.status).toBe(401);
137
- });
138
-
139
- test("GET /api/channels/<ch>/turn-events with no Authorization → 401 (agent:read gated)", async () => {
140
- const res = await fetch(`${base}/api/channels/ui1/turn-events`);
141
- expect(res.status).toBe(401);
142
- expect(((await res.json()) as { error: string }).error).toBe("unauthorized");
143
- // The SSE stream must NOT open on a 401 — the gate short-circuits to JSON.
144
- expect(res.headers.get("content-type")).toContain("application/json");
145
- });
146
-
147
- test("an invalid bearer is also rejected (401, no JWKS needed for a non-JWT)", async () => {
148
- // A non-JWT bearer can't reach the JWKS — looksLikeJwt is false so the lib
149
- // rejects shape-first. Still no network.
150
- const res = await fetch(`${base}/api/reply`, {
151
- method: "POST",
152
- headers: { "content-type": "application/json", authorization: "Bearer not-a-jwt" },
153
- body: JSON.stringify({ channel: "ui1", text: "hi" }),
154
- });
155
- expect(res.status).toBe(401);
156
- });
157
- });
158
-
159
- describe("UI-facing + discovery endpoints stay open (no token, 200)", () => {
160
- test("GET /health → 200", async () => {
161
- const res = await fetch(`${base}/health`);
162
- expect(res.status).toBe(200);
163
- const body = (await res.json()) as { status: string };
164
- expect(body.status).toBe("ok");
165
- });
166
-
167
- test("GET /.parachute/config → 200", async () => {
168
- const res = await fetch(`${base}/.parachute/config`);
169
- expect(res.status).toBe(200);
170
- const body = (await res.json()) as { channels: unknown[] };
171
- expect(Array.isArray(body.channels)).toBe(true);
172
- });
173
-
174
- test("GET /.parachute/config/schema → 200", async () => {
175
- const res = await fetch(`${base}/.parachute/config/schema`);
176
- expect(res.status).toBe(200);
177
- });
178
-
179
- });
180
-
181
- // ---------------------------------------------------------------------------
182
- // Phase 4c — the server-rendered HTML pages retired into the v2 SPA. Each page
183
- // route now 302s to the SPA (relative Location so it resolves daemon-direct AND
184
- // hub-proxied). The CRITICAL footgun: retiring the `/ui` PAGE must NOT touch the
185
- // `/ui/events` message SSE the SPA Chat depends on — that's an EXACT `=== "/ui"`
186
- // match, with `/ui/events` still owned by the http-ui transport. /terminal is
187
- // demoted (off the SPA nav) but stays a live 200.
188
- // ---------------------------------------------------------------------------
189
- describe("Phase 4c — retired pages redirect to the SPA; the data plane survives", () => {
190
- for (const { path, location } of [
191
- { path: "/agents", location: "app/" },
192
- { path: "/jobs", location: "app/" },
193
- { path: "/home", location: "app/" },
194
- { path: "/admin", location: "app/" },
195
- { path: "/", location: "app/" },
196
- // /ui → the SPA Chat route (basename-relative `/chat`).
197
- { path: "/ui", location: "app/chat" },
198
- ]) {
199
- test(`GET ${path} → 302 to ${location}`, async () => {
200
- const res = await fetch(`${base}${path}`, { redirect: "manual" });
201
- expect(res.status).toBe(302);
202
- expect(res.headers.get("location")).toBe(location);
203
- });
204
- }
205
-
206
- test("FOOTGUN GUARD — GET /ui/events STILL routes to the SSE handler (NOT redirected)", async () => {
207
- // The /ui page retired, but /ui/events is the message SSE the SPA Chat
208
- // subscribes to (owned by the http-ui transport's ingestHttp). It must NOT
209
- // be swallowed by the `/ui` redirect. With no ?token= it 401s at the SSE
210
- // gate — proving it reached the handler, not the 302 page route.
211
- const res = await fetch(`${base}/ui/events?channel=ui1`, { redirect: "manual" });
212
- expect(res.status).toBe(401);
213
- expect(res.headers.get("content-type")).toContain("application/json");
214
- expect(((await res.json()) as { error: string }).error).toBe("unauthorized");
215
- });
216
-
217
- test("GET /terminal STILL serves the page (demoted, off the SPA nav, but live)", async () => {
218
- const res = await fetch(`${base}/terminal`);
219
- expect(res.status).toBe(200);
220
- expect(res.headers.get("content-type")).toContain("text/html");
221
- });
222
-
223
- test("a representative /api/* route STILL works (gated, not redirected)", async () => {
224
- // /api/reply with no Authorization → 401 (the data plane is intact; the
225
- // route still reaches requireScope rather than a page redirect).
226
- const res = await fetch(`${base}/api/reply`, {
227
- method: "POST",
228
- headers: { "content-type": "application/json" },
229
- body: JSON.stringify({ channel: "ui1", text: "hi" }),
230
- redirect: "manual",
231
- });
232
- expect(res.status).toBe(401);
233
- });
234
- });
235
-
236
- // ---------------------------------------------------------------------------
237
- // OAuth discovery for the HTTP MCP surface (RFC 9728 + RFC 8414). These are the
238
- // endpoints a Claude Code HTTP-MCP client probes when adding the agent by URL.
239
- // Path-insertion form (`.well-known` ABOVE the resource path), mirroring vault.
240
- // PUBLIC — no token needed (they must be reachable before the client has one).
241
- // ---------------------------------------------------------------------------
242
- describe("OAuth discovery (RFC 9728 / RFC 8414) — public, points at the hub", () => {
243
- // The hub origin the daemon advertises as the authorization server. Set on the
244
- // module's getHubOrigin via PARACHUTE_HUB_ORIGIN; default loopback otherwise.
245
- const HUB = process.env.PARACHUTE_HUB_ORIGIN?.replace(/\/$/, "") || "http://127.0.0.1:1939";
246
-
247
- test("GET /.well-known/oauth-protected-resource/mcp/ui1 → 200, names hub + agent scopes", async () => {
248
- const res = await fetch(`${base}/.well-known/oauth-protected-resource/mcp/ui1`);
249
- expect(res.status).toBe(200);
250
- const body = (await res.json()) as {
251
- resource: string;
252
- authorization_servers: string[];
253
- scopes_supported: string[];
254
- bearer_methods_supported: string[];
255
- };
256
- expect(body.authorization_servers).toEqual([HUB]);
257
- expect(body.scopes_supported).toEqual(["agent:read", "agent:write"]);
258
- expect(body.bearer_methods_supported).toEqual(["header"]);
259
- // No forwarded host → loopback resource URL at /mcp/<channel> (no /agent prefix).
260
- expect(body.resource).toBe(`${base}/mcp/ui1`);
261
- });
262
-
263
- test("X-Forwarded-Host builds the PUBLIC resource URL (with /agent mount prefix)", async () => {
264
- const res = await fetch(`${base}/.well-known/oauth-protected-resource/mcp/ui1`, {
265
- headers: { "x-forwarded-host": "parachute.taildf9ce2.ts.net", "x-forwarded-proto": "https" },
266
- });
267
- expect(res.status).toBe(200);
268
- const body = (await res.json()) as { resource: string };
269
- expect(body.resource).toBe("https://parachute.taildf9ce2.ts.net/agent/mcp/ui1");
270
- });
271
-
272
- test("GET /.well-known/oauth-authorization-server/mcp/ui1 → 200, forwards every endpoint to the hub", async () => {
273
- const res = await fetch(`${base}/.well-known/oauth-authorization-server/mcp/ui1`);
274
- expect(res.status).toBe(200);
275
- const body = (await res.json()) as {
276
- issuer: string;
277
- authorization_endpoint: string;
278
- token_endpoint: string;
279
- registration_endpoint: string;
280
- jwks_uri: string;
281
- scopes_supported: string[];
282
- };
283
- expect(body.issuer).toBe(HUB);
284
- expect(body.authorization_endpoint).toBe(`${HUB}/oauth/authorize`);
285
- expect(body.token_endpoint).toBe(`${HUB}/oauth/token`);
286
- expect(body.registration_endpoint).toBe(`${HUB}/oauth/register`);
287
- expect(body.jwks_uri).toBe(`${HUB}/.well-known/jwks.json`);
288
- expect(body.scopes_supported).toEqual(["agent:read", "agent:write"]);
289
- });
290
- });
291
-
292
- // ---------------------------------------------------------------------------
293
- // RFC 9728 WWW-Authenticate challenge on the /mcp/<channel> 401. A plain 401
294
- // gives a spec OAuth client no way to find the authorization server; the header
295
- // names the protected-resource metadata document so the client can discover
296
- // OAuth and start the flow. Only the /mcp path carries it (it's the one that
297
- // drives a spec client); /events + /api/* stay plain 401.
298
- // ---------------------------------------------------------------------------
299
- describe("MCP 401 carries the WWW-Authenticate challenge (RFC 9728)", () => {
300
- test("POST /mcp/ui1 with no bearer → 401 + WWW-Authenticate naming the PRM URL", async () => {
301
- const res = await fetch(`${base}/mcp/ui1`, {
302
- method: "POST",
303
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
304
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
305
- });
306
- expect(res.status).toBe(401);
307
- const header = res.headers.get("WWW-Authenticate");
308
- expect(header).toBe(
309
- `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource/mcp/ui1"`,
310
- );
311
- // And the URL the header names is a route the daemon actually serves.
312
- const prmUrl = header!.match(/resource_metadata="([^"]+)"/)![1]!;
313
- const prm = await fetch(prmUrl);
314
- expect(prm.status).toBe(200);
315
- });
316
-
317
- test("behind the hub (x-forwarded-host) the challenge names the PUBLIC PRM URL", async () => {
318
- const res = await fetch(`${base}/mcp/ui1`, {
319
- method: "POST",
320
- headers: {
321
- "content-type": "application/json",
322
- "x-forwarded-host": "parachute.taildf9ce2.ts.net",
323
- "x-forwarded-proto": "https",
324
- },
325
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
326
- });
327
- expect(res.status).toBe(401);
328
- expect(res.headers.get("WWW-Authenticate")).toBe(
329
- 'Bearer resource_metadata="https://parachute.taildf9ce2.ts.net/agent/.well-known/oauth-protected-resource/mcp/ui1"',
330
- );
331
- });
332
-
333
- test("the other bridge endpoints stay plain 401 (no challenge)", async () => {
334
- const events = await fetch(`${base}/events?channel=ui1`);
335
- expect(events.status).toBe(401);
336
- expect(events.headers.get("WWW-Authenticate")).toBeNull();
337
- const reply = await fetch(`${base}/api/reply`, {
338
- method: "POST",
339
- headers: { "content-type": "application/json" },
340
- body: JSON.stringify({ channel: "ui1", text: "hi" }),
341
- });
342
- expect(reply.status).toBe(401);
343
- expect(reply.headers.get("WWW-Authenticate")).toBeNull();
344
- });
345
- });
346
-
347
- // ---------------------------------------------------------------------------
348
- // Layer 2 (human↔UI): the http-ui transport's send + SSE routes are gated the
349
- // same way — a hub JWT (no-token → 401, short-circuits pre-JWKS). The token may
350
- // arrive as a Bearer header (send) or a ?token= query param (SSE). Asserted here
351
- // through the REAL daemon fetch handler so we cover the daemon → ingestHttp →
352
- // requireScope wiring, not just the transport in isolation.
353
- // ---------------------------------------------------------------------------
354
- describe("Layer 2 — http-ui UI endpoints require a token (401 with none)", () => {
355
- test("POST /api/channels/ui1/send with no token → 401", async () => {
356
- const res = await fetch(`${base}/api/channels/ui1/send`, {
357
- method: "POST",
358
- headers: { "content-type": "application/json" },
359
- body: JSON.stringify({ text: "from-ui" }),
360
- });
361
- expect(res.status).toBe(401);
362
- expect(((await res.json()) as { error: string }).error).toBe("unauthorized");
363
- });
364
-
365
- test("GET /ui/events with no ?token= → 401", async () => {
366
- const res = await fetch(`${base}/ui/events?channel=ui1`);
367
- expect(res.status).toBe(401);
368
- // Must short-circuit before the SSE stream opens.
369
- expect(res.headers.get("content-type")).toContain("application/json");
370
- });
371
- });
372
-
373
- // ---------------------------------------------------------------------------
374
- // Vault inbound webhook: POST /api/vault/inbound. A vault trigger POSTs here on
375
- // a new inbound #agent/message note; the daemon validates the per-channel
376
- // shared secret, resolves the channel from note.metadata.channel, and hands the
377
- // note to the channel's VaultTransport.ingestInbound (which emits → wakes the
378
- // session). Secret auth, unknown-channel 404, idempotency by note id.
379
- // ---------------------------------------------------------------------------
380
- describe("Vault inbound webhook — POST /api/vault/inbound", () => {
381
- const SECRET = "s3cret";
382
-
383
- /** Build a daemon over one vault channel + a fake transport ctx recording emits. */
384
- function buildVaultServer() {
385
- const registry = new ClientRegistry();
386
- const transport = new VaultTransport({
387
- vault: "default",
388
- vaultUrl: "http://127.0.0.1:1940",
389
- token: "x",
390
- webhookSecret: SECRET,
391
- });
392
- const emitted: InboundMessage[] = [];
393
- const ctx: TransportContext = {
394
- channel: "eng",
395
- emit(msg) {
396
- emitted.push(msg);
397
- },
398
- emitPermissionVerdict() {},
399
- };
400
- void transport.start(ctx);
401
- const channels = new Map<string, Channel>([
402
- ["eng", { name: "eng", transport, entry: { name: "eng", transport: "vault" } }],
403
- ]);
404
- const srv = Bun.serve({
405
- port: 0,
406
- hostname: "127.0.0.1",
407
- idleTimeout: 0,
408
- fetch: createFetchHandler(channels, registry),
409
- });
410
- return { srv, base: `http://127.0.0.1:${srv.port}`, emitted };
411
- }
412
-
413
- function body(
414
- noteId: string,
415
- extraMeta: Record<string, unknown> = {},
416
- tags: string[] = ["#agent/message", "#agent/message/inbound"],
417
- ) {
418
- return JSON.stringify({
419
- trigger: "channel-inbound",
420
- event: "created",
421
- note: {
422
- id: noteId,
423
- path: `channel/eng/${noteId}`,
424
- content: "wake up session",
425
- tags,
426
- metadata: { channel: "eng", direction: "inbound", sender: "aaron", ...extraMeta },
427
- },
428
- });
429
- }
430
-
431
- test("wrong secret → 401, no emit", async () => {
432
- const { srv, base, emitted } = buildVaultServer();
433
- try {
434
- const res = await fetch(`${base}/api/vault/inbound?secret=wrong`, {
435
- method: "POST",
436
- headers: { "content-type": "application/json" },
437
- body: body("n1"),
438
- });
439
- expect(res.status).toBe(401);
440
- expect(emitted).toHaveLength(0);
441
- } finally {
442
- srv.stop(true);
443
- }
444
- });
445
-
446
- test("missing secret → 401", async () => {
447
- const { srv, base, emitted } = buildVaultServer();
448
- try {
449
- const res = await fetch(`${base}/api/vault/inbound`, {
450
- method: "POST",
451
- headers: { "content-type": "application/json" },
452
- body: body("n1"),
453
- });
454
- expect(res.status).toBe(401);
455
- expect(emitted).toHaveLength(0);
456
- } finally {
457
- srv.stop(true);
458
- }
459
- });
460
-
461
- test("unknown channel → 401 (uniform with bad-secret, no channel enumeration), no emit", async () => {
462
- const { srv, base, emitted } = buildVaultServer();
463
- try {
464
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
465
- method: "POST",
466
- headers: { "content-type": "application/json" },
467
- body: JSON.stringify({
468
- note: { id: "n1", content: "x", metadata: { channel: "nope", direction: "inbound" } },
469
- }),
470
- });
471
- expect(res.status).toBe(401);
472
- expect(emitted).toHaveLength(0);
473
- } finally {
474
- srv.stop(true);
475
- }
476
- });
477
-
478
- test("channel-spoofing: a webhook for channel B presenting channel A's secret → 401, no emit", async () => {
479
- const registry = new ClientRegistry();
480
- const eng = new VaultTransport({ vault: "default", vaultUrl: "http://127.0.0.1:1940", token: "x", webhookSecret: "eng-secret" });
481
- const ops = new VaultTransport({ vault: "default", vaultUrl: "http://127.0.0.1:1940", token: "x", webhookSecret: "ops-secret" });
482
- const engEmits: InboundMessage[] = [];
483
- const opsEmits: InboundMessage[] = [];
484
- void eng.start({ channel: "eng", emit: (m) => engEmits.push(m), emitPermissionVerdict() {} });
485
- void ops.start({ channel: "ops", emit: (m) => opsEmits.push(m), emitPermissionVerdict() {} });
486
- const channels = new Map<string, Channel>([
487
- ["eng", { name: "eng", transport: eng, entry: { name: "eng", transport: "vault" } }],
488
- ["ops", { name: "ops", transport: ops, entry: { name: "ops", transport: "vault" } }],
489
- ]);
490
- const srv = Bun.serve({ port: 0, hostname: "127.0.0.1", idleTimeout: 0, fetch: createFetchHandler(channels, registry) });
491
- try {
492
- const res = await fetch(`http://127.0.0.1:${srv.port}/api/vault/inbound?secret=eng-secret`, {
493
- method: "POST",
494
- headers: { "content-type": "application/json" },
495
- body: JSON.stringify({ note: { id: "spoof1", content: "x", metadata: { channel: "ops", direction: "inbound" } } }),
496
- });
497
- expect(res.status).toBe(401); // eng's secret can't authorize a write to ops
498
- expect(opsEmits).toHaveLength(0);
499
- expect(engEmits).toHaveLength(0);
500
- } finally {
501
- srv.stop(true);
502
- }
503
- });
504
-
505
- test("missing routing key (neither agent nor channel) → 400", async () => {
506
- const { srv, base } = buildVaultServer();
507
- try {
508
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
509
- method: "POST",
510
- headers: { "content-type": "application/json" },
511
- body: JSON.stringify({ note: { id: "n1", content: "x", metadata: {} } }),
512
- });
513
- expect(res.status).toBe(400);
514
- } finally {
515
- srv.stop(true);
516
- }
517
- });
518
-
519
- test("valid (query secret) → 200 + routes to the channel's transport + emits", async () => {
520
- const { srv, base, emitted } = buildVaultServer();
521
- try {
522
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
523
- method: "POST",
524
- headers: { "content-type": "application/json" },
525
- body: body("n-ok"),
526
- });
527
- expect(res.status).toBe(200);
528
- expect(await res.json()).toEqual({ ok: true });
529
- expect(emitted).toHaveLength(1);
530
- expect(emitted[0]!.channel).toBe("eng");
531
- expect(emitted[0]!.content).toBe("wake up session");
532
- expect(emitted[0]!.meta.note_id).toBe("n-ok");
533
- expect(emitted[0]!.meta.source).toBe("vault");
534
- } finally {
535
- srv.stop(true);
536
- }
537
- });
538
-
539
- test("EXPAND-PHASE dual-read: a note carrying ONLY metadata.agent (no channel) routes + emits", async () => {
540
- const { srv, base, emitted } = buildVaultServer();
541
- try {
542
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
543
- method: "POST",
544
- headers: { "content-type": "application/json" },
545
- body: JSON.stringify({
546
- note: {
547
- id: "agent-only-1",
548
- content: "wake up via agent key",
549
- tags: ["#agent/message", "#agent/message/inbound"],
550
- // NO `channel` field — the routing key is carried ONLY under the new `agent` alias.
551
- metadata: { agent: "eng", direction: "inbound", sender: "aaron" },
552
- },
553
- }),
554
- });
555
- expect(res.status).toBe(200);
556
- expect(emitted).toHaveLength(1);
557
- expect(emitted[0]!.channel).toBe("eng");
558
- expect(emitted[0]!.content).toBe("wake up via agent key");
559
- } finally {
560
- srv.stop(true);
561
- }
562
- });
563
-
564
- test("BACK-COMPAT dual-read: a note carrying ONLY legacy metadata.channel (no agent) still routes + emits", async () => {
565
- const { srv, base, emitted } = buildVaultServer();
566
- try {
567
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
568
- method: "POST",
569
- headers: { "content-type": "application/json" },
570
- body: JSON.stringify({
571
- note: {
572
- id: "channel-only-1",
573
- content: "wake up via legacy channel key",
574
- tags: ["#agent/message", "#agent/message/inbound"],
575
- // ONLY the legacy `channel` field — a pre-expand writer; must still route.
576
- metadata: { channel: "eng", direction: "inbound", sender: "aaron" },
577
- },
578
- }),
579
- });
580
- expect(res.status).toBe(200);
581
- expect(emitted).toHaveLength(1);
582
- expect(emitted[0]!.channel).toBe("eng");
583
- expect(emitted[0]!.content).toBe("wake up via legacy channel key");
584
- } finally {
585
- srv.stop(true);
586
- }
587
- });
588
-
589
- test("valid via X-Channel-Webhook-Secret header → 200 + emits", async () => {
590
- const { srv, base, emitted } = buildVaultServer();
591
- try {
592
- const res = await fetch(`${base}/api/vault/inbound`, {
593
- method: "POST",
594
- headers: { "content-type": "application/json", "x-channel-webhook-secret": SECRET },
595
- body: body("n-hdr"),
596
- });
597
- expect(res.status).toBe(200);
598
- expect(emitted).toHaveLength(1);
599
- } finally {
600
- srv.stop(true);
601
- }
602
- });
603
-
604
- test("duplicate note id → no double-emit (idempotency)", async () => {
605
- const { srv, base, emitted } = buildVaultServer();
606
- try {
607
- for (let i = 0; i < 2; i++) {
608
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
609
- method: "POST",
610
- headers: { "content-type": "application/json" },
611
- body: body("dup-1"),
612
- });
613
- expect(res.status).toBe(200); // both ack
614
- }
615
- expect(emitted).toHaveLength(1); // but only one wake
616
- } finally {
617
- srv.stop(true);
618
- }
619
- });
620
-
621
- test("#agent/message/outbound-tagged note is ack'd 200 but NOT emitted (belt-and-suspenders)", async () => {
622
- const { srv, base, emitted } = buildVaultServer();
623
- try {
624
- const res = await fetch(`${base}/api/vault/inbound?secret=${SECRET}`, {
625
- method: "POST",
626
- headers: { "content-type": "application/json" },
627
- body: body("ob-1", { direction: "outbound" }, ["#agent/message", "#agent/message/outbound"]),
628
- });
629
- expect(res.status).toBe(200);
630
- expect(emitted).toHaveLength(0);
631
- } finally {
632
- srv.stop(true);
633
- }
634
- });
635
- });
636
-
637
- // ---------------------------------------------------------------------------
638
- // startCmd resolution for hub supervision (channel#34)
639
- // ---------------------------------------------------------------------------
640
-
641
- describe("resolveStartCmd (hub-supervisor start command)", () => {
642
- function tmpInstallDir(): string {
643
- return mkdtempSync(join(tmpdir(), "agent-startcmd-"));
644
- }
645
-
646
- test("reads startCmd from <installDir>/.parachute/module.json", () => {
647
- const dir = tmpInstallDir();
648
- try {
649
- mkdirSync(join(dir, ".parachute"), { recursive: true });
650
- writeFileSync(
651
- join(dir, ".parachute", "module.json"),
652
- JSON.stringify({ startCmd: ["parachute-agent"] }),
653
- );
654
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent"]);
655
- } finally {
656
- rmSync(dir, { recursive: true, force: true });
657
- }
658
- });
659
-
660
- test("preserves a multi-arg module.json startCmd verbatim", () => {
661
- const dir = tmpInstallDir();
662
- try {
663
- mkdirSync(join(dir, ".parachute"), { recursive: true });
664
- writeFileSync(
665
- join(dir, ".parachute", "module.json"),
666
- JSON.stringify({ startCmd: ["parachute-agent", "daemon"] }),
667
- );
668
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent", "daemon"]);
669
- } finally {
670
- rmSync(dir, { recursive: true, force: true });
671
- }
672
- });
673
-
674
- test("falls back to the bin name when module.json is absent", () => {
675
- const dir = tmpInstallDir();
676
- try {
677
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent"]);
678
- } finally {
679
- rmSync(dir, { recursive: true, force: true });
680
- }
681
- });
682
-
683
- test("falls back to the bin name when module.json startCmd is missing/empty/non-string", () => {
684
- const dir = tmpInstallDir();
685
- try {
686
- mkdirSync(join(dir, ".parachute"), { recursive: true });
687
- writeFileSync(join(dir, ".parachute", "module.json"), JSON.stringify({ startCmd: [] }));
688
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent"]);
689
- writeFileSync(join(dir, ".parachute", "module.json"), JSON.stringify({ name: "agent" }));
690
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent"]);
691
- writeFileSync(join(dir, ".parachute", "module.json"), JSON.stringify({ startCmd: [123] }));
692
- expect(resolveStartCmd(dir)).toEqual(["parachute-agent"]);
693
- } finally {
694
- rmSync(dir, { recursive: true, force: true });
695
- }
696
- });
697
-
698
- test("the repo's own .parachute/module.json carries a usable startCmd", () => {
699
- // INSTALL_DIR at runtime is the repo root; src/.. is that root in this checkout.
700
- const repoRoot = join(import.meta.dir, "..");
701
- expect(resolveStartCmd(repoRoot)).toEqual(["parachute-agent"]);
702
- });
703
- });
704
-
705
- // ---------------------------------------------------------------------------
706
- // Turn-event sink — the streaming-view fan-out (design build item #1).
707
- // ---------------------------------------------------------------------------
708
-
709
- describe("buildTurnEventSink (streaming-view fan-out)", () => {
710
- test("routes a turn event to ONLY the channel's subscribers, as a 'turn' SSE frame", () => {
711
- const turnEvents = new ClientRegistry();
712
- const engFrames: string[] = [];
713
- const opsFrames: string[] = [];
714
- turnEvents.add("c-eng", { channel: "eng", enqueue: (p) => engFrames.push(p) });
715
- turnEvents.add("c-ops", { channel: "ops", enqueue: (p) => opsFrames.push(p) });
716
-
717
- const sink = buildTurnEventSink(turnEvents);
718
- sink("eng", { kind: "text", text: "hi" });
719
-
720
- // The eng subscriber got it; the ops subscriber did not (channel isolation).
721
- expect(engFrames).toHaveLength(1);
722
- expect(opsFrames).toHaveLength(0);
723
- expect(engFrames[0]).toContain("event: turn");
724
- expect(engFrames[0]).toContain(JSON.stringify({ kind: "text", text: "hi" }));
725
- });
726
-
727
- test("a 0-subscriber channel is a clean no-op (events drop; no throw)", () => {
728
- const turnEvents = new ClientRegistry();
729
- const sink = buildTurnEventSink(turnEvents);
730
- expect(() => sink("ghost", { kind: "done", reply: "x" })).not.toThrow();
731
- });
732
-
733
- test("a dead (throwing) subscriber is dropped, not fatal", () => {
734
- const turnEvents = new ClientRegistry();
735
- turnEvents.add("dead", {
736
- channel: "eng",
737
- enqueue: () => {
738
- throw new Error("stream closed");
739
- },
740
- });
741
- const sink = buildTurnEventSink(turnEvents);
742
- expect(() => sink("eng", { kind: "tool", tool: "Read" })).not.toThrow();
743
- // routeToChannel drops the dead client; a follow-up emit finds no subscribers.
744
- expect(turnEvents.countForChannel("eng")).toBe(0);
745
- });
746
- });