hmcp-web 0.0.1 → 0.1.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.
- package/LICENSE +77 -0
- package/README.md +48 -2
- package/THIRD-PARTY-NOTICES.md +110 -0
- package/bin/hmcp-web.js +20 -0
- package/dist/api.d.ts +11 -0
- package/dist/api.js +1404 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/contracts/onboarding.d.ts +233 -0
- package/dist/contracts/onboarding.js +1 -0
- package/dist/http.d.ts +72 -0
- package/dist/http.js +319 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/model/console-settings.d.ts +37 -0
- package/dist/model/console-settings.js +74 -0
- package/dist/model/doctor.d.ts +68 -0
- package/dist/model/doctor.js +254 -0
- package/dist/model/fs-browse.d.ts +9 -0
- package/dist/model/fs-browse.js +184 -0
- package/dist/model/gateway-config.d.ts +287 -0
- package/dist/model/gateway-config.js +760 -0
- package/dist/model/metrics.d.ts +65 -0
- package/dist/model/metrics.js +198 -0
- package/dist/model/oauth-flows.d.ts +60 -0
- package/dist/model/oauth-flows.js +79 -0
- package/dist/model/pipeline.d.ts +58 -0
- package/dist/model/pipeline.js +84 -0
- package/dist/model/probe.d.ts +155 -0
- package/dist/model/probe.js +385 -0
- package/dist/model/process.d.ts +100 -0
- package/dist/model/process.js +278 -0
- package/dist/model/protection.d.ts +378 -0
- package/dist/model/protection.js +470 -0
- package/dist/model/registry-cache.d.ts +59 -0
- package/dist/model/registry-cache.js +238 -0
- package/dist/model/scan.d.ts +48 -0
- package/dist/model/scan.js +59 -0
- package/dist/model/server.d.ts +127 -0
- package/dist/model/server.js +243 -0
- package/dist/model/tools.d.ts +61 -0
- package/dist/model/tools.js +72 -0
- package/dist/routes/catalog.d.ts +8 -0
- package/dist/routes/catalog.js +47 -0
- package/dist/routes/connect.d.ts +14 -0
- package/dist/routes/connect.js +633 -0
- package/dist/routes/oauth.d.ts +55 -0
- package/dist/routes/oauth.js +406 -0
- package/dist/routes/policy.d.ts +34 -0
- package/dist/routes/policy.js +513 -0
- package/dist/routes/runtime.d.ts +6 -0
- package/dist/routes/runtime.js +921 -0
- package/dist/routes/servers-add.d.ts +24 -0
- package/dist/routes/servers-add.js +1091 -0
- package/dist/routes/system.d.ts +4 -0
- package/dist/routes/system.js +13 -0
- package/dist/start.d.ts +56 -0
- package/dist/start.js +164 -0
- package/dist-ui/assets/Activity-BqKGpXMN.js +1 -0
- package/dist-ui/assets/Approvals-Qo7bCcli.js +1 -0
- package/dist-ui/assets/AttachApp-0zRSPgSY.js +5 -0
- package/dist-ui/assets/Connections-CE0JGe8c.js +2 -0
- package/dist-ui/assets/Gallery-B39L2Yma.js +17 -0
- package/dist-ui/assets/PreApprovals-BsIhjMqb.js +1 -0
- package/dist-ui/assets/Protection-DlB09ABa.js +1 -0
- package/dist-ui/assets/Safety-CN-oHO2h.js +1 -0
- package/dist-ui/assets/Settings-BLD7G1Ag.js +1 -0
- package/dist-ui/assets/StartPage-HuZSnmSr.js +1 -0
- package/dist-ui/assets/Suggestions-Dp7pofcs.js +1 -0
- package/dist-ui/assets/Tools-Bfot3bx5.js +4 -0
- package/dist-ui/assets/index-Khp0l1zp.js +16 -0
- package/dist-ui/assets/index-Ylyt4DEr.css +2 -0
- package/dist-ui/assets/kit-DQ7Oxf5n.js +4 -0
- package/dist-ui/brand/logo-256.png +0 -0
- package/dist-ui/brand/logo-512.png +0 -0
- package/dist-ui/brand/logo.svg +6 -0
- package/dist-ui/brand/mark.svg +5 -0
- package/dist-ui/fonts/OFL.txt +99 -0
- package/dist-ui/fonts/README.md +21 -0
- package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
- package/dist-ui/fonts/manrope-latin.woff2 +0 -0
- package/dist-ui/index.html +51 -0
- package/package.json +69 -6
- package/bin/notice.js +0 -7
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gateways this console started, and nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Only HTTP mode is offered. A stdio gateway is spawned by the AI app that
|
|
5
|
+
* talks to it -- its stdin and stdout *are* the conversation -- so one started
|
|
6
|
+
* here would have nobody on the other end. The console can see such a gateway
|
|
7
|
+
* (it announces itself in `runtime_state`) but cannot own it, and says so.
|
|
8
|
+
*
|
|
9
|
+
* One process per registered server. A second start for the same id is a
|
|
10
|
+
* conflict rather than a second process, because two gateways with one
|
|
11
|
+
* component write the same `runtime_state` and inventory rows and a reader can
|
|
12
|
+
* no longer tell which one it is looking at.
|
|
13
|
+
*/
|
|
14
|
+
export type ProcessState = "stopped" | "starting" | "running" | "exited";
|
|
15
|
+
export interface HttpOptions {
|
|
16
|
+
readonly port: number;
|
|
17
|
+
readonly host: "127.0.0.1" | "::1" | "localhost";
|
|
18
|
+
readonly allowHosts: readonly string[];
|
|
19
|
+
readonly allowOrigins: readonly string[];
|
|
20
|
+
/** Require callers to present a bearer token, generated here. */
|
|
21
|
+
readonly requireToken: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface ProcessView {
|
|
24
|
+
readonly managed: boolean;
|
|
25
|
+
readonly state: ProcessState;
|
|
26
|
+
readonly pid: number | null;
|
|
27
|
+
readonly startedAt: number | null;
|
|
28
|
+
readonly exitCode: number | null;
|
|
29
|
+
readonly signal: string | null;
|
|
30
|
+
readonly mode: "http";
|
|
31
|
+
readonly http: {
|
|
32
|
+
host: string;
|
|
33
|
+
port: number;
|
|
34
|
+
url: string | null;
|
|
35
|
+
tokenRequired: boolean;
|
|
36
|
+
} | null;
|
|
37
|
+
readonly log: string[];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The gateway's CLI, resolved through the package the console already depends
|
|
41
|
+
* on. The same file `scripts/demo.mjs` runs, found the way an installed console
|
|
42
|
+
* would find it rather than by a path into this repository.
|
|
43
|
+
*/
|
|
44
|
+
export declare function gatewayCliPath(): string;
|
|
45
|
+
export declare class ProcessManager {
|
|
46
|
+
/** The command to run; replaced in tests. */
|
|
47
|
+
private readonly command;
|
|
48
|
+
private readonly managed;
|
|
49
|
+
/** Every pid started here, so a row one of them left behind is not taken for someone else's. */
|
|
50
|
+
private readonly spawned;
|
|
51
|
+
private exitHookInstalled;
|
|
52
|
+
constructor(
|
|
53
|
+
/** The command to run; replaced in tests. */
|
|
54
|
+
command?: () => {
|
|
55
|
+
file: string;
|
|
56
|
+
args: string[];
|
|
57
|
+
});
|
|
58
|
+
view(id: string): ProcessView;
|
|
59
|
+
/** The pid of a gateway this console owns and that is still alive. */
|
|
60
|
+
livePid(id: string): number | null;
|
|
61
|
+
/** What the last start was asked for, so a restart can repeat it. */
|
|
62
|
+
optionsFor(id: string): HttpOptions | undefined;
|
|
63
|
+
/**
|
|
64
|
+
* Whether a pid announcing itself is someone else's gateway: not one this
|
|
65
|
+
* console started, and actually alive. A gateway's `runtime_state` row stays
|
|
66
|
+
* fresh for a few seconds after it exits, which without this would make a
|
|
67
|
+
* gateway stopped here look like one an AI app is running.
|
|
68
|
+
*/
|
|
69
|
+
isForeign(pid: number): boolean;
|
|
70
|
+
isActive(id: string): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Starts a gateway and waits until it is listening, or has failed.
|
|
73
|
+
*
|
|
74
|
+
* Returns the token once, when one was generated for this start. A restart
|
|
75
|
+
* reuses the previous token and returns null, so the value is shown to the
|
|
76
|
+
* user exactly once.
|
|
77
|
+
*/
|
|
78
|
+
start(id: string, configPath: string, options: HttpOptions, reuseToken?: boolean): Promise<{
|
|
79
|
+
view: ProcessView;
|
|
80
|
+
token: string | null;
|
|
81
|
+
}>;
|
|
82
|
+
/** SIGTERM, then SIGKILL if it has not gone within five seconds. */
|
|
83
|
+
stop(id: string): Promise<ProcessView>;
|
|
84
|
+
/** Forgets a process that is no longer running, e.g. when its server is removed. */
|
|
85
|
+
forget(id: string): void;
|
|
86
|
+
/**
|
|
87
|
+
* Sends every child SIGTERM, synchronously.
|
|
88
|
+
*
|
|
89
|
+
* Synchronous because it runs from an `exit` handler, where nothing
|
|
90
|
+
* asynchronous gets to happen. Each gateway handles SIGTERM by closing its
|
|
91
|
+
* upstreams, so this is enough to leave nothing behind.
|
|
92
|
+
*/
|
|
93
|
+
killAll(): void;
|
|
94
|
+
private installExitHook;
|
|
95
|
+
private push;
|
|
96
|
+
}
|
|
97
|
+
/** The console's one manager. Process-wide, like the store cache. */
|
|
98
|
+
export declare const processes: ProcessManager;
|
|
99
|
+
/** For the console's shutdown path. */
|
|
100
|
+
export declare function stopAllManaged(): void;
|