@openparachute/hub 0.5.0 → 0.5.2

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.
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { HUB_SVC, hubPortPath } from "../hub-control.ts";
7
7
  import { hubDbPath, openHubDb } from "../hub-db.ts";
8
- import { findVaultUpstream, hubFetch } from "../hub-server.ts";
8
+ import { findServiceUpstream, findVaultUpstream, hubFetch } from "../hub-server.ts";
9
9
  import { pidPath } from "../process-state.ts";
10
10
  import { type ServiceEntry, writeManifest } from "../services-manifest.ts";
11
11
  import { rotateSigningKey } from "../signing-keys.ts";
@@ -1051,6 +1051,585 @@ describe("hubFetch /vault/<name>/* dynamic proxy (#144)", () => {
1051
1051
  });
1052
1052
  });
1053
1053
 
1054
+ describe("findServiceUpstream (#182)", () => {
1055
+ // Generic longest-prefix match across non-vault services.json entries. Vault
1056
+ // entries are filtered out — vault routing is the SPA-fallback-aware path
1057
+ // through findVaultUpstream / proxyToVault.
1058
+
1059
+ test("matches a non-vault entry by exact path", () => {
1060
+ const services: ServiceEntry[] = [
1061
+ {
1062
+ name: "scribe",
1063
+ port: 1942,
1064
+ paths: ["/scribe"],
1065
+ health: "/scribe/health",
1066
+ version: "0.1.0",
1067
+ },
1068
+ ];
1069
+ const m = findServiceUpstream(services, "/scribe");
1070
+ expect(m?.port).toBe(1942);
1071
+ expect(m?.mount).toBe("/scribe");
1072
+ expect(m?.entry.name).toBe("scribe");
1073
+ });
1074
+
1075
+ test("matches a deeper subpath via prefix", () => {
1076
+ const services: ServiceEntry[] = [
1077
+ {
1078
+ name: "agent",
1079
+ port: 1943,
1080
+ paths: ["/agent"],
1081
+ health: "/agent/api/health",
1082
+ version: "0.1.0",
1083
+ },
1084
+ ];
1085
+ expect(findServiceUpstream(services, "/agent/api/health")?.port).toBe(1943);
1086
+ });
1087
+
1088
+ test("ignores vault entries — those route via findVaultUpstream", () => {
1089
+ const services: ServiceEntry[] = [
1090
+ {
1091
+ name: "parachute-vault",
1092
+ port: 1940,
1093
+ paths: ["/vault/default"],
1094
+ health: "/vault/default/health",
1095
+ version: "0.4.0",
1096
+ },
1097
+ ];
1098
+ expect(findServiceUpstream(services, "/vault/default/health")).toBeUndefined();
1099
+ });
1100
+
1101
+ test("returns undefined when no service claims the path", () => {
1102
+ const services: ServiceEntry[] = [
1103
+ {
1104
+ name: "scribe",
1105
+ port: 1942,
1106
+ paths: ["/scribe"],
1107
+ health: "/scribe/health",
1108
+ version: "0.1.0",
1109
+ },
1110
+ ];
1111
+ expect(findServiceUpstream(services, "/unknown/foo")).toBeUndefined();
1112
+ });
1113
+
1114
+ test("longest-prefix wins when multiple paths could match", () => {
1115
+ // A service registering `/api` and another (older / catch-all) registering
1116
+ // `/` would conflict on every request — longest mount wins so the more
1117
+ // specific one takes precedence.
1118
+ const services: ServiceEntry[] = [
1119
+ { name: "wide", port: 1950, paths: ["/api"], health: "/api/health", version: "0.1.0" },
1120
+ {
1121
+ name: "deeper",
1122
+ port: 1951,
1123
+ paths: ["/api/v2"],
1124
+ health: "/api/v2/health",
1125
+ version: "0.1.0",
1126
+ },
1127
+ ];
1128
+ expect(findServiceUpstream(services, "/api/v2/things")?.port).toBe(1951);
1129
+ expect(findServiceUpstream(services, "/api/v1/things")?.port).toBe(1950);
1130
+ });
1131
+
1132
+ test("does not match a sibling that shares a prefix without a slash boundary", () => {
1133
+ // `/scribe-admin` must NOT match a service mounted at `/scribe`. The
1134
+ // boundary check is `pathname === path || pathname.startsWith(path + '/')`.
1135
+ const services: ServiceEntry[] = [
1136
+ {
1137
+ name: "scribe",
1138
+ port: 1942,
1139
+ paths: ["/scribe"],
1140
+ health: "/scribe/health",
1141
+ version: "0.1.0",
1142
+ },
1143
+ ];
1144
+ expect(findServiceUpstream(services, "/scribe-admin")).toBeUndefined();
1145
+ expect(findServiceUpstream(services, "/scribe-admin/foo")).toBeUndefined();
1146
+ });
1147
+ });
1148
+
1149
+ describe("hubFetch /<svc>/* generic proxy dispatch (#182)", () => {
1150
+ // hub#182: services.json-driven dispatch for non-vault modules. Lets
1151
+ // `parachute install <svc>` reach the on-box hub at hub:1939/<svc>/* with
1152
+ // no per-service codepath. Vault keeps its own routing for the SPA seam.
1153
+
1154
+ function startUpstream(replyTag: string): { port: number; stop: () => void } {
1155
+ const server = Bun.serve({
1156
+ port: 0,
1157
+ hostname: "127.0.0.1",
1158
+ fetch: async (req) => {
1159
+ const u = new URL(req.url);
1160
+ const body = req.body ? await req.text() : "";
1161
+ return new Response(
1162
+ JSON.stringify({
1163
+ tag: replyTag,
1164
+ method: req.method,
1165
+ pathname: u.pathname,
1166
+ search: u.search,
1167
+ authorization: req.headers.get("authorization") ?? "",
1168
+ contentType: req.headers.get("content-type") ?? "",
1169
+ body,
1170
+ }),
1171
+ { status: 200, headers: { "content-type": "application/json" } },
1172
+ );
1173
+ },
1174
+ });
1175
+ return { port: server.port as number, stop: () => server.stop(true) };
1176
+ }
1177
+
1178
+ test("routes /scribe/health to the matching upstream, path preserved", async () => {
1179
+ const h = makeHarness();
1180
+ const upstream = startUpstream("scribe");
1181
+ try {
1182
+ writeManifest(
1183
+ {
1184
+ services: [
1185
+ {
1186
+ name: "scribe",
1187
+ port: upstream.port,
1188
+ paths: ["/scribe"],
1189
+ health: "/scribe/health",
1190
+ version: "0.1.0",
1191
+ },
1192
+ ],
1193
+ },
1194
+ h.manifestPath,
1195
+ );
1196
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1197
+ const res = await fetcher(req("/scribe/health"));
1198
+ expect(res.status).toBe(200);
1199
+ const body = (await res.json()) as { tag: string; pathname: string };
1200
+ expect(body.tag).toBe("scribe");
1201
+ // Path-preservation convention: backend sees the full mount-prefixed
1202
+ // path, matching `serviceProxyTarget` in commands/expose.ts.
1203
+ expect(body.pathname).toBe("/scribe/health");
1204
+ } finally {
1205
+ upstream.stop();
1206
+ h.cleanup();
1207
+ }
1208
+ });
1209
+
1210
+ test("routes /notes/sw.js to the matching upstream", async () => {
1211
+ // Notes is the canonical path-mount case — the PWA shell has to see the
1212
+ // full `/notes/...` path so its service worker registers correctly (the
1213
+ // motivator for the `--mount` strip in notes-serve.ts).
1214
+ const h = makeHarness();
1215
+ const upstream = startUpstream("notes");
1216
+ try {
1217
+ writeManifest(
1218
+ {
1219
+ services: [
1220
+ {
1221
+ name: "notes",
1222
+ port: upstream.port,
1223
+ paths: ["/notes"],
1224
+ health: "/notes/health",
1225
+ version: "0.1.0",
1226
+ },
1227
+ ],
1228
+ },
1229
+ h.manifestPath,
1230
+ );
1231
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1232
+ const res = await fetcher(req("/notes/sw.js"));
1233
+ expect(res.status).toBe(200);
1234
+ const body = (await res.json()) as { tag: string; pathname: string };
1235
+ expect(body.tag).toBe("notes");
1236
+ expect(body.pathname).toBe("/notes/sw.js");
1237
+ } finally {
1238
+ upstream.stop();
1239
+ h.cleanup();
1240
+ }
1241
+ });
1242
+
1243
+ test("routes a deep /agent/api/health to the matching upstream", async () => {
1244
+ // Agent registers `/agent`; deeper paths route by prefix.
1245
+ const h = makeHarness();
1246
+ const upstream = startUpstream("agent");
1247
+ try {
1248
+ writeManifest(
1249
+ {
1250
+ services: [
1251
+ {
1252
+ name: "agent",
1253
+ port: upstream.port,
1254
+ paths: ["/agent"],
1255
+ health: "/agent/api/health",
1256
+ version: "0.1.0",
1257
+ },
1258
+ ],
1259
+ },
1260
+ h.manifestPath,
1261
+ );
1262
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1263
+ const res = await fetcher(req("/agent/api/health?probe=1"));
1264
+ expect(res.status).toBe(200);
1265
+ const body = (await res.json()) as { tag: string; pathname: string; search: string };
1266
+ expect(body.tag).toBe("agent");
1267
+ expect(body.pathname).toBe("/agent/api/health");
1268
+ expect(body.search).toBe("?probe=1");
1269
+ } finally {
1270
+ upstream.stop();
1271
+ h.cleanup();
1272
+ }
1273
+ });
1274
+
1275
+ test("preserves method, multipart body, and Authorization on POSTs", async () => {
1276
+ // Scribe-shaped upload: multipart/form-data with a bearer token. Multipart
1277
+ // is what real scribe clients send; if the proxy strips the boundary or
1278
+ // drops Authorization, scribe rejects the request before transcribing.
1279
+ const h = makeHarness();
1280
+ const upstream = startUpstream("scribe");
1281
+ try {
1282
+ writeManifest(
1283
+ {
1284
+ services: [
1285
+ {
1286
+ name: "scribe",
1287
+ port: upstream.port,
1288
+ paths: ["/scribe"],
1289
+ health: "/scribe/health",
1290
+ version: "0.1.0",
1291
+ },
1292
+ ],
1293
+ },
1294
+ h.manifestPath,
1295
+ );
1296
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1297
+ const form = new FormData();
1298
+ form.append("model", "whisper-1");
1299
+ form.append("file", new Blob([new Uint8Array([1, 2, 3, 4])]), "audio.wav");
1300
+ const res = await fetcher(
1301
+ req("/scribe/v1/audio/transcriptions", {
1302
+ method: "POST",
1303
+ headers: { authorization: "Bearer test-token" },
1304
+ body: form,
1305
+ }),
1306
+ );
1307
+ expect(res.status).toBe(200);
1308
+ const body = (await res.json()) as {
1309
+ method: string;
1310
+ authorization: string;
1311
+ contentType: string;
1312
+ body: string;
1313
+ };
1314
+ expect(body.method).toBe("POST");
1315
+ expect(body.authorization).toBe("Bearer test-token");
1316
+ // Bun's fetch sets the boundary; we just need to confirm the
1317
+ // multipart content-type survived.
1318
+ expect(body.contentType).toMatch(/^multipart\/form-data;\s*boundary=/);
1319
+ // And the body bytes — the boundary marker the upstream echoes back
1320
+ // should contain the form fields we sent.
1321
+ expect(body.body).toContain('name="model"');
1322
+ expect(body.body).toContain("whisper-1");
1323
+ expect(body.body).toContain('name="file"');
1324
+ } finally {
1325
+ upstream.stop();
1326
+ h.cleanup();
1327
+ }
1328
+ });
1329
+
1330
+ test("stripPrefix=true forwards the bare path (mount removed)", async () => {
1331
+ // The scribe-shaped case from real life: scribe's HTTP routes are
1332
+ // `/health`, `/v1/...` — no `/scribe` prefix. When the entry sets
1333
+ // stripPrefix:true the hub strips the mount before forwarding so the
1334
+ // backend sees `/health` rather than `/scribe/health`. Without this,
1335
+ // every proxied scribe request 404s at the backend.
1336
+ const h = makeHarness();
1337
+ const upstream = startUpstream("scribe");
1338
+ try {
1339
+ writeManifest(
1340
+ {
1341
+ services: [
1342
+ {
1343
+ name: "scribe",
1344
+ port: upstream.port,
1345
+ paths: ["/scribe"],
1346
+ health: "/scribe/health",
1347
+ version: "0.1.0",
1348
+ stripPrefix: true,
1349
+ },
1350
+ ],
1351
+ },
1352
+ h.manifestPath,
1353
+ );
1354
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1355
+ const res = await fetcher(req("/scribe/v1/audio/transcriptions?model=whisper-1"));
1356
+ expect(res.status).toBe(200);
1357
+ const body = (await res.json()) as { tag: string; pathname: string; search: string };
1358
+ expect(body.tag).toBe("scribe");
1359
+ // Backend sees the bare path — `/scribe` is stripped.
1360
+ expect(body.pathname).toBe("/v1/audio/transcriptions");
1361
+ // Query string is always preserved verbatim regardless of stripPrefix.
1362
+ expect(body.search).toBe("?model=whisper-1");
1363
+ } finally {
1364
+ upstream.stop();
1365
+ h.cleanup();
1366
+ }
1367
+ });
1368
+
1369
+ test("stripPrefix=true: request to bare mount becomes `/`", async () => {
1370
+ // Edge case: pathname === mount. Slicing yields the empty string; the
1371
+ // proxy normalizes to `/` so the backend sees a valid path.
1372
+ const h = makeHarness();
1373
+ const upstream = startUpstream("scribe");
1374
+ try {
1375
+ writeManifest(
1376
+ {
1377
+ services: [
1378
+ {
1379
+ name: "scribe",
1380
+ port: upstream.port,
1381
+ paths: ["/scribe"],
1382
+ health: "/health",
1383
+ version: "0.1.0",
1384
+ stripPrefix: true,
1385
+ },
1386
+ ],
1387
+ },
1388
+ h.manifestPath,
1389
+ );
1390
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1391
+ const res = await fetcher(req("/scribe"));
1392
+ expect(res.status).toBe(200);
1393
+ const body = (await res.json()) as { pathname: string };
1394
+ expect(body.pathname).toBe("/");
1395
+ } finally {
1396
+ upstream.stop();
1397
+ h.cleanup();
1398
+ }
1399
+ });
1400
+
1401
+ test("stripPrefix absent (default false) preserves the prefix — no behavior change for existing entries", async () => {
1402
+ // Migration safety: a services.json entry written before stripPrefix
1403
+ // existed (e.g. notes / agent rows already on disk) must continue to
1404
+ // forward the full path. The /notes/sw.js test above already exercises
1405
+ // this in the happy case; this test makes the absence-of-flag → keep-
1406
+ // prefix contract explicit.
1407
+ const h = makeHarness();
1408
+ const upstream = startUpstream("notes");
1409
+ try {
1410
+ writeManifest(
1411
+ {
1412
+ services: [
1413
+ {
1414
+ name: "notes",
1415
+ port: upstream.port,
1416
+ paths: ["/notes"],
1417
+ health: "/notes/health",
1418
+ version: "0.1.0",
1419
+ // stripPrefix intentionally omitted — must default to false.
1420
+ },
1421
+ ],
1422
+ },
1423
+ h.manifestPath,
1424
+ );
1425
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1426
+ const res = await fetcher(req("/notes/health"));
1427
+ expect(res.status).toBe(200);
1428
+ const body = (await res.json()) as { pathname: string };
1429
+ expect(body.pathname).toBe("/notes/health");
1430
+ } finally {
1431
+ upstream.stop();
1432
+ h.cleanup();
1433
+ }
1434
+ });
1435
+
1436
+ test("stripPrefix=false explicitly preserves the prefix", async () => {
1437
+ // The opposite explicit-declaration of the previous test: an operator
1438
+ // who writes `stripPrefix: false` in services.json gets the same
1439
+ // keep-prefix behavior as omitting the field. Confirms validator round-
1440
+ // tripping doesn't lose the explicit-false (separate from the absent
1441
+ // case which is checked above).
1442
+ const h = makeHarness();
1443
+ const upstream = startUpstream("notes");
1444
+ try {
1445
+ writeManifest(
1446
+ {
1447
+ services: [
1448
+ {
1449
+ name: "notes",
1450
+ port: upstream.port,
1451
+ paths: ["/notes"],
1452
+ health: "/notes/health",
1453
+ version: "0.1.0",
1454
+ stripPrefix: false,
1455
+ },
1456
+ ],
1457
+ },
1458
+ h.manifestPath,
1459
+ );
1460
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1461
+ const res = await fetcher(req("/notes/sw.js"));
1462
+ expect(res.status).toBe(200);
1463
+ const body = (await res.json()) as { pathname: string };
1464
+ expect(body.pathname).toBe("/notes/sw.js");
1465
+ } finally {
1466
+ upstream.stop();
1467
+ h.cleanup();
1468
+ }
1469
+ });
1470
+
1471
+ test("unknown /<svc>/* path returns 404", async () => {
1472
+ const h = makeHarness();
1473
+ const upstream = startUpstream("scribe");
1474
+ try {
1475
+ writeManifest(
1476
+ {
1477
+ services: [
1478
+ {
1479
+ name: "scribe",
1480
+ port: upstream.port,
1481
+ paths: ["/scribe"],
1482
+ health: "/scribe/health",
1483
+ version: "0.1.0",
1484
+ },
1485
+ ],
1486
+ },
1487
+ h.manifestPath,
1488
+ );
1489
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1490
+ const res = await fetcher(req("/notinstalled/foo"));
1491
+ expect(res.status).toBe(404);
1492
+ } finally {
1493
+ upstream.stop();
1494
+ h.cleanup();
1495
+ }
1496
+ });
1497
+
1498
+ test("returns 502 when the matching upstream is unreachable", async () => {
1499
+ // Service is in services.json but the port has nothing listening — same
1500
+ // shape as the vault-unreachable test, label is the entry's `name`.
1501
+ const h = makeHarness();
1502
+ try {
1503
+ writeManifest(
1504
+ {
1505
+ services: [
1506
+ {
1507
+ name: "scribe",
1508
+ port: await pickClosedPort(),
1509
+ paths: ["/scribe"],
1510
+ health: "/scribe/health",
1511
+ version: "0.1.0",
1512
+ },
1513
+ ],
1514
+ },
1515
+ h.manifestPath,
1516
+ );
1517
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1518
+ const res = await fetcher(req("/scribe/health"));
1519
+ expect(res.status).toBe(502);
1520
+ const body = (await res.json()) as { error: string };
1521
+ expect(body.error).toContain("scribe upstream unreachable");
1522
+ } finally {
1523
+ h.cleanup();
1524
+ }
1525
+ });
1526
+
1527
+ test("/oauth/authorize is hub-handled, never reaches service dispatch", async () => {
1528
+ // Even if a (misbehaving) service registers `/oauth`, the hub's own
1529
+ // /oauth/* handlers run first by virtue of dispatch ordering. We don't
1530
+ // need an explicit denylist — ordering enforces it.
1531
+ const h = makeHarness();
1532
+ const upstream = startUpstream("malicious");
1533
+ try {
1534
+ writeManifest(
1535
+ {
1536
+ services: [
1537
+ {
1538
+ name: "malicious",
1539
+ port: upstream.port,
1540
+ paths: ["/oauth"],
1541
+ health: "/oauth/health",
1542
+ version: "0.0.1",
1543
+ },
1544
+ ],
1545
+ },
1546
+ h.manifestPath,
1547
+ );
1548
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1549
+ const res = await fetcher(req("/oauth/authorize"));
1550
+ // Hub's own /oauth/authorize handler responds (likely a redirect or
1551
+ // error page rendering) — we just need to verify the upstream was NOT
1552
+ // reached, i.e. `tag: "malicious"` is not in the body.
1553
+ const text = await res.text();
1554
+ expect(text).not.toContain('"tag":"malicious"');
1555
+ } finally {
1556
+ upstream.stop();
1557
+ h.cleanup();
1558
+ }
1559
+ });
1560
+
1561
+ test("/.well-known/parachute.json is hub-handled, never reaches service dispatch", async () => {
1562
+ const h = makeHarness();
1563
+ const upstream = startUpstream("malicious");
1564
+ try {
1565
+ writeManifest(
1566
+ {
1567
+ services: [
1568
+ {
1569
+ name: "malicious",
1570
+ port: upstream.port,
1571
+ paths: ["/.well-known"],
1572
+ health: "/.well-known/health",
1573
+ version: "0.0.1",
1574
+ },
1575
+ ],
1576
+ },
1577
+ h.manifestPath,
1578
+ );
1579
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1580
+ const res = await fetcher(req("/.well-known/parachute.json"));
1581
+ expect(res.status).toBe(200);
1582
+ // Hub serves the well-known doc as JSON — its body has `vaults`,
1583
+ // `services`, etc., not the upstream's `tag` echo.
1584
+ const text = await res.text();
1585
+ expect(text).not.toContain('"tag":"malicious"');
1586
+ } finally {
1587
+ upstream.stop();
1588
+ h.cleanup();
1589
+ }
1590
+ });
1591
+
1592
+ test("vault entries are NOT routed via the generic dispatch (regression for #144)", async () => {
1593
+ // Reach hubFetch with a vault entry but a request shape that the vault
1594
+ // block won't match (e.g. no leading `/vault/`). The generic dispatch
1595
+ // must skip vault entries — confirming via findServiceUpstream-level
1596
+ // unit test isn't enough, we want the integration to stay coherent.
1597
+ const h = makeHarness();
1598
+ const upstream = startUpstream("vault-default");
1599
+ try {
1600
+ writeManifest(
1601
+ {
1602
+ services: [
1603
+ {
1604
+ name: "parachute-vault",
1605
+ port: upstream.port,
1606
+ paths: ["/vault/default"],
1607
+ health: "/vault/default/health",
1608
+ version: "0.4.0",
1609
+ },
1610
+ ],
1611
+ },
1612
+ h.manifestPath,
1613
+ );
1614
+ const fetcher = hubFetch(h.dir, { manifestPath: h.manifestPath });
1615
+ // /vault/default/health goes through the vault-specific block and
1616
+ // proxies (still works — that's the regression check).
1617
+ const vaultRes = await fetcher(req("/vault/default/health"));
1618
+ expect(vaultRes.status).toBe(200);
1619
+ // /vault/default by itself is the SPA single-segment seam — it does
1620
+ // proxy via proxyToVault per the existing behavior.
1621
+ // The point of this test is the generic dispatch CANNOT mistakenly
1622
+ // match a vault entry. Verify by writing a request that's not under
1623
+ // /vault/* and confirming no fallthrough to the vault upstream.
1624
+ const elsewhere = await fetcher(req("/totally/not/a/vault"));
1625
+ expect(elsewhere.status).toBe(404);
1626
+ } finally {
1627
+ upstream.stop();
1628
+ h.cleanup();
1629
+ }
1630
+ });
1631
+ });
1632
+
1054
1633
  /** Find a port that no one is listening on by binding briefly and releasing. */
1055
1634
  async function pickClosedPort(): Promise<number> {
1056
1635
  const s = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("x") });