hmcp-web 0.0.1 → 0.2.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 (94) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +49 -2
  3. package/THIRD-PARTY-NOTICES.md +110 -0
  4. package/bin/hmcp-web.js +20 -0
  5. package/dist/api.d.ts +22 -0
  6. package/dist/api.js +1458 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +40 -0
  9. package/dist/contracts/onboarding.d.ts +233 -0
  10. package/dist/contracts/onboarding.js +1 -0
  11. package/dist/http.d.ts +72 -0
  12. package/dist/http.js +319 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.js +7 -0
  15. package/dist/model/app-servers.d.ts +85 -0
  16. package/dist/model/app-servers.js +109 -0
  17. package/dist/model/console-settings.d.ts +37 -0
  18. package/dist/model/console-settings.js +74 -0
  19. package/dist/model/doctor.d.ts +68 -0
  20. package/dist/model/doctor.js +254 -0
  21. package/dist/model/fs-browse.d.ts +9 -0
  22. package/dist/model/fs-browse.js +184 -0
  23. package/dist/model/gateway-config.d.ts +287 -0
  24. package/dist/model/gateway-config.js +760 -0
  25. package/dist/model/import-record.d.ts +80 -0
  26. package/dist/model/import-record.js +179 -0
  27. package/dist/model/metrics.d.ts +65 -0
  28. package/dist/model/metrics.js +213 -0
  29. package/dist/model/oauth-flows.d.ts +60 -0
  30. package/dist/model/oauth-flows.js +79 -0
  31. package/dist/model/pipeline.d.ts +58 -0
  32. package/dist/model/pipeline.js +84 -0
  33. package/dist/model/probe.d.ts +155 -0
  34. package/dist/model/probe.js +385 -0
  35. package/dist/model/process.d.ts +100 -0
  36. package/dist/model/process.js +278 -0
  37. package/dist/model/protection.d.ts +378 -0
  38. package/dist/model/protection.js +470 -0
  39. package/dist/model/registry-cache.d.ts +59 -0
  40. package/dist/model/registry-cache.js +238 -0
  41. package/dist/model/scan.d.ts +48 -0
  42. package/dist/model/scan.js +59 -0
  43. package/dist/model/server.d.ts +127 -0
  44. package/dist/model/server.js +243 -0
  45. package/dist/model/tools.d.ts +61 -0
  46. package/dist/model/tools.js +72 -0
  47. package/dist/routes/catalog.d.ts +8 -0
  48. package/dist/routes/catalog.js +47 -0
  49. package/dist/routes/connect-import.d.ts +9 -0
  50. package/dist/routes/connect-import.js +594 -0
  51. package/dist/routes/connect.d.ts +50 -0
  52. package/dist/routes/connect.js +691 -0
  53. package/dist/routes/github.d.ts +97 -0
  54. package/dist/routes/github.js +587 -0
  55. package/dist/routes/guard.d.ts +3 -0
  56. package/dist/routes/guard.js +166 -0
  57. package/dist/routes/oauth.d.ts +55 -0
  58. package/dist/routes/oauth.js +406 -0
  59. package/dist/routes/policy.d.ts +34 -0
  60. package/dist/routes/policy.js +513 -0
  61. package/dist/routes/runtime.d.ts +12 -0
  62. package/dist/routes/runtime.js +921 -0
  63. package/dist/routes/servers-add.d.ts +32 -0
  64. package/dist/routes/servers-add.js +1091 -0
  65. package/dist/routes/system.d.ts +4 -0
  66. package/dist/routes/system.js +13 -0
  67. package/dist/start.d.ts +56 -0
  68. package/dist/start.js +164 -0
  69. package/dist-ui/assets/Activity-CZ78RyRO.js +1 -0
  70. package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
  71. package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
  72. package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
  73. package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
  74. package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
  75. package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
  76. package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
  77. package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
  78. package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
  79. package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
  80. package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
  81. package/dist-ui/assets/index-DttDjRpu.js +16 -0
  82. package/dist-ui/assets/index-QeJyD5z2.css +2 -0
  83. package/dist-ui/assets/kit-DRVm92_t.js +4 -0
  84. package/dist-ui/brand/logo-256.png +0 -0
  85. package/dist-ui/brand/logo-512.png +0 -0
  86. package/dist-ui/brand/logo.svg +6 -0
  87. package/dist-ui/brand/mark.svg +5 -0
  88. package/dist-ui/fonts/OFL.txt +99 -0
  89. package/dist-ui/fonts/README.md +21 -0
  90. package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
  91. package/dist-ui/fonts/manrope-latin.woff2 +0 -0
  92. package/dist-ui/index.html +51 -0
  93. package/package.json +69 -6
  94. package/bin/notice.js +0 -7
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The enforcement pipeline, in the order it actually runs.
3
+ *
4
+ * This is the one part of the protection view that is written ahead of time
5
+ * rather than derived, because it describes the runtime's code and not the
6
+ * user's configuration. Each step carries the file and lines it corresponds to
7
+ * so it can be checked against the source.
8
+ *
9
+ * KEEP IN SYNC with `packages/runtime/src/enforce.ts`, `request.ts`, and
10
+ * `packages/core/src/egress.ts`. If you change the order enforcement happens
11
+ * in, change it here in the same commit.
12
+ */
13
+ export declare const ENFORCEMENT_PIPELINE: readonly [{
14
+ readonly step: 1;
15
+ readonly title: "Tenant resolved once, at startup";
16
+ readonly detail: string;
17
+ readonly source: "runtime/src/server.ts:78";
18
+ }, {
19
+ readonly step: 2;
20
+ readonly title: "Arguments validated against a closed schema";
21
+ readonly detail: string;
22
+ readonly source: "runtime/src/server.ts:131-137";
23
+ }, {
24
+ readonly step: 3;
25
+ readonly title: "Pagination ceiling applied before anything is recorded";
26
+ readonly detail: string;
27
+ readonly source: "runtime/src/request.ts:164-174";
28
+ }, {
29
+ readonly step: 4;
30
+ readonly title: "Policy decides, and the decision is pure";
31
+ readonly detail: string;
32
+ readonly source: "core/src/decide.ts:133";
33
+ }, {
34
+ readonly step: 5;
35
+ readonly title: "A refusal never reaches the upstream";
36
+ readonly detail: string;
37
+ readonly source: "runtime/src/enforce.ts:88-103";
38
+ }, {
39
+ readonly step: 6;
40
+ readonly title: "Approvals are bound to the exact arguments";
41
+ readonly detail: string;
42
+ readonly source: "core/src/approvals.ts:256";
43
+ }, {
44
+ readonly step: 7;
45
+ readonly title: "Tenant injected last, after the agent's arguments are placed";
46
+ readonly detail: string;
47
+ readonly source: "runtime/src/request.ts:63-90";
48
+ }, {
49
+ readonly step: 8;
50
+ readonly title: "Egress checked, then the resolved addresses pinned";
51
+ readonly detail: string;
52
+ readonly source: "core/src/egress.ts:84-140";
53
+ }, {
54
+ readonly step: 9;
55
+ readonly title: "The outcome is recorded either way";
56
+ readonly detail: string;
57
+ readonly source: "runtime/src/enforce.ts:137-162";
58
+ }];
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The enforcement pipeline, in the order it actually runs.
3
+ *
4
+ * This is the one part of the protection view that is written ahead of time
5
+ * rather than derived, because it describes the runtime's code and not the
6
+ * user's configuration. Each step carries the file and lines it corresponds to
7
+ * so it can be checked against the source.
8
+ *
9
+ * KEEP IN SYNC with `packages/runtime/src/enforce.ts`, `request.ts`, and
10
+ * `packages/core/src/egress.ts`. If you change the order enforcement happens
11
+ * in, change it here in the same commit.
12
+ */
13
+ export const ENFORCEMENT_PIPELINE = [
14
+ {
15
+ step: 1,
16
+ title: "Tenant resolved once, at startup",
17
+ detail: "The tenant value is read from the credential when the server boots, not per call. A required " +
18
+ "tenant that cannot be resolved stops the server from starting at all, rather than failing " +
19
+ "later on a call that looked fine.",
20
+ source: "runtime/src/server.ts:78"
21
+ },
22
+ {
23
+ step: 2,
24
+ title: "Arguments validated against a closed schema",
25
+ detail: "The MCP SDK checks arguments against the tool's schema, which declares additionalProperties: " +
26
+ "false. An argument the schema does not name is rejected with an error rather than quietly " +
27
+ "stripped, so an attempt to smuggle a tenant id in is visible instead of silent.",
28
+ source: "runtime/src/server.ts:131-137"
29
+ },
30
+ {
31
+ step: 3,
32
+ title: "Pagination ceiling applied before anything is recorded",
33
+ detail: "A missing page-size argument is filled in with the server's ceiling, so no call is unbounded " +
34
+ "and the arguments written to the audit log are the ones that will actually be used.",
35
+ source: "runtime/src/request.ts:164-174"
36
+ },
37
+ {
38
+ step: 4,
39
+ title: "Policy decides, and the decision is pure",
40
+ detail: "decide() runs in this order: tenant integrity, then unclassified handling, then the first " +
41
+ "matching rule with its argument bounds checked before its decision is honoured, then the " +
42
+ "posture. It is synchronous and touches no network, so enforcement can never depend on a " +
43
+ "service being reachable.",
44
+ source: "core/src/decide.ts:133"
45
+ },
46
+ {
47
+ step: 5,
48
+ title: "A refusal never reaches the upstream",
49
+ detail: "On a deny the call is recorded and returned as an error. The upstream request is not built " +
50
+ "and no credential is read, so a refused call cannot have a side effect.",
51
+ source: "runtime/src/enforce.ts:88-103"
52
+ },
53
+ {
54
+ step: 6,
55
+ title: "Approvals are bound to the exact arguments",
56
+ detail: "A grant commits to sha256(tool + canonical arguments), so an approval for one set of " +
57
+ "arguments cannot release another. A standing grant is checked here too, and is bounded by " +
58
+ "its argument constraints, its expiry and its use cap.",
59
+ source: "core/src/approvals.ts:256"
60
+ },
61
+ {
62
+ step: 7,
63
+ title: "Tenant injected last, after the agent's arguments are placed",
64
+ detail: "Arguments are written into the request first and the tenant value after, so no argument can " +
65
+ "overwrite it. Path placeholders are percent-encoded, so a value cannot escape its segment.",
66
+ source: "runtime/src/request.ts:63-90"
67
+ },
68
+ {
69
+ step: 8,
70
+ title: "Egress checked, then the resolved addresses pinned",
71
+ detail: "Scheme, plaintext HTTP, credentials in the URL, method, IP literals and the host allowlist are " +
72
+ "checked first. Then every DNS answer is validated against private, loopback and link-local " +
73
+ "space and the addresses are pinned for the connection, which closes the rebinding window. " +
74
+ "Redirects are re-validated per hop rather than followed.",
75
+ source: "core/src/egress.ts:84-140"
76
+ },
77
+ {
78
+ step: 9,
79
+ title: "The outcome is recorded either way",
80
+ detail: "Completed, denied, held for approval or errored, one hash-chained record is appended with the " +
81
+ "arguments redacted and hashed. An edited, removed or reordered record is detectable.",
82
+ source: "runtime/src/enforce.ts:137-162"
83
+ }
84
+ ];
@@ -0,0 +1,155 @@
1
+ import { SecretStore, type Policy } from "hmcp-core";
2
+ import { type FetchLike, type PackRuleOut, type DraftServer, type FieldValues, type MaterializedDraft, type ProbeOutcome, type Upstream } from "hmcp-gateway";
3
+ /**
4
+ * "Test it": the machinery behind POST /test-server, and what install reads
5
+ * back from it.
6
+ *
7
+ * A test runs the real server, with the real keys, before anything is saved.
8
+ * So nothing it does may touch the files a saved server lives in:
9
+ *
10
+ * - keys typed into the form go to a scratch locked-keys file in a fresh
11
+ * private temp folder, deleted when the test ends -- never the real one;
12
+ * - the policy is a copy in memory, with the server's address allowed only
13
+ * for the test;
14
+ * - what install needs afterwards (including the typed keys) is kept in this
15
+ * process's memory for 15 minutes under a random id, and nowhere else.
16
+ */
17
+ export declare const PROBE_TTL_MS: number;
18
+ export declare const PROBE_TIMEOUT_MS = 20000;
19
+ export declare const MAX_CONCURRENT_PROBES = 2;
20
+ export interface CachedProbe {
21
+ readonly probeId: string;
22
+ /** The gateway it was tested against, or null when none existed yet. */
23
+ readonly gatewayId: string | null;
24
+ readonly draft: DraftServer;
25
+ /** As typed, secret values included. Memory only; dropped on install or expiry. */
26
+ readonly values: FieldValues;
27
+ readonly materialized: MaterializedDraft;
28
+ readonly outcome: ProbeOutcome;
29
+ /** The server this test sets up again, by name (install puts it in that one's place). */
30
+ readonly replacing?: string;
31
+ /**
32
+ * Locked keys this setup gives a new value in place: a key the server being
33
+ * set up again already had, used by no other server. Install overwrites
34
+ * them under the same name rather than saving a second key and leaving
35
+ * the turned-down one behind (UT5 round 4).
36
+ */
37
+ readonly replacesSecrets?: readonly string[];
38
+ readonly expiresAt: number;
39
+ }
40
+ /**
41
+ * At most this many test results are kept. Each holds what was typed (keys
42
+ * included), so a page clicking Test it in a loop must not grow memory for
43
+ * 15 minutes; the oldest goes first.
44
+ */
45
+ export declare const MAX_CACHED_PROBES = 50;
46
+ export declare function rememberProbe(entry: Omit<CachedProbe, "probeId" | "expiresAt">, now?: number): CachedProbe;
47
+ export declare function recallProbe(probeId: string, now?: number): CachedProbe | undefined;
48
+ export declare function forgetProbe(probeId: string): void;
49
+ /** For tests. */
50
+ export declare function clearProbes(): void;
51
+ /**
52
+ * At most two tests at once: each starts a real program or opens a real
53
+ * connection, and a page that is clicked repeatedly should not start a dozen.
54
+ * A third is refused in plain words rather than queued behind a 20s wait the
55
+ * person cannot see.
56
+ */
57
+ export declare function withProbeSlot<T>(fn: () => Promise<T>): Promise<T>;
58
+ /**
59
+ * A locked-keys file for one test: the keys just typed, plus copies of the
60
+ * existing keys the server refers to. In a fresh temp folder (0700 from
61
+ * mkdtemp) that `dispose` deletes.
62
+ */
63
+ export declare function scratchSecretStore(materialized: MaterializedDraft, real: SecretStore): {
64
+ store: SecretStore;
65
+ dispose: () => void;
66
+ };
67
+ /**
68
+ * What a console killed mid-test (a crash, an out-of-memory kill, a laptop
69
+ * losing power) leaves behind: a scratch locked-keys file holding a typed key,
70
+ * and the server it was testing, still running. Run once when the console
71
+ * starts. Only this user's folders are touched, only when the console that
72
+ * made them is gone (or they are too old to belong to a running test), and a
73
+ * server is stopped only if it is still orphaned and is the very process the
74
+ * test recorded (same start time, so a reused pid is left alone).
75
+ */
76
+ export declare function sweepTestLeftovers(options?: {
77
+ dir?: string;
78
+ now?: number;
79
+ }): {
80
+ removed: string[];
81
+ stopped: number[];
82
+ };
83
+ /**
84
+ * The gateway's policy as the test runs it: its own (or a new gateway's
85
+ * default), with this server's address allowed. In memory only.
86
+ */
87
+ export declare function scratchPolicy(base: Policy, upstream: Upstream, localNetwork: boolean, extraHosts?: readonly string[]): Policy;
88
+ /** How long a stopped test may take to finish stopping before its slot is given back anyway. */
89
+ export declare const PROBE_STOP_GRACE_MS = 20000;
90
+ /**
91
+ * Runs `probeUpstream` (workstream F) with the limit and a hard stop a little
92
+ * after its own timeout, and turns a throw into a failed outcome with a
93
+ * problem code -- a test that crashes is still an answer for the page.
94
+ *
95
+ * The hard stop stops the test, not just the wait for it: it aborts the probe,
96
+ * which closes the gateway it built and so the server it started, and then
97
+ * waits for the probe to finish stopping. Until then this has not returned,
98
+ * so the caller still holds the test's slot and its scratch locked-keys file;
99
+ * a server left running in the background would be a third test the limit of
100
+ * two cannot see, holding keys in a file about to be deleted. If stopping
101
+ * itself hangs, the slot is given back after `PROBE_STOP_GRACE_MS`.
102
+ */
103
+ export declare function runProbe(spec: Upstream, options: {
104
+ policy: Policy;
105
+ secrets: SecretStore;
106
+ cwd: string;
107
+ packId?: string;
108
+ within?: string[];
109
+ /** Our own catalog's harmless first call (see probeUpstream). */
110
+ checkCall?: {
111
+ tool: string;
112
+ args: Record<string, unknown>;
113
+ };
114
+ /** Tests only: the probe's own limit and the hard stop, in place of the defaults. */
115
+ timeoutMs?: number;
116
+ hardStopMs?: number;
117
+ }): Promise<ProbeOutcome>;
118
+ /**
119
+ * Removes every typed key from something about to be sent to the browser.
120
+ *
121
+ * Belt and braces: the probe already keeps secrets out of what it reports,
122
+ * but a server that prints its own key in an error message would otherwise
123
+ * put it on the page. Values shorter than 4 characters are left alone; they
124
+ * would match ordinary text and are not keys anyone types.
125
+ */
126
+ export declare function scrubSecrets<T>(value: T, secrets: readonly string[]): T;
127
+ /**
128
+ * Rule packs, from the gateway package: the same loader and applier Test it's
129
+ * preview (probeUpstream) uses, so what is saved is what was shown.
130
+ */
131
+ export type PackRuleShape = PackRuleOut;
132
+ export interface PackRules {
133
+ readonly label: string;
134
+ readonly rules: readonly PackRuleShape[];
135
+ readonly skippedBounds: readonly string[];
136
+ }
137
+ /** The pack's rules for the tools the test actually saw, or null when there is no such pack. */
138
+ export declare function packRulesFor(args: {
139
+ packId: string | undefined;
140
+ upstreamName: string;
141
+ namespace: boolean;
142
+ toolNames: readonly string[];
143
+ within: readonly string[] | undefined;
144
+ }): Promise<PackRules | null>;
145
+ /**
146
+ * Whether an http server that refused the test offers a sign-in.
147
+ *
148
+ * The public list and a pasted address say nothing about sign-in, so a server
149
+ * like Notion is first tried without one and answers 401. Asking its
150
+ * well-known addresses (OAuth discovery, through a guard limited to the hosts
151
+ * it names) tells "needs a key we do not have" from "sign in instead". A
152
+ * server that does not answer within a few seconds is taken as no, and so is
153
+ * one whose sign-in can't register this console by itself (UT2: GitHub).
154
+ */
155
+ export declare function offersSignIn(url: string, fetchFn: FetchLike, timeoutMs?: number): Promise<boolean>;
@@ -0,0 +1,385 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { SecretStore, isSecretRef } from "hmcp-core";
7
+ import { applyPack, classifyUpstreamError, discover, loadPacks, probeUpstream } from "hmcp-gateway";
8
+ import { HttpError } from "../http.js";
9
+ import { egressChangesFor } from "./gateway-config.js";
10
+ /**
11
+ * "Test it": the machinery behind POST /test-server, and what install reads
12
+ * back from it.
13
+ *
14
+ * A test runs the real server, with the real keys, before anything is saved.
15
+ * So nothing it does may touch the files a saved server lives in:
16
+ *
17
+ * - keys typed into the form go to a scratch locked-keys file in a fresh
18
+ * private temp folder, deleted when the test ends -- never the real one;
19
+ * - the policy is a copy in memory, with the server's address allowed only
20
+ * for the test;
21
+ * - what install needs afterwards (including the typed keys) is kept in this
22
+ * process's memory for 15 minutes under a random id, and nowhere else.
23
+ */
24
+ export const PROBE_TTL_MS = 15 * 60_000;
25
+ export const PROBE_TIMEOUT_MS = 20_000;
26
+ export const MAX_CONCURRENT_PROBES = 2;
27
+ const cache = new Map();
28
+ /**
29
+ * At most this many test results are kept. Each holds what was typed (keys
30
+ * included), so a page clicking Test it in a loop must not grow memory for
31
+ * 15 minutes; the oldest goes first.
32
+ */
33
+ export const MAX_CACHED_PROBES = 50;
34
+ function sweep(now) {
35
+ for (const [id, entry] of cache)
36
+ if (entry.expiresAt <= now)
37
+ cache.delete(id);
38
+ }
39
+ export function rememberProbe(entry, now = Date.now()) {
40
+ sweep(now);
41
+ // A Map keeps insertion order, so the first key is the oldest result.
42
+ while (cache.size >= MAX_CACHED_PROBES)
43
+ cache.delete(cache.keys().next().value);
44
+ const probeId = randomBytes(18).toString("base64url");
45
+ const full = { ...entry, probeId, expiresAt: now + PROBE_TTL_MS };
46
+ cache.set(probeId, full);
47
+ return full;
48
+ }
49
+ export function recallProbe(probeId, now = Date.now()) {
50
+ sweep(now);
51
+ return cache.get(probeId);
52
+ }
53
+ export function forgetProbe(probeId) {
54
+ cache.delete(probeId);
55
+ }
56
+ /** For tests. */
57
+ export function clearProbes() {
58
+ cache.clear();
59
+ }
60
+ /* -------------------------------------------------------------- concurrency */
61
+ let running = 0;
62
+ /**
63
+ * At most two tests at once: each starts a real program or opens a real
64
+ * connection, and a page that is clicked repeatedly should not start a dozen.
65
+ * A third is refused in plain words rather than queued behind a 20s wait the
66
+ * person cannot see.
67
+ */
68
+ export async function withProbeSlot(fn) {
69
+ if (running >= MAX_CONCURRENT_PROBES) {
70
+ throw new HttpError(429, "busy", "Two servers are already being tested. Wait for one to finish, then press Test it again.");
71
+ }
72
+ running++;
73
+ try {
74
+ return await fn();
75
+ }
76
+ finally {
77
+ running--;
78
+ }
79
+ }
80
+ /* ------------------------------------------------------------- scratch files */
81
+ /**
82
+ * A locked-keys file for one test: the keys just typed, plus copies of the
83
+ * existing keys the server refers to. In a fresh temp folder (0700 from
84
+ * mkdtemp) that `dispose` deletes.
85
+ */
86
+ export function scratchSecretStore(materialized, real) {
87
+ const dir = mkdtempSync(join(tmpdir(), "hmcp-test-it-"));
88
+ const dispose = () => rmSync(dir, { recursive: true, force: true });
89
+ try {
90
+ writeFileSync(join(dir, "owner"), String(process.pid), { mode: 0o600 });
91
+ const store = new SecretStore(join(dir, "secrets.json"));
92
+ const now = new Date().toISOString();
93
+ const up = materialized.upstream;
94
+ const referenced = new Set([
95
+ ...materialized.secretsReferenced,
96
+ ...Object.values(up.transport === "http" ? up.headers : up.env).filter(isSecretRef).map((r) => r.secret),
97
+ ...(up.transport === "http" && up.oauth ? [up.oauth.secret] : [])
98
+ ]);
99
+ for (const name of referenced) {
100
+ const existing = real.get(name);
101
+ if (existing)
102
+ store.set(name, existing);
103
+ }
104
+ for (const s of materialized.secretsToCreate) {
105
+ const entry = { kind: "value", value: s.value, label: s.label, created_at: now, updated_at: now };
106
+ store.set(s.name, entry);
107
+ }
108
+ return { store, dispose };
109
+ }
110
+ catch (err) {
111
+ dispose();
112
+ throw err;
113
+ }
114
+ }
115
+ /* ------------------------------------------------------------ crash leftovers */
116
+ /** Older than this, a scratch folder is from a test that can't still be running. */
117
+ const LEFTOVER_AGE_MS = PROBE_TIMEOUT_MS * 3;
118
+ const alive = (pid) => {
119
+ try {
120
+ process.kill(pid, 0);
121
+ return true;
122
+ }
123
+ catch (err) {
124
+ return err.code === "EPERM";
125
+ }
126
+ };
127
+ /**
128
+ * What a console killed mid-test (a crash, an out-of-memory kill, a laptop
129
+ * losing power) leaves behind: a scratch locked-keys file holding a typed key,
130
+ * and the server it was testing, still running. Run once when the console
131
+ * starts. Only this user's folders are touched, only when the console that
132
+ * made them is gone (or they are too old to belong to a running test), and a
133
+ * server is stopped only if it is still orphaned and is the very process the
134
+ * test recorded (same start time, so a reused pid is left alone).
135
+ */
136
+ export function sweepTestLeftovers(options = {}) {
137
+ const base = options.dir ?? tmpdir();
138
+ const now = options.now ?? Date.now();
139
+ const removed = [];
140
+ const stopped = [];
141
+ let names;
142
+ try {
143
+ names = readdirSync(base);
144
+ }
145
+ catch {
146
+ return { removed, stopped };
147
+ }
148
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
149
+ for (const name of names) {
150
+ if (!/^hmcp-(test-it|probe)-[A-Za-z0-9]{6}$/.test(name))
151
+ continue;
152
+ const dir = join(base, name);
153
+ try {
154
+ const st = statSync(dir);
155
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid))
156
+ continue;
157
+ let owner = null;
158
+ try {
159
+ owner = Number(readFileSync(join(dir, "owner"), "utf8").trim()) || null;
160
+ }
161
+ catch {
162
+ owner = null;
163
+ }
164
+ const ownerGone = owner !== null && owner !== process.pid && !alive(owner);
165
+ const old = now - st.mtimeMs > LEFTOVER_AGE_MS;
166
+ if (owner === process.pid || !(ownerGone || old))
167
+ continue;
168
+ stopped.push(...stopRecordedChildren(dir));
169
+ rmSync(dir, { recursive: true, force: true });
170
+ removed.push(dir);
171
+ }
172
+ catch {
173
+ /* a folder that vanished or can't be read is not ours to worry about */
174
+ }
175
+ }
176
+ return { removed, stopped };
177
+ }
178
+ function stopRecordedChildren(dir) {
179
+ let text;
180
+ try {
181
+ text = readFileSync(join(dir, "children"), "utf8");
182
+ }
183
+ catch {
184
+ return [];
185
+ }
186
+ // What each recorded process is now: its parent, and whether it is still the same process.
187
+ const now = new Map();
188
+ for (const line of text.split("\n")) {
189
+ const [pidText, lstart] = line.split("\t");
190
+ const pid = Number(pidText);
191
+ if (!pid || !lstart)
192
+ continue;
193
+ try {
194
+ const ps = execFileSync("ps", ["-o", "ppid=,lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2_000, stdio: ["ignore", "pipe", "ignore"] }).trim();
195
+ const m = /^(\d+)\s+(.*)$/.exec(ps);
196
+ if (m && m[2].trim() === lstart.trim())
197
+ now.set(pid, Number(m[1]));
198
+ }
199
+ catch {
200
+ /* gone already */
201
+ }
202
+ }
203
+ /*
204
+ * Stopped: one still orphaned (adopted by init), and any recorded process
205
+ * whose parent is one being stopped -- the real server under a wrapper
206
+ * command (R2 N1, round 3). Nothing whose parent is a live, unrecorded
207
+ * process is touched.
208
+ */
209
+ const stop = new Set();
210
+ for (let grew = true; grew;) {
211
+ grew = false;
212
+ for (const [pid, ppid] of now) {
213
+ if (!stop.has(pid) && (ppid === 1 || stop.has(ppid))) {
214
+ stop.add(pid);
215
+ grew = true;
216
+ }
217
+ }
218
+ }
219
+ const out = [];
220
+ for (const pid of stop) {
221
+ try {
222
+ process.kill(pid, "SIGTERM");
223
+ out.push(pid);
224
+ }
225
+ catch {
226
+ /* gone already */
227
+ }
228
+ }
229
+ return out;
230
+ }
231
+ /**
232
+ * The gateway's policy as the test runs it: its own (or a new gateway's
233
+ * default), with this server's address allowed. In memory only.
234
+ */
235
+ export function scratchPolicy(base, upstream, localNetwork, extraHosts = []) {
236
+ const policy = structuredClone(base);
237
+ const changes = [
238
+ ...egressChangesFor(upstream, { localNetwork }),
239
+ ...extraHosts.map((host) => ({ kind: "egress-allow", host }))
240
+ ];
241
+ for (const change of changes) {
242
+ if (change.kind === "egress-allow" && !policy.egress.allow.includes(change.host))
243
+ policy.egress.allow.push(change.host);
244
+ if (change.kind === "egress-method" && !policy.egress.methods.map((m) => m.toUpperCase()).includes(change.method)) {
245
+ policy.egress.methods.push(change.method);
246
+ }
247
+ if (change.kind === "egress-plain-http")
248
+ policy.egress.allow_http = true;
249
+ if (change.kind === "egress-local-network") {
250
+ policy.egress.block_private_ips = false;
251
+ policy.egress.allow_http = true;
252
+ policy.egress.allow_ip_literals = true;
253
+ }
254
+ }
255
+ return policy;
256
+ }
257
+ /* -------------------------------------------------------------------- probe */
258
+ /** How long a stopped test may take to finish stopping before its slot is given back anyway. */
259
+ export const PROBE_STOP_GRACE_MS = PROBE_TIMEOUT_MS;
260
+ /**
261
+ * Runs `probeUpstream` (workstream F) with the limit and a hard stop a little
262
+ * after its own timeout, and turns a throw into a failed outcome with a
263
+ * problem code -- a test that crashes is still an answer for the page.
264
+ *
265
+ * The hard stop stops the test, not just the wait for it: it aborts the probe,
266
+ * which closes the gateway it built and so the server it started, and then
267
+ * waits for the probe to finish stopping. Until then this has not returned,
268
+ * so the caller still holds the test's slot and its scratch locked-keys file;
269
+ * a server left running in the background would be a third test the limit of
270
+ * two cannot see, holding keys in a file about to be deleted. If stopping
271
+ * itself hangs, the slot is given back after `PROBE_STOP_GRACE_MS`.
272
+ */
273
+ export async function runProbe(spec, options) {
274
+ const started = Date.now();
275
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
276
+ const failed = (err) => ({
277
+ ok: false,
278
+ problem: classifyUpstreamError(err, spec),
279
+ tools: [],
280
+ resources: 0,
281
+ prompts: 0,
282
+ findings: [],
283
+ elapsedMs: Date.now() - started
284
+ });
285
+ const controller = new AbortController();
286
+ let inner;
287
+ try {
288
+ inner = probeUpstream(spec, {
289
+ policy: options.policy,
290
+ secrets: options.secrets,
291
+ cwd: options.cwd,
292
+ timeoutMs,
293
+ signal: controller.signal,
294
+ ...(options.packId ? { packId: options.packId } : {}),
295
+ ...(options.within ? { within: options.within } : {}),
296
+ ...(options.checkCall ? { checkCall: options.checkCall } : {})
297
+ }).then((outcome) => ({ outcome }), (error) => ({ error }));
298
+ }
299
+ catch (err) {
300
+ return failed(err);
301
+ }
302
+ let timer;
303
+ const stop = new Promise((done) => {
304
+ timer = setTimeout(() => done("stop"), options.hardStopMs ?? timeoutMs + 5_000);
305
+ });
306
+ const first = await Promise.race([inner, stop]);
307
+ clearTimeout(timer);
308
+ if (first !== "stop")
309
+ return "outcome" in first ? first.outcome : failed(first.error);
310
+ const timedOut = Object.assign(new Error(`no answer within ${Math.round(timeoutMs / 1000)} seconds`), { code: "ETIMEDOUT" });
311
+ controller.abort(timedOut);
312
+ let grace;
313
+ await Promise.race([
314
+ inner,
315
+ new Promise((done) => {
316
+ grace = setTimeout(done, PROBE_STOP_GRACE_MS);
317
+ })
318
+ ]);
319
+ clearTimeout(grace);
320
+ return failed(timedOut);
321
+ }
322
+ /**
323
+ * Removes every typed key from something about to be sent to the browser.
324
+ *
325
+ * Belt and braces: the probe already keeps secrets out of what it reports,
326
+ * but a server that prints its own key in an error message would otherwise
327
+ * put it on the page. Values shorter than 4 characters are left alone; they
328
+ * would match ordinary text and are not keys anyone types.
329
+ */
330
+ export function scrubSecrets(value, secrets) {
331
+ const needles = secrets.filter((s) => s.length >= 4).sort((a, b) => b.length - a.length);
332
+ if (needles.length === 0)
333
+ return value;
334
+ let text = JSON.stringify(value);
335
+ for (const needle of needles) {
336
+ const encoded = JSON.stringify(needle).slice(1, -1);
337
+ text = text.split(encoded).join("[locked key]");
338
+ }
339
+ return JSON.parse(text);
340
+ }
341
+ /** The pack's rules for the tools the test actually saw, or null when there is no such pack. */
342
+ export async function packRulesFor(args) {
343
+ if (!args.packId)
344
+ return null;
345
+ const pack = loadPacks().find((p) => p.name === args.packId);
346
+ if (!pack)
347
+ return null;
348
+ const advertised = args.toolNames.map((t) => (args.namespace ? `${args.upstreamName}__${t}` : t));
349
+ /*
350
+ * A pack bounds paths to the folders chosen, all of them, exactly as Test
351
+ * it's preview (probeUpstream) bounds them, so what is saved is what was shown.
352
+ */
353
+ const within = args.within;
354
+ const applied = applyPack(pack, { upstreamName: args.upstreamName, namespace: args.namespace, advertised, within });
355
+ return { label: pack.label, rules: applied.rules, skippedBounds: applied.skippedBounds };
356
+ }
357
+ /* -------------------------------------------------------------- sign-in */
358
+ /**
359
+ * Whether an http server that refused the test offers a sign-in.
360
+ *
361
+ * The public list and a pasted address say nothing about sign-in, so a server
362
+ * like Notion is first tried without one and answers 401. Asking its
363
+ * well-known addresses (OAuth discovery, through a guard limited to the hosts
364
+ * it names) tells "needs a key we do not have" from "sign in instead". A
365
+ * server that does not answer within a few seconds is taken as no, and so is
366
+ * one whose sign-in can't register this console by itself (UT2: GitHub).
367
+ */
368
+ export async function offersSignIn(url, fetchFn, timeoutMs = 5_000) {
369
+ let timer;
370
+ try {
371
+ return await Promise.race([
372
+ // Only a sign-in a person can finish: without dynamic registration (github.com) it needs a developer's app ID, a dead end here.
373
+ discover(url, fetchFn).then((d) => !!d.metadata.registration_endpoint),
374
+ new Promise((done) => {
375
+ timer = setTimeout(() => done(false), timeoutMs);
376
+ })
377
+ ]);
378
+ }
379
+ catch {
380
+ return false;
381
+ }
382
+ finally {
383
+ clearTimeout(timer);
384
+ }
385
+ }