hmcp-web 0.0.0-stage → 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 +50 -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 +71 -4
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { Command } from "commander";
|
|
4
|
+
import { defaultRegistryPath } from "hmcp-core";
|
|
5
|
+
import { DEFAULT_PORT, StartError, startConsole } from "./start.js";
|
|
6
|
+
// Read from the package's own manifest, which ships next to dist/, so the
|
|
7
|
+
// answer is the version that is installed rather than one written down twice.
|
|
8
|
+
const VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
9
|
+
const program = new Command()
|
|
10
|
+
.name("hmcp-web")
|
|
11
|
+
.description("Local review console: tools, approvals, pre-approvals, protection detail and the audit log.")
|
|
12
|
+
.version(VERSION)
|
|
13
|
+
.option("-p, --port <number>", "port to listen on", String(DEFAULT_PORT))
|
|
14
|
+
.option("-r, --registry <file>", "server registry", defaultRegistryPath())
|
|
15
|
+
.option("--no-open", "do not open the browser")
|
|
16
|
+
.option("--allow-origin <origin...>", "extra origin to accept, for running the Vite dev server")
|
|
17
|
+
.action(async (options) => {
|
|
18
|
+
try {
|
|
19
|
+
await startConsole({
|
|
20
|
+
port: Number(options.port),
|
|
21
|
+
// A port asked for by name is that port or nothing; the default may move along.
|
|
22
|
+
strictPort: program.getOptionValueSource("port") === "cli",
|
|
23
|
+
open: options.open,
|
|
24
|
+
registryPath: options.registry,
|
|
25
|
+
allowOrigins: options.allowOrigin ?? []
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
/*
|
|
30
|
+
* A busy port is the ordinary failure here, and the reader needs one
|
|
31
|
+
* line and the flag that fixes it -- not Node's unhandled-error trace.
|
|
32
|
+
*/
|
|
33
|
+
if (err instanceof StartError) {
|
|
34
|
+
process.stderr.write(`error: ${err.message}\n`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
await program.parseAsync();
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The console API for adding servers, signing in, the machine check and the
|
|
3
|
+
* start page. CONTRACT (phase 0): changed only by the supervisor. The UI keeps
|
|
4
|
+
* a copy of these types in ui/src/api/onboarding.ts (the UI cannot import
|
|
5
|
+
* server code); keep the two identical.
|
|
6
|
+
*
|
|
7
|
+
* Every route is under /api/v1 and needs the console session + CSRF header,
|
|
8
|
+
* like the rest. No response ever carries a secret value.
|
|
9
|
+
*/
|
|
10
|
+
import type { CatalogEntry, DraftServer, FieldValues, ParsedSnippet, ProbeOutcome, RegistryHit, Runtime } from "hmcp-gateway";
|
|
11
|
+
import type { LiveConfigStateRow, SecretSummary, UpstreamLiveState } from "hmcp-core";
|
|
12
|
+
/** GET /api/v1/catalog */
|
|
13
|
+
export interface CatalogResponse {
|
|
14
|
+
entries: CatalogEntry[];
|
|
15
|
+
}
|
|
16
|
+
/** GET /api/v1/catalog/:id/draft?variant= */
|
|
17
|
+
export interface DraftResponse {
|
|
18
|
+
draft: DraftServer;
|
|
19
|
+
}
|
|
20
|
+
/** GET /api/v1/registry/search?q=&cursor= -- 404 code "registry-off" when the setting is off. */
|
|
21
|
+
export interface RegistrySearchResponse {
|
|
22
|
+
hits: RegistryHit[];
|
|
23
|
+
/** When the local copy of the public list was last refreshed, ISO. */
|
|
24
|
+
updatedAt: string | null;
|
|
25
|
+
/** True while the first download is still running; the UI shows "Getting the list...". */
|
|
26
|
+
loading: boolean;
|
|
27
|
+
total: number;
|
|
28
|
+
nextCursor: string | null;
|
|
29
|
+
/** Plain words when the list could not be downloaded. */
|
|
30
|
+
problem?: string;
|
|
31
|
+
}
|
|
32
|
+
/** POST /api/v1/paste { text } */
|
|
33
|
+
export type PasteResponse = ParsedSnippet;
|
|
34
|
+
/** POST /api/v1/test-server */
|
|
35
|
+
export interface TestServerRequest {
|
|
36
|
+
/** The gateway it will join; omitted before the first gateway exists. */
|
|
37
|
+
gatewayId?: string;
|
|
38
|
+
draft: DraftServer;
|
|
39
|
+
values: FieldValues;
|
|
40
|
+
/** Upstream name override. */
|
|
41
|
+
name?: string;
|
|
42
|
+
/**
|
|
43
|
+
* The saved server this one takes the place of, by name: a fix such as
|
|
44
|
+
* "Choose the folder again" sets it up afresh, and saving puts it where the
|
|
45
|
+
* old one was rather than beside it.
|
|
46
|
+
*/
|
|
47
|
+
replacing?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface TestServerResponse {
|
|
50
|
+
/** Pass to install; valid 15 minutes. */
|
|
51
|
+
probeId: string;
|
|
52
|
+
outcome: ProbeOutcome;
|
|
53
|
+
/** The upstream as it will be written (secret fields are references). */
|
|
54
|
+
upstream: unknown;
|
|
55
|
+
/** Hosts the network rules will have to allow. */
|
|
56
|
+
egressHosts: string[];
|
|
57
|
+
/** Field id -> plain problem, when values are invalid (nothing was run). */
|
|
58
|
+
problems: Record<string, string>;
|
|
59
|
+
/**
|
|
60
|
+
* The server refused the test (401) and offers a sign-in (OAuth metadata
|
|
61
|
+
* was found). Send values.__signin to switch the draft to signing in.
|
|
62
|
+
*/
|
|
63
|
+
signInAvailable?: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** POST /api/v1/servers/:id/gateway/install (id "main" creates the default toolbox if needed) */
|
|
66
|
+
export interface InstallRequest {
|
|
67
|
+
probeId: string;
|
|
68
|
+
/** Digests from GET /servers/:id/gateway and its policy; omitted when creating. */
|
|
69
|
+
expected?: {
|
|
70
|
+
gateway: string;
|
|
71
|
+
policy: string;
|
|
72
|
+
};
|
|
73
|
+
acknowledged?: {
|
|
74
|
+
loosens: true;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Only say what saving would loosen, and write nothing: the answer is then
|
|
78
|
+
* { preview: true, loosens: string[] } instead of an InstallResponse.
|
|
79
|
+
*/
|
|
80
|
+
preview?: true;
|
|
81
|
+
}
|
|
82
|
+
export interface InstallResponse {
|
|
83
|
+
gatewayId: string;
|
|
84
|
+
upstreamName: string;
|
|
85
|
+
/** The server's name in plain words, from the draft ("Files on this computer"). */
|
|
86
|
+
displayName?: string;
|
|
87
|
+
/**
|
|
88
|
+
* live: a running gateway picked it up; pending: a gateway is running and has
|
|
89
|
+
* not applied it yet (poll /live); not-running: nothing is running it -- it
|
|
90
|
+
* applies when the AI app next starts the gateway; needs-restart: a running
|
|
91
|
+
* gateway refused to apply it live.
|
|
92
|
+
*/
|
|
93
|
+
apply: "live" | "pending" | "not-running" | "needs-restart";
|
|
94
|
+
digests: {
|
|
95
|
+
gateway: string;
|
|
96
|
+
policy: string;
|
|
97
|
+
};
|
|
98
|
+
/** True when this call created the gateway. */
|
|
99
|
+
created: boolean;
|
|
100
|
+
/** Plain-words lines: "Changes now wait for you", "Added github.com to allowed addresses". */
|
|
101
|
+
summary: string[];
|
|
102
|
+
}
|
|
103
|
+
/** 422 body detail when acknowledgement is needed: { needs: "loosens", loosens: string[] } */
|
|
104
|
+
/** GET /api/v1/servers/:id/live */
|
|
105
|
+
export interface LiveResponse {
|
|
106
|
+
/** Merged across live gateway processes; empty when none is running. */
|
|
107
|
+
upstreams: UpstreamLiveState[];
|
|
108
|
+
processes: Pick<LiveConfigStateRow, "pid" | "config_digest" | "applied_at" | "refusal" | "heartbeat_at">[];
|
|
109
|
+
/** True when a live process has applied the current gateway.yaml. */
|
|
110
|
+
applied: boolean;
|
|
111
|
+
running: boolean;
|
|
112
|
+
}
|
|
113
|
+
/** POST /api/v1/servers/:id/upstreams/:name/retry -> 202 {} */
|
|
114
|
+
/** POST /api/v1/servers/:id/gateway/secrets/move { expectedDigest } */
|
|
115
|
+
export interface MoveSecretsResponse {
|
|
116
|
+
moved: {
|
|
117
|
+
upstream: string;
|
|
118
|
+
key: string;
|
|
119
|
+
secret: string;
|
|
120
|
+
}[];
|
|
121
|
+
digest: string;
|
|
122
|
+
/** Files that still hold the old values (backups). */
|
|
123
|
+
stillIn: string[];
|
|
124
|
+
}
|
|
125
|
+
/** GET /api/v1/secrets */
|
|
126
|
+
export interface SecretsResponse {
|
|
127
|
+
secrets: (SecretSummary & {
|
|
128
|
+
usedBy: {
|
|
129
|
+
gatewayId: string;
|
|
130
|
+
upstream: string;
|
|
131
|
+
}[];
|
|
132
|
+
})[];
|
|
133
|
+
path: string;
|
|
134
|
+
}
|
|
135
|
+
/** POST /api/v1/secrets { name?, label, value } -> { name } ; PUT /secrets/:name { value } ; DELETE /secrets/:name */
|
|
136
|
+
export interface CreateSecretRequest {
|
|
137
|
+
name?: string;
|
|
138
|
+
label: string;
|
|
139
|
+
value: string;
|
|
140
|
+
}
|
|
141
|
+
/** POST /api/v1/oauth/start */
|
|
142
|
+
export interface OAuthStartRequest {
|
|
143
|
+
serverUrl: string;
|
|
144
|
+
/** The locked-key name the sign-in is stored under. */
|
|
145
|
+
secretName: string;
|
|
146
|
+
label?: string;
|
|
147
|
+
/** Advanced fallback when the provider has no dynamic registration. */
|
|
148
|
+
clientId?: string;
|
|
149
|
+
clientSecret?: string;
|
|
150
|
+
}
|
|
151
|
+
export interface OAuthStartResponse {
|
|
152
|
+
/** Open this in a new tab. */
|
|
153
|
+
authorizeUrl: string;
|
|
154
|
+
state: string;
|
|
155
|
+
/** Hosts the gateway will need to reach: the server and the token endpoint. */
|
|
156
|
+
hosts: string[];
|
|
157
|
+
provider: string;
|
|
158
|
+
}
|
|
159
|
+
/** 422 code "no-dynamic-registration" -> the UI asks for an app ID. */
|
|
160
|
+
/** POST /api/v1/oauth/complete { state, code?, error?, error_description? } */
|
|
161
|
+
export interface OAuthCompleteResponse {
|
|
162
|
+
ok: boolean;
|
|
163
|
+
secretName: string;
|
|
164
|
+
/** Plain words when it failed. */
|
|
165
|
+
problem?: string;
|
|
166
|
+
}
|
|
167
|
+
/** GET /api/v1/oauth/flows/:state */
|
|
168
|
+
export interface OAuthFlowResponse {
|
|
169
|
+
status: "waiting" | "done" | "failed" | "expired";
|
|
170
|
+
secretName: string;
|
|
171
|
+
problem?: string;
|
|
172
|
+
}
|
|
173
|
+
export interface RuntimeCheck {
|
|
174
|
+
id: Runtime | "npx" | "uvx";
|
|
175
|
+
found: boolean;
|
|
176
|
+
path: string | null;
|
|
177
|
+
version: string | null;
|
|
178
|
+
/** docker: installed but not running. */
|
|
179
|
+
running?: boolean;
|
|
180
|
+
problem?: string;
|
|
181
|
+
}
|
|
182
|
+
/** GET /api/v1/system/doctor */
|
|
183
|
+
export interface DoctorResponse {
|
|
184
|
+
platform: NodeJS.Platform;
|
|
185
|
+
arch: string;
|
|
186
|
+
checks: RuntimeCheck[];
|
|
187
|
+
/** Folders to put on PATH for AI apps (node, uv, docker...). */
|
|
188
|
+
pathDirs: string[];
|
|
189
|
+
}
|
|
190
|
+
/** GET /api/v1/fs/dirs?path= */
|
|
191
|
+
export interface DirListing {
|
|
192
|
+
path: string;
|
|
193
|
+
parent: string | null;
|
|
194
|
+
dirs: {
|
|
195
|
+
name: string;
|
|
196
|
+
path: string;
|
|
197
|
+
symlinkTo?: string;
|
|
198
|
+
}[];
|
|
199
|
+
truncated: boolean;
|
|
200
|
+
/** Home, Desktop, Documents, Downloads; drive letters on Windows. */
|
|
201
|
+
shortcuts: {
|
|
202
|
+
label: string;
|
|
203
|
+
path: string;
|
|
204
|
+
}[];
|
|
205
|
+
/** Plain words when choosing this folder is risky ("every file you have"). */
|
|
206
|
+
warning?: string;
|
|
207
|
+
}
|
|
208
|
+
/** GET/PUT /api/v1/console/settings */
|
|
209
|
+
export interface ConsoleSettings {
|
|
210
|
+
version: 1;
|
|
211
|
+
onboarding: {
|
|
212
|
+
step: StartStep;
|
|
213
|
+
done: StartStep[];
|
|
214
|
+
dismissed: boolean;
|
|
215
|
+
};
|
|
216
|
+
registry: {
|
|
217
|
+
enabled: boolean;
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
export type StartStep = "welcome" | "computer" | "server" | "app" | "try" | "protect" | "done";
|
|
221
|
+
/** POST /api/v1/connect/attach */
|
|
222
|
+
export interface AttachRequest {
|
|
223
|
+
gatewayId: string;
|
|
224
|
+
scope: string;
|
|
225
|
+
projectDir?: string;
|
|
226
|
+
}
|
|
227
|
+
export interface AttachResponse {
|
|
228
|
+
configPath: string;
|
|
229
|
+
entryName: string;
|
|
230
|
+
backupPath: string;
|
|
231
|
+
alreadyConnected: boolean;
|
|
232
|
+
restartHint: string;
|
|
233
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
import { HttpError, MAX_BODY_BYTES, badRequest, conflict, notFound, unprocessable } from "hmcp-core";
|
|
3
|
+
export { HttpError, MAX_BODY_BYTES, badRequest, conflict, notFound, unprocessable };
|
|
4
|
+
/**
|
|
5
|
+
* The console's HTTP layer.
|
|
6
|
+
*
|
|
7
|
+
* This process can approve a write that an agent was refused, so it is a
|
|
8
|
+
* privileged surface and is treated as one: loopback only, an explicit token,
|
|
9
|
+
* a Host check that closes DNS rebinding against the console itself, and a
|
|
10
|
+
* double-submit token on everything that mutates.
|
|
11
|
+
*/
|
|
12
|
+
export interface RequestContext {
|
|
13
|
+
readonly method: string;
|
|
14
|
+
readonly path: string;
|
|
15
|
+
readonly params: Readonly<Record<string, string>>;
|
|
16
|
+
readonly query: URLSearchParams;
|
|
17
|
+
readonly body: unknown;
|
|
18
|
+
readonly actor: string;
|
|
19
|
+
/**
|
|
20
|
+
* The Host the browser sent, already checked against the console's own
|
|
21
|
+
* names (127.0.0.1, localhost, [::1] on its port). Sign-in needs it: its
|
|
22
|
+
* callback must come back to the host the session cookie belongs to.
|
|
23
|
+
*/
|
|
24
|
+
readonly host?: string;
|
|
25
|
+
}
|
|
26
|
+
export type Handler = (ctx: RequestContext) => unknown | Promise<unknown>;
|
|
27
|
+
export interface Route {
|
|
28
|
+
readonly method: string;
|
|
29
|
+
/** Path segments; a segment starting with ":" captures. */
|
|
30
|
+
readonly pattern: readonly string[];
|
|
31
|
+
readonly handler: Handler;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A handler's result with a status other than 200 (202 for "asked; it
|
|
35
|
+
* happens in the background"). Anything else a handler returns is sent as 200.
|
|
36
|
+
*/
|
|
37
|
+
export declare class Respond {
|
|
38
|
+
readonly status: number;
|
|
39
|
+
readonly body: unknown;
|
|
40
|
+
constructor(status: number, body: unknown);
|
|
41
|
+
}
|
|
42
|
+
export declare const respond: (status: number, body: unknown) => Respond;
|
|
43
|
+
export declare function route(method: string, path: string, handler: Handler): Route;
|
|
44
|
+
/**
|
|
45
|
+
* A token on disk, readable only by its owner.
|
|
46
|
+
*
|
|
47
|
+
* Anyone who can read this file can approve a destructive call, so a
|
|
48
|
+
* group- or world-readable token is treated as a configuration error rather
|
|
49
|
+
* than tolerated.
|
|
50
|
+
*/
|
|
51
|
+
export declare function loadOrCreateToken(path?: string): string;
|
|
52
|
+
/** What GET /api/v1/ping answers, so `hmcp start` can tell its own console from something else on the port. */
|
|
53
|
+
export declare const HEALTH_APP = "hmcp-web";
|
|
54
|
+
/** Not /api/v1/health: that one needs a session, and the UI uses it to tell whether it is signed in. */
|
|
55
|
+
export declare const PING_PATH = "/api/v1/ping";
|
|
56
|
+
/**
|
|
57
|
+
* Which console this is, without saying anything that signs in: a keyed hash
|
|
58
|
+
* of its sign-in token. Two consoles answer with the same id only when they
|
|
59
|
+
* share a home folder (and so a token); \`hmcp start\` and \`npm run demo\` reuse
|
|
60
|
+
* a running console only then, instead of any console on the port (R1).
|
|
61
|
+
*/
|
|
62
|
+
export declare function consoleId(token: string): string;
|
|
63
|
+
export interface ServeOptions {
|
|
64
|
+
readonly routes: readonly Route[];
|
|
65
|
+
readonly token: string;
|
|
66
|
+
readonly uiDir: string;
|
|
67
|
+
readonly port: number;
|
|
68
|
+
readonly actor: string;
|
|
69
|
+
/** Extra origins to accept, for running the Vite dev server. Off by default. */
|
|
70
|
+
readonly allowOrigins?: readonly string[];
|
|
71
|
+
}
|
|
72
|
+
export declare function createConsoleServer(options: ServeOptions): Server;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
3
|
+
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, extname, join, normalize, resolve, sep } from "node:path";
|
|
5
|
+
import { HttpError, MAX_BODY_BYTES, badRequest, constantTimeEquals, expandPath, readBody, conflict, notFound, unprocessable, assertPrivateFile } from "hmcp-core";
|
|
6
|
+
/*
|
|
7
|
+
* Re-exported so the console's own modules keep importing them from here.
|
|
8
|
+
* They live in core because the gateway needs them too and must not depend
|
|
9
|
+
* on the console.
|
|
10
|
+
*/
|
|
11
|
+
export { HttpError, MAX_BODY_BYTES, badRequest, conflict, notFound, unprocessable };
|
|
12
|
+
/**
|
|
13
|
+
* A handler's result with a status other than 200 (202 for "asked; it
|
|
14
|
+
* happens in the background"). Anything else a handler returns is sent as 200.
|
|
15
|
+
*/
|
|
16
|
+
export class Respond {
|
|
17
|
+
status;
|
|
18
|
+
body;
|
|
19
|
+
constructor(status, body) {
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.body = body;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export const respond = (status, body) => new Respond(status, body);
|
|
25
|
+
export function route(method, path, handler) {
|
|
26
|
+
return { method, pattern: path.split("/").filter(Boolean), handler };
|
|
27
|
+
}
|
|
28
|
+
function matchRoute(routes, method, segments) {
|
|
29
|
+
for (const r of routes) {
|
|
30
|
+
if (r.method !== method)
|
|
31
|
+
continue;
|
|
32
|
+
if (r.pattern.length !== segments.length)
|
|
33
|
+
continue;
|
|
34
|
+
const params = {};
|
|
35
|
+
let ok = true;
|
|
36
|
+
for (const [i, part] of r.pattern.entries()) {
|
|
37
|
+
const actual = segments[i];
|
|
38
|
+
if (part.startsWith(":"))
|
|
39
|
+
params[part.slice(1)] = decodeURIComponent(actual);
|
|
40
|
+
else if (part !== actual) {
|
|
41
|
+
ok = false;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (ok)
|
|
46
|
+
return { route: r, params };
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
/* --------------------------------------------------------------------- token */
|
|
51
|
+
/**
|
|
52
|
+
* A token on disk, readable only by its owner.
|
|
53
|
+
*
|
|
54
|
+
* Anyone who can read this file can approve a destructive call, so a
|
|
55
|
+
* group- or world-readable token is treated as a configuration error rather
|
|
56
|
+
* than tolerated.
|
|
57
|
+
*/
|
|
58
|
+
export function loadOrCreateToken(path = expandPath("~/.hmcp/web-token")) {
|
|
59
|
+
if (existsSync(path)) {
|
|
60
|
+
assertPrivate(path);
|
|
61
|
+
return readFileSync(path, "utf8").trim();
|
|
62
|
+
}
|
|
63
|
+
const token = randomBytes(32).toString("base64url");
|
|
64
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
65
|
+
writeFileSync(path, `${token}\n`, { encoding: "utf8", mode: 0o600 });
|
|
66
|
+
return token;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Windows has no mode bits -- `stat` there reports 0o666 for every file it
|
|
70
|
+
* can write -- so core's check skips it; access there is the user profile's
|
|
71
|
+
* ACL, which already keeps other users out.
|
|
72
|
+
*/
|
|
73
|
+
function assertPrivate(path) {
|
|
74
|
+
assertPrivateFile(path, {
|
|
75
|
+
error: (p, mode) => new Error(`${p} is readable by other users (mode ${mode.toString(8)}). ` +
|
|
76
|
+
"Anyone who can read it can approve a write. Run: chmod 600 " +
|
|
77
|
+
p)
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** What GET /api/v1/ping answers, so `hmcp start` can tell its own console from something else on the port. */
|
|
81
|
+
export const HEALTH_APP = "hmcp-web";
|
|
82
|
+
/** Not /api/v1/health: that one needs a session, and the UI uses it to tell whether it is signed in. */
|
|
83
|
+
export const PING_PATH = "/api/v1/ping";
|
|
84
|
+
/**
|
|
85
|
+
* Which console this is, without saying anything that signs in: a keyed hash
|
|
86
|
+
* of its sign-in token. Two consoles answer with the same id only when they
|
|
87
|
+
* share a home folder (and so a token); \`hmcp start\` and \`npm run demo\` reuse
|
|
88
|
+
* a running console only then, instead of any console on the port (R1).
|
|
89
|
+
*/
|
|
90
|
+
export function consoleId(token) {
|
|
91
|
+
return createHmac("sha256", token).update("hmcp-console-id").digest("hex").slice(0, 32);
|
|
92
|
+
}
|
|
93
|
+
/* -------------------------------------------------------------------- static */
|
|
94
|
+
const CONTENT_TYPES = {
|
|
95
|
+
".html": "text/html; charset=utf-8",
|
|
96
|
+
".js": "text/javascript; charset=utf-8",
|
|
97
|
+
".css": "text/css; charset=utf-8",
|
|
98
|
+
".json": "application/json; charset=utf-8",
|
|
99
|
+
".svg": "image/svg+xml",
|
|
100
|
+
// The icon ladder: a browser that will not take an SVG favicon asks for one
|
|
101
|
+
// of these, and served as octet-stream it is quietly ignored.
|
|
102
|
+
".png": "image/png",
|
|
103
|
+
".ico": "image/x-icon",
|
|
104
|
+
".woff2": "font/woff2",
|
|
105
|
+
".map": "application/json; charset=utf-8"
|
|
106
|
+
};
|
|
107
|
+
export function createConsoleServer(options) {
|
|
108
|
+
const sessions = new Set();
|
|
109
|
+
const csrfBySession = new Map();
|
|
110
|
+
return createServer((req, res) => {
|
|
111
|
+
handle(req, res, options, sessions, csrfBySession).catch((err) => {
|
|
112
|
+
// A stack trace or an unexpected path must not reach the client.
|
|
113
|
+
process.stderr.write(`[hmcp-web] ${err.stack ?? String(err)}\n`);
|
|
114
|
+
if (!res.headersSent)
|
|
115
|
+
send(res, 500, { error: { code: "internal", message: "internal error" } });
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function securityHeaders(res, isApi) {
|
|
120
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
121
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
122
|
+
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
|
|
123
|
+
res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
124
|
+
res.setHeader("Permissions-Policy", "geolocation=(), camera=(), microphone=()");
|
|
125
|
+
if (isApi)
|
|
126
|
+
res.setHeader("Cache-Control", "no-store");
|
|
127
|
+
else {
|
|
128
|
+
res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; " +
|
|
129
|
+
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; " +
|
|
130
|
+
"form-action 'none'; frame-ancestors 'none'; base-uri 'none'");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function send(res, status, body) {
|
|
134
|
+
const text = JSON.stringify(body, null, 2);
|
|
135
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
136
|
+
res.end(text);
|
|
137
|
+
}
|
|
138
|
+
async function handle(req, res, options, sessions, csrfBySession) {
|
|
139
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
140
|
+
const isApi = url.pathname.startsWith("/api/");
|
|
141
|
+
securityHeaders(res, isApi);
|
|
142
|
+
// 1. Loopback only. The listener is already bound to 127.0.0.1; this catches
|
|
143
|
+
// a proxy someone puts in front of it by accident.
|
|
144
|
+
const remote = req.socket.remoteAddress ?? "";
|
|
145
|
+
if (!["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(remote)) {
|
|
146
|
+
send(res, 403, { error: { code: "forbidden", message: "this console only serves loopback requests" } });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
// 2. Host check. A domain that resolves to 127.0.0.1 in order to reach this
|
|
150
|
+
// process still sends its own Host header, so this is what closes DNS
|
|
151
|
+
// rebinding against the console.
|
|
152
|
+
// Port 0 means "any free port": the one actually serving is the socket's own.
|
|
153
|
+
const port = options.port === 0 ? req.socket.localPort : options.port;
|
|
154
|
+
const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
|
|
155
|
+
if (!allowedHosts.includes(req.headers.host ?? "")) {
|
|
156
|
+
send(res, 403, { error: { code: "forbidden", message: `unexpected Host header: ${req.headers.host}` } });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const mutating = req.method !== "GET" && req.method !== "HEAD";
|
|
160
|
+
// 3. Origin, when the browser sent one.
|
|
161
|
+
const origin = req.headers.origin;
|
|
162
|
+
if (origin) {
|
|
163
|
+
const allowed = [`http://127.0.0.1:${port}`, `http://localhost:${port}`].concat(options.allowOrigins ?? []);
|
|
164
|
+
if (!allowed.includes(origin)) {
|
|
165
|
+
send(res, 403, { error: { code: "forbidden", message: "cross-origin request refused" } });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
else if (mutating) {
|
|
170
|
+
send(res, 403, { error: { code: "forbidden", message: "a mutating request must carry an Origin header" } });
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (!isApi) {
|
|
174
|
+
serveStatic(req, res, options.uiDir);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
/*
|
|
178
|
+
* Unauthenticated on purpose and saying nothing but "this is the console",
|
|
179
|
+
* and which one: `hmcp start` asks it before starting a second one, and has
|
|
180
|
+
* no session.
|
|
181
|
+
*/
|
|
182
|
+
if (url.pathname === PING_PATH && req.method === "GET") {
|
|
183
|
+
send(res, 200, { app: HEALTH_APP, ok: true, id: consoleId(options.token) });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
187
|
+
// The session exchange: hand in the token printed at startup, get a cookie.
|
|
188
|
+
if (url.pathname === "/api/v1/session" && req.method === "POST") {
|
|
189
|
+
const body = (await readBody(req));
|
|
190
|
+
if (typeof body?.token !== "string" || !constantTimeEquals(body.token, options.token)) {
|
|
191
|
+
send(res, 401, { error: { code: "unauthorized", message: "bad token" } });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const session = randomBytes(24).toString("base64url");
|
|
195
|
+
const csrf = randomBytes(24).toString("base64url");
|
|
196
|
+
sessions.add(session);
|
|
197
|
+
csrfBySession.set(session, csrf);
|
|
198
|
+
res.setHeader("Set-Cookie", [
|
|
199
|
+
`hmcp_web=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800`,
|
|
200
|
+
`hmcp_csrf=${csrf}; SameSite=Strict; Path=/; Max-Age=28800`
|
|
201
|
+
]);
|
|
202
|
+
send(res, 200, { ok: true });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const session = cookies["hmcp_web"];
|
|
206
|
+
if (!session || !sessions.has(session)) {
|
|
207
|
+
send(res, 401, { error: { code: "unauthorized", message: "no session; reopen the URL printed at startup" } });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (mutating) {
|
|
211
|
+
// 4. Double submit. SameSite=Strict already blocks cross-site cookie
|
|
212
|
+
// attachment; this covers another local server on a different port,
|
|
213
|
+
// which is same-site for cookie purposes on loopback.
|
|
214
|
+
const expected = csrfBySession.get(session);
|
|
215
|
+
const supplied = req.headers["x-hmcp-csrf"];
|
|
216
|
+
if (!expected || typeof supplied !== "string" || !constantTimeEquals(supplied, expected)) {
|
|
217
|
+
send(res, 403, { error: { code: "forbidden", message: "missing or stale X-HMCP-CSRF header" } });
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
// A JSON-only body is something an HTML form cannot produce.
|
|
221
|
+
const contentType = (req.headers["content-type"] ?? "").split(";")[0].trim();
|
|
222
|
+
if (contentType !== "application/json") {
|
|
223
|
+
send(res, 400, { error: { code: "bad-request", message: "Content-Type must be application/json" } });
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
228
|
+
const matched = matchRoute(options.routes, req.method ?? "GET", segments);
|
|
229
|
+
if (!matched) {
|
|
230
|
+
send(res, 404, { error: { code: "not-found", message: `no route for ${req.method} ${url.pathname}` } });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const body = mutating ? await readBody(req) : undefined;
|
|
235
|
+
const result = await matched.route.handler({
|
|
236
|
+
method: req.method ?? "GET",
|
|
237
|
+
path: url.pathname,
|
|
238
|
+
params: matched.params,
|
|
239
|
+
query: url.searchParams,
|
|
240
|
+
body,
|
|
241
|
+
actor: options.actor,
|
|
242
|
+
...(req.headers.host ? { host: req.headers.host } : {})
|
|
243
|
+
});
|
|
244
|
+
if (result instanceof Respond)
|
|
245
|
+
send(res, result.status, result.body);
|
|
246
|
+
else
|
|
247
|
+
send(res, 200, result);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
if (err instanceof HttpError) {
|
|
251
|
+
send(res, err.status, {
|
|
252
|
+
error: { code: err.code, message: err.message, ...(err.detail ? { detail: err.detail } : {}) }
|
|
253
|
+
});
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
process.stderr.write(`[hmcp-web] ${err.stack ?? String(err)}\n`);
|
|
257
|
+
send(res, 500, { error: { code: "internal", message: err.message } });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function parseCookies(header) {
|
|
261
|
+
const out = {};
|
|
262
|
+
for (const part of (header ?? "").split(";")) {
|
|
263
|
+
const index = part.indexOf("=");
|
|
264
|
+
if (index === -1)
|
|
265
|
+
continue;
|
|
266
|
+
out[part.slice(0, index).trim()] = part.slice(index + 1).trim();
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
function serveStatic(req, res, uiDir) {
|
|
271
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
272
|
+
res.writeHead(405, { "Content-Type": "text/plain; charset=utf-8" });
|
|
273
|
+
res.end("method not allowed\n");
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (!existsSync(uiDir)) {
|
|
277
|
+
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
|
|
278
|
+
res.end("The console UI has not been built yet. Run:\n\n npm run -w hmcp-web build:ui\n");
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
282
|
+
let pathname;
|
|
283
|
+
try {
|
|
284
|
+
pathname = decodeURIComponent(url.pathname);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
res.writeHead(400).end();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
// Traversal and NUL are rejected after decoding, then the resolved path is
|
|
291
|
+
// asserted to stay inside the root.
|
|
292
|
+
if (pathname.includes("\0")) {
|
|
293
|
+
res.writeHead(400).end();
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const root = resolve(uiDir);
|
|
297
|
+
const candidate = resolve(join(root, normalize(pathname)));
|
|
298
|
+
const inRoot = candidate === root || candidate.startsWith(root + sep);
|
|
299
|
+
const found = inRoot && existsSync(candidate) && statSync(candidate).isFile();
|
|
300
|
+
// A build file that is not there is a 404, not the app. The UI bundle still
|
|
301
|
+
// names its source map, which is not shipped, and answering that with
|
|
302
|
+
// index.html made every browser's developer tools report a broken map.
|
|
303
|
+
// Page routes have no extension and stay with the single-page fallback.
|
|
304
|
+
if (!found && (pathname.startsWith("/assets/") || pathname.endsWith(".map"))) {
|
|
305
|
+
res.writeHead(404).end();
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const file = found ? candidate : join(root, "index.html");
|
|
309
|
+
if (!existsSync(file)) {
|
|
310
|
+
res.writeHead(404).end();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
res.writeHead(200, { "Content-Type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream" });
|
|
314
|
+
if (req.method === "HEAD") {
|
|
315
|
+
res.end();
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
createReadStream(file).pipe(res);
|
|
319
|
+
}
|