@basaltkit/deploy-ui 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Basalt Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,168 @@
1
- # Temporary Holding Version
1
+ # @basaltkit/deploy-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local web UI for [`@basaltkit/deploy`](../deploy#readme). It runs on **your
4
+ machine**, listens on `127.0.0.1` only, and drives each server over **your own
5
+ `ssh`** — your keys, your agent, your `known_hosts` — as the app user, exactly
6
+ as you would type the commands yourself. Nothing is installed or started on the
7
+ server; the UI can do what your SSH account can do, and nothing more.
8
+
9
+ Design and threat model: [RFC 0009](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0009-deploy-local-ui.md)
10
+ (it builds on the machine protocol of [RFC 0008](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0008-deploy-machine-protocol.md)
11
+ and the pipeline of [RFC 0006](https://github.com/basaltkit/basalt/blob/main/docs/rfcs/0006-basalt-deploy.md)).
12
+
13
+ ## Start it
14
+
15
+ ```sh
16
+ npx @basaltkit/deploy-ui@<exact version>
17
+ # or: npm install -g @basaltkit/deploy-ui@<exact version> && basalt-deploy-ui
18
+ ```
19
+
20
+ It prints `listening on http://127.0.0.1:<port>/` and opens your browser with a
21
+ one-time code. Pin an exact version: it is a tool that handles your deploy
22
+ secrets.
23
+
24
+ > **Never add it to an app's `package.json`** — not even as a devDependency.
25
+ > `@basaltkit/deploy` runs the app's `pnpm install` on the server, which
26
+ > installs devDependencies: the UI would land on every server.
27
+ > `basalt-deploy ui` (in the app) only prints this reminder.
28
+
29
+ | Option | |
30
+ |---|---|
31
+ | `--targets=<file>` | the targets file (default below) |
32
+ | `--ssh=<absolute path>` | the ssh client (default: `ssh` from `PATH`; on Windows `%SystemRoot%\System32\OpenSSH\ssh.exe`, else the first `ssh.exe` in an absolute `PATH` entry, never the current folder) |
33
+ | `--no-open` | print the URL instead of opening the browser |
34
+ | `--idle-minutes=<n>` | stop after n idle minutes (1–240, default 15) |
35
+
36
+ There is no `--host` and no `--port`: see the security model.
37
+
38
+ ## What a server needs
39
+
40
+ - The app checked out and deployed once with `@basaltkit/deploy` from a
41
+ terminal (the UI speaks protocol 1: the release with RFC 0008's `--json`).
42
+ - An SSH account (the app user) you can already reach with `ssh` from a
43
+ terminal, with a key in your agent: the UI runs `ssh` in batch mode and never
44
+ asks for a password, a passphrase or a host-key confirmation.
45
+ - A POSIX login shell for that account (`sh`, `bash`, `zsh`).
46
+
47
+ ## Targets
48
+
49
+ Kept in **your** config directory — `$XDG_CONFIG_HOME/basalt/deploy-targets.json`
50
+ (default `~/.config/basalt/…`), `%APPDATA%\basalt\deploy-targets.json` on
51
+ Windows — written `0600`, never in the app repository: a target names where your
52
+ key and the `.env` secrets you type are sent, and a commit to a shared
53
+ repository must not be able to repoint it. The file holds no secret.
54
+
55
+ ```json
56
+ {
57
+ "version": 1,
58
+ "actor": "alice",
59
+ "targets": [
60
+ { "name": "staging", "ssh": "deploy@203.0.113.10", "dir": "/srv/myapp" },
61
+ { "name": "production", "ssh": "myapp-prod", "port": 2222, "dir": "/srv/myapp", "node": "/usr/local/bin/node", "protected": true }
62
+ ]
63
+ }
64
+ ```
65
+
66
+ | Field | |
67
+ |---|---|
68
+ | `name` | `a-z`, `0-9`, `-`; the UI's key, never put in a command |
69
+ | `ssh` | `[user@]host` or a `Host` alias of your `~/.ssh/config` — jump hosts, identity files and proxies go there |
70
+ | `port` | optional, 1–65535 |
71
+ | `dir` | the checkout on the server, absolute |
72
+ | `node` | optional absolute path, when a non-interactive shell has no `node` on `PATH` (nvm); from `@basaltkit/deploy` 0.5.1 the deploy puts its directory on `PATH` for `pnpm` and the app's scripts too |
73
+ | `config` | optional `--config` path, relative to the checkout |
74
+ | `protected` | deploy and rollback need the target's name typed |
75
+ | `actor` | recorded with each release (`--actor`); default: your OS user name |
76
+
77
+ Every field has a closed grammar (no leading `-`, no spaces, no `..`); an
78
+ unknown field is refused, not ignored. The UI refuses a targets file that is a
79
+ symbolic link, writable by other users, or owned by another user (root
80
+ included). It also refuses one in a directory, up to `/`, that another user
81
+ owns or that others can write to without the sticky bit: whoever can replace
82
+ the file chooses where your secrets go. A deploy, a `.env` write or a
83
+ rollback carries the target your confirmation showed. If the file changed
84
+ since then, nothing is sent, and the page shows the new values.
85
+
86
+ ## What it does
87
+
88
+ Per target: **check the connection**; **status** (current release, process,
89
+ lock, active and last run, a hold); **plan** (findings, what a run would do, the
90
+ questions it would ask); the **`.env` form** (secrets in password fields, never
91
+ stored, emptied after sending); **deploy** — detached by default, so a closed
92
+ laptop lid does not stop it, or attended; the **live log**, which re-attaches
93
+ after a dropped connection without a gap or a duplicate (even one cut
94
+ mid-line); **cancel** (a second cancel, separately confirmed, stops it at
95
+ once; the server decides which one it is, so a cancel already sent from a
96
+ terminal counts); **rollback**, to the last
97
+ healthy release or one picked from **history** (the last 10 releases); and
98
+ "Write .env only" for a first setup.
99
+
100
+ Each action is one `ssh` invocation of the app's own, lockfile-pinned
101
+ `node node_modules/@basaltkit/deploy/dist/bin.js <command> --json=1`, with
102
+ `--via=ui` so the release record says how it was made. `install`, `bootstrap`
103
+ and `init` (root's or code-writing commands) are not reachable from the UI.
104
+
105
+ ## Security model
106
+
107
+ The server is reachable by every process on your machine and is a target for
108
+ every page your browser opens. So:
109
+
110
+ - **Loopback only.** `127.0.0.1` and a port the OS picks; never `0.0.0.0`, `::`
111
+ or `localhost`. Nothing ever listens on the server.
112
+ - **One browser session.** A 256-bit one-time launch code in the URL fragment
113
+ (never sent in a request, valid 120 s) is exchanged once for a 256-bit session
114
+ token, held in that tab's `sessionStorage` and sent as `Authorization: Bearer`
115
+ — not a cookie: cookies are not port-scoped and would reach your other local
116
+ servers. A second claim is refused and printed in the terminal.
117
+ - **The server proves itself.** The exchange also gives the page a key that
118
+ it never sends. After every load, and before any `.env` answer leaves the
119
+ page, the server must answer a fresh challenge with an HMAC under that key.
120
+ Once the UI has stopped, another program may take its port. It may have
121
+ seen the token, but it never has the key, so it gets no answer. When the
122
+ server is gone or fails the check, the page empties its forms, forgets the
123
+ session and says so.
124
+ - **Every request checked:** exact `Host` (DNS rebinding), API calls `POST`
125
+ only with `application/json`, an exact `Origin`, `Sec-Fetch-Site:
126
+ same-origin` when sent, and the token in constant time; 1 MiB bodies; no
127
+ CORS, ever. Static files come from a fixed list read at start.
128
+ - **Strict CSP** (`script-src 'self'`, no inline script or style,
129
+ `frame-ancestors 'none'`), `X-Frame-Options: DENY`, `no-store`.
130
+ - **System `ssh`, argv only**, with `BatchMode=yes`, `StrictHostKeyChecking=yes`
131
+ (a host you never verified is refused, whatever your config says),
132
+ `ForwardAgent=no`, `ForwardX11=no`, `ClearAllForwardings=yes`,
133
+ `PermitLocalCommand=no`, `-e none`, and `--` before the destination. The
134
+ remote command is built from validated pieces, each single-quoted. ssh (and
135
+ the browser opener) start in your home directory. On Windows they are always
136
+ absolute paths, because Windows looks a bare `ssh.exe` up in the current
137
+ folder first.
138
+ - **Secrets travel once:** browser → loopback request body → `ssh` stdin.
139
+ Never in argv, the environment, a file, a log, the URL or `sessionStorage`;
140
+ the buffers the UI owns are zero-filled after the write. The deploy redacts
141
+ them from every event on the server.
142
+ - **Server output is data:** every line is validated (`parseEvent`, `seq`
143
+ continuity, 1 MiB per line); text is rendered as text only and cleaned of
144
+ escapes, control and bidi characters; a build that prints a fake event is a
145
+ log line.
146
+ - **Idle shutdown** after 15 minutes without a request (an open live log or a
147
+ command still running keeps it alive). Quit from the page or `Ctrl-C`;
148
+ detached runs go on on the server.
149
+ - **Destructive confirmations** open with the focus on *Cancel* (or on the
150
+ typed name for a protected target), never on the destructive button.
151
+
152
+ Limits: on a machine shared with other users, the launch code is visible in the
153
+ browser opener's arguments for an instant — a claim by anyone else makes your
154
+ tab fail loudly and the terminal say so (RFC 0009 Q1). JavaScript strings
155
+ cannot be wiped from memory. The server's proof is checked just before an
156
+ answer is sent, not inside the same request. After a reload, the page you get
157
+ is whatever answers on the port. When the terminal says the UI stopped, close
158
+ the tab (RFC 0009 §15).
159
+
160
+ ## Troubleshooting
161
+
162
+ | The UI says | Do |
163
+ |---|---|
164
+ | the server refused your SSH key | `ssh-add`, then check `ssh deploy@host` works from a terminal |
165
+ | your SSH key needs its passphrase | add it to your agent: `ssh-add` |
166
+ | this host's key is not in your known_hosts | connect once from a terminal and check the fingerprint |
167
+ | node was not found on the server | set the target's `node` to an absolute path |
168
+ | no protocol output from the server | a POSIX login shell? `@basaltkit/deploy` recent enough (RFC 0008)? |
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './cli.js';
3
+ process.exit(await main(process.argv.slice(2)));
package/dist/cli.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { Spawn, SshRunner } from './remote.js';
2
+ import { type UiServer, type UiServerOptions } from './server.js';
3
+ export declare const USAGE = "basalt-deploy-ui \u2014 a local UI for @basaltkit/deploy (RFC 0009)\n\nRuns on YOUR machine, never on the server. Listens on 127.0.0.1 only and drives\neach server over your own ssh (keys, agent, known_hosts), as the app user.\n\n npx @basaltkit/deploy-ui@<exact version> [options]\n\nOptions:\n --targets=<file> the targets file (default: $XDG_CONFIG_HOME/basalt/deploy-targets.json,\n %APPDATA%\\basalt\\deploy-targets.json on Windows)\n --ssh=<absolute path> the ssh client (default: ssh from PATH; on Windows\n %SystemRoot%\\System32\\OpenSSH\\ssh.exe, else the first ssh.exe\n in an absolute PATH entry \u2014 never the current folder)\n --no-open print the URL instead of opening the browser\n --idle-minutes=<n> stop after n idle minutes (1\u2013240, default 15)\n -h, --help\n\nNever add @basaltkit/deploy-ui to an app's package.json: the deploy installs an\napp's devDependencies on the server.\n";
4
+ export interface CliFlags {
5
+ targets?: string;
6
+ ssh?: string;
7
+ open: boolean;
8
+ idleMinutes: number;
9
+ help: boolean;
10
+ }
11
+ export declare class UsageError extends Error {
12
+ }
13
+ export declare function parseFlags(argv: readonly string[], cwd: string): CliFlags;
14
+ export interface CliDeps {
15
+ platform: NodeJS.Platform;
16
+ env: NodeJS.ProcessEnv;
17
+ cwd: string;
18
+ home: string;
19
+ osUser: string | undefined;
20
+ spawn: Spawn;
21
+ /** One line to the terminal (stderr). */
22
+ print: (line: string) => void;
23
+ /** The browser opener; the URL carries the one-time launch code. */
24
+ open: (url: string) => Promise<boolean>;
25
+ start: (options: UiServerOptions) => Promise<UiServer>;
26
+ /** Ctrl-C and friends. */
27
+ onSignal: (listener: () => void) => void;
28
+ /** Overrides for tests (the fake ssh). */
29
+ runner?: Partial<SshRunner>;
30
+ clientDir?: string | null;
31
+ }
32
+ export declare function processDeps(): CliDeps;
33
+ /** Starts the UI; resolves with an exit code once it has stopped (idle, quit, a signal) — or at once on a usage error. */
34
+ export declare function main(argv: readonly string[], deps?: CliDeps): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process';
2
+ import { homedir, userInfo } from 'node:os';
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ import { openBrowser } from './open.js';
5
+ import { MAX_IDLE_MINUTES, startUiServer } from './server.js';
6
+ import { sshProgram } from './ssh.js';
7
+ import { defaultTargetsPath } from './targets.js';
8
+ export const USAGE = `basalt-deploy-ui — a local UI for @basaltkit/deploy (RFC 0009)
9
+
10
+ Runs on YOUR machine, never on the server. Listens on 127.0.0.1 only and drives
11
+ each server over your own ssh (keys, agent, known_hosts), as the app user.
12
+
13
+ npx @basaltkit/deploy-ui@<exact version> [options]
14
+
15
+ Options:
16
+ --targets=<file> the targets file (default: $XDG_CONFIG_HOME/basalt/deploy-targets.json,
17
+ %APPDATA%\\basalt\\deploy-targets.json on Windows)
18
+ --ssh=<absolute path> the ssh client (default: ssh from PATH; on Windows
19
+ %SystemRoot%\\System32\\OpenSSH\\ssh.exe, else the first ssh.exe
20
+ in an absolute PATH entry — never the current folder)
21
+ --no-open print the URL instead of opening the browser
22
+ --idle-minutes=<n> stop after n idle minutes (1–${MAX_IDLE_MINUTES}, default 15)
23
+ -h, --help
24
+
25
+ Never add @basaltkit/deploy-ui to an app's package.json: the deploy installs an
26
+ app's devDependencies on the server.
27
+ `;
28
+ export class UsageError extends Error {
29
+ }
30
+ export function parseFlags(argv, cwd) {
31
+ const flags = { open: true, idleMinutes: 15, help: false };
32
+ for (const arg of argv) {
33
+ if (arg === '-h' || arg === '--help') {
34
+ flags.help = true;
35
+ continue;
36
+ }
37
+ if (arg === '--no-open') {
38
+ flags.open = false;
39
+ continue;
40
+ }
41
+ const match = /^--(targets|ssh|idle-minutes)=(.+)$/.exec(arg);
42
+ if (!match)
43
+ throw new UsageError(`unknown argument ${JSON.stringify(arg)} (there is no --host or --port: the UI listens on 127.0.0.1 and a port the OS picks)`);
44
+ const [, name, value] = match;
45
+ if (name === 'targets')
46
+ flags.targets = resolve(cwd, value);
47
+ else if (name === 'ssh') {
48
+ if (!isAbsolute(value))
49
+ throw new UsageError('--ssh takes an absolute path');
50
+ flags.ssh = value;
51
+ }
52
+ else {
53
+ if (!/^\d{1,3}$/.test(value) || Number(value) < 1 || Number(value) > MAX_IDLE_MINUTES)
54
+ throw new UsageError(`--idle-minutes takes 1 to ${MAX_IDLE_MINUTES}`);
55
+ flags.idleMinutes = Number(value);
56
+ }
57
+ }
58
+ return flags;
59
+ }
60
+ export function processDeps() {
61
+ let osUser;
62
+ try {
63
+ osUser = userInfo().username;
64
+ }
65
+ catch {
66
+ osUser = undefined;
67
+ }
68
+ return {
69
+ platform: process.platform,
70
+ env: process.env,
71
+ cwd: process.cwd(),
72
+ home: homedir(),
73
+ osUser,
74
+ spawn: nodeSpawn,
75
+ print: (line) => { process.stderr.write(`${line}\n`); },
76
+ open: (url) => openBrowser(nodeSpawn, process.platform, url, homedir(), process.env),
77
+ start: startUiServer,
78
+ onSignal: (listener) => { for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'])
79
+ process.once(signal, listener); },
80
+ };
81
+ }
82
+ /** Starts the UI; resolves with an exit code once it has stopped (idle, quit, a signal) — or at once on a usage error. */
83
+ export async function main(argv, deps = processDeps()) {
84
+ let flags;
85
+ try {
86
+ flags = parseFlags(argv, deps.cwd);
87
+ }
88
+ catch (error) {
89
+ deps.print(`basalt-deploy-ui: ${error.message}`);
90
+ return 2;
91
+ }
92
+ if (flags.help) {
93
+ deps.print(USAGE.trimEnd());
94
+ return 0;
95
+ }
96
+ const targetsPath = flags.targets ?? defaultTargetsPath(deps.platform, deps.env, deps.home);
97
+ let finish = () => undefined;
98
+ const finished = new Promise((resolve) => { finish = resolve; });
99
+ const server = await deps.start({
100
+ targetsPath,
101
+ runner: { program: sshProgram(deps.platform, flags.ssh, deps.env), prefix: [], spawn: deps.spawn, env: deps.env, cwd: deps.home, ...deps.runner },
102
+ ...(deps.osUser ? { osUser: deps.osUser } : {}),
103
+ idleMinutes: flags.idleMinutes,
104
+ ...(deps.clientDir === undefined ? {} : { clientDir: deps.clientDir }),
105
+ log: (line) => deps.print(`basalt-deploy-ui: ${line}`),
106
+ onStop: (reason) => {
107
+ deps.print(reason === 'idle' ? `basalt-deploy-ui: stopped after ${flags.idleMinutes} idle minutes` : 'basalt-deploy-ui: stopped');
108
+ finish(0);
109
+ },
110
+ });
111
+ deps.onSignal(() => {
112
+ void server.close().then(() => {
113
+ deps.print('basalt-deploy-ui: stopped (detached runs go on on the server)');
114
+ finish(0);
115
+ });
116
+ });
117
+ deps.print(`basalt-deploy-ui: listening on ${server.url} (this machine only)`);
118
+ deps.print(`basalt-deploy-ui: targets in ${targetsPath}`);
119
+ const opened = flags.open && await Promise.race([deps.open(server.launchUrl), new Promise((resolve) => setTimeout(() => resolve(true), 5000).unref())]);
120
+ if (!opened) {
121
+ deps.print(`basalt-deploy-ui: open this URL in your browser within 2 minutes (it works once):\n ${server.launchUrl}`);
122
+ }
123
+ return finished;
124
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * The page's calls to its local server: POST, JSON, the session token as a
3
+ * bearer header (never a cookie: cookies are not port-scoped). Streams are
4
+ * POST too, read with fetch, NDJSON line by line.
5
+ */
6
+ export class ApiError extends Error {
7
+ status;
8
+ body;
9
+ constructor(status, message, body = {}) {
10
+ super(message);
11
+ this.status = status;
12
+ this.body = body;
13
+ }
14
+ }
15
+ /**
16
+ * The local server is gone (`unreachable`: the UI stopped — idle, quit,
17
+ * Ctrl-C) or is not the one this page was opened from (`unverified`: it
18
+ * could not prove it knows the server key). The page stops: nothing more is
19
+ * sent, and never an answer.
20
+ */
21
+ export class ServerGone extends Error {
22
+ why;
23
+ constructor(why, message) {
24
+ super(message);
25
+ this.why = why;
26
+ }
27
+ }
28
+ /** The same string as the server's `PROOF_CONTEXT` (session.ts; a test keeps them equal). */
29
+ export const PROOF_CONTEXT = 'basalt-deploy-ui hello v1\n';
30
+ const toBase64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
31
+ function fromBase64Url(text) {
32
+ const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/'));
33
+ const bytes = new Uint8Array(binary.length);
34
+ for (let i = 0; i < binary.length; i++)
35
+ bytes[i] = binary.charCodeAt(i);
36
+ return bytes;
37
+ }
38
+ const init = (body, token, signal) => ({
39
+ method: 'POST',
40
+ headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
41
+ body: JSON.stringify(body),
42
+ credentials: 'omit',
43
+ cache: 'no-store',
44
+ redirect: 'error',
45
+ ...(signal ? { signal } : {}),
46
+ });
47
+ async function failure(response) {
48
+ const type = response.headers.get('content-type') ?? '';
49
+ try {
50
+ if (type.startsWith('application/json')) {
51
+ const body = (await response.json());
52
+ return new ApiError(response.status, typeof body['error'] === 'string' ? body['error'] : `HTTP ${response.status}`, body);
53
+ }
54
+ return new ApiError(response.status, (await response.text()).trim() || `HTTP ${response.status}`);
55
+ }
56
+ catch {
57
+ return new ApiError(response.status, `HTTP ${response.status}`);
58
+ }
59
+ }
60
+ /** Splits a byte stream into lines (UTF-8 across chunk boundaries). */
61
+ export async function readLines(body, onLine) {
62
+ const reader = body.getReader();
63
+ const decoder = new TextDecoder();
64
+ let pending = '';
65
+ for (;;) {
66
+ const { value, done } = await reader.read();
67
+ if (done)
68
+ break;
69
+ pending += decoder.decode(value, { stream: true });
70
+ let newline;
71
+ while ((newline = pending.indexOf('\n')) !== -1) {
72
+ const line = pending.slice(0, newline);
73
+ pending = pending.slice(newline + 1);
74
+ if (line.trim() !== '')
75
+ onLine(line);
76
+ }
77
+ }
78
+ pending += decoder.decode();
79
+ if (pending.trim() !== '')
80
+ onLine(pending);
81
+ }
82
+ /** The launch code for the session's credentials, once. */
83
+ export async function exchange(code, fetchImpl) {
84
+ const response = await fetchImpl('/api/session', init({ code }, undefined));
85
+ if (!response.ok)
86
+ throw await failure(response);
87
+ const body = (await response.json());
88
+ if (typeof body.token !== 'string' || typeof body.serverKey !== 'string')
89
+ throw new ApiError(500, 'no token or no server key in the session reply');
90
+ return { token: body.token, serverKey: body.serverKey };
91
+ }
92
+ const carriesAnswers = (body) => Array.isArray(body['answers']) && body['answers'].length > 0;
93
+ export class Api {
94
+ token;
95
+ fetchImpl;
96
+ options;
97
+ /** Called once, the first time the server is found gone or unverified. */
98
+ onGone;
99
+ gone;
100
+ constructor(token, fetchImpl, options = {}) {
101
+ this.token = token;
102
+ this.fetchImpl = fetchImpl;
103
+ this.options = options;
104
+ }
105
+ /**
106
+ * Checks that the server is the process this page was opened from: a fresh
107
+ * random nonce, answered with HMAC-SHA256(serverKey, context + nonce).
108
+ * Anything else — no key, no WebCrypto, a refusal, a wrong proof — and the
109
+ * page stops.
110
+ */
111
+ async verifyServer() {
112
+ const crypto = this.options.crypto;
113
+ const serverKey = this.options.serverKey;
114
+ if (!serverKey || !crypto?.subtle)
115
+ throw this.stop('unverified', 'this page cannot check its local server (no server key, or no WebCrypto): nothing is sent');
116
+ const nonce = toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
117
+ let proof;
118
+ try {
119
+ proof = (await this.send('hello', { nonce })).proof;
120
+ }
121
+ catch (error) {
122
+ if (error instanceof ServerGone)
123
+ throw error;
124
+ throw this.stop('unverified', 'the local server refused to prove it is this UI: it is not the one this page was opened from');
125
+ }
126
+ let valid = false;
127
+ if (typeof proof === 'string' && /^[A-Za-z0-9_-]{43}$/.test(proof)) {
128
+ const key = await crypto.subtle.importKey('raw', fromBase64Url(serverKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
129
+ valid = await crypto.subtle.verify('HMAC', key, fromBase64Url(proof), new TextEncoder().encode(`${PROOF_CONTEXT}${nonce}`));
130
+ }
131
+ if (!valid)
132
+ throw this.stop('unverified', 'the local server could not prove it is this UI: another program may be listening on its port');
133
+ }
134
+ /** A call; one that carries answers checks the server first. */
135
+ async post(route, body = {}) {
136
+ if (carriesAnswers(body))
137
+ await this.verifyServer();
138
+ return this.send(route, body);
139
+ }
140
+ /** An NDJSON stream; resolves when it ends (or the signal aborts it). One that carries answers checks the server first. */
141
+ async stream(route, body, onMessage, signal) {
142
+ if (carriesAnswers(body))
143
+ await this.verifyServer();
144
+ const response = await this.request(route, body, signal);
145
+ if (!response.ok)
146
+ throw await failure(response);
147
+ if (!response.body)
148
+ throw new ApiError(500, 'the stream has no body');
149
+ let handlerFailed = false;
150
+ try {
151
+ await readLines(response.body, (line) => {
152
+ let message;
153
+ try {
154
+ message = JSON.parse(line);
155
+ }
156
+ catch {
157
+ return;
158
+ }
159
+ if (!message || typeof message !== 'object' || typeof message.kind !== 'string')
160
+ return;
161
+ try {
162
+ onMessage(message);
163
+ }
164
+ catch (error) {
165
+ handlerFailed = true;
166
+ throw error;
167
+ }
168
+ });
169
+ }
170
+ catch (error) {
171
+ // The page's own bug is not the server going away.
172
+ if (handlerFailed || signal?.aborted)
173
+ throw error;
174
+ throw this.stop('unreachable', 'the deploy UI stopped while this stream was open');
175
+ }
176
+ }
177
+ async send(route, body) {
178
+ const response = await this.request(route, body);
179
+ if (!response.ok)
180
+ throw await failure(response);
181
+ return (await response.json());
182
+ }
183
+ /** fetch, or the page stops: a loopback server that cannot be reached has stopped. */
184
+ async request(route, body, signal) {
185
+ if (this.gone)
186
+ throw this.gone;
187
+ try {
188
+ return await this.fetchImpl(`/api/${route}`, init(body, this.token, signal));
189
+ }
190
+ catch (error) {
191
+ if (signal?.aborted)
192
+ throw error;
193
+ throw this.stop('unreachable', 'the deploy UI is not running any more (it stopped after its idle time, from Quit, or with Ctrl-C)');
194
+ }
195
+ }
196
+ stop(why, message) {
197
+ if (this.gone)
198
+ return this.gone;
199
+ this.gone = new ServerGone(why, message);
200
+ this.onGone?.(this.gone);
201
+ return this.gone;
202
+ }
203
+ }