@anhlp/alp-cli 0.0.0-beta.2 → 0.0.1-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +25 -0
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +139 -23
  4. package/dist/alp-web/THIRD-PARTY-NOTICES.txt +2590 -0
  5. package/dist/alp-web/alp-boundary.json +15 -0
  6. package/dist/alp-web/apple-touch-icon.png +0 -0
  7. package/dist/alp-web/assets/TerminalPanel-DLuoa74B.css +1 -0
  8. package/dist/alp-web/assets/TerminalPanel-PrU2l3u5.js +16 -0
  9. package/dist/alp-web/assets/index-BJdBTDFX.css +1 -0
  10. package/dist/alp-web/assets/index-DpfiPv5s.js +52 -0
  11. package/dist/alp-web/favicon-attention.svg +6 -0
  12. package/dist/alp-web/favicon-running.svg +6 -0
  13. package/dist/alp-web/favicon.svg +5 -0
  14. package/dist/alp-web/index.html +20 -0
  15. package/dist/alp-web.js +9640 -0
  16. package/dist/alpd.js +10897 -3514
  17. package/dist/backup.js +2 -2
  18. package/dist/build-manifest.json +99 -1
  19. package/dist/cli.js +9 -3
  20. package/dist/daemon.js +6 -2
  21. package/dist/interfaces.d.ts +9 -1
  22. package/dist/interfaces.js +99 -39
  23. package/dist/schedules.d.ts +2 -0
  24. package/dist/schedules.js +45 -0
  25. package/dist/sessions.d.ts +3 -1
  26. package/dist/sessions.js +22 -11
  27. package/dist/terminal.d.ts +8 -0
  28. package/dist/terminal.js +79 -0
  29. package/dist/usage.d.ts +1 -1
  30. package/dist/usage.js +8 -2
  31. package/dist/web-service.d.ts +38 -0
  32. package/dist/web-service.js +119 -0
  33. package/package.json +10 -4
  34. package/src/backup.js +1 -1
  35. package/src/cli.js +12 -3
  36. package/src/daemon.js +8 -3
  37. package/src/interfaces.js +136 -31
  38. package/src/schedules.js +38 -0
  39. package/src/sessions.js +21 -11
  40. package/src/terminal.js +77 -0
  41. package/src/usage.js +8 -2
  42. package/src/web/grant.js +204 -0
  43. package/src/web/main.js +285 -0
  44. package/src/web/serve.js +144 -0
  45. package/src/web-service.js +143 -0
@@ -0,0 +1,285 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ /**
4
+ * alp-web (docs/alp/web.md): the service behind `alp web`. ONE loopback listener at `web.port`
5
+ * (default 7433, then the next nine ports) carries the ALP gateway and the built apps/web files.
6
+ * It owns the `web` integration lock and `<home>/web.json`, which names its pid, port, URL and the
7
+ * `alpgw1.*` token of its credential, so the CLI can open the app with the token in the address.
8
+ * It keeps alpd running (ALP_SUPERVISE=0 opts out) and keeps the credential's workspaces in step
9
+ * with alpd's project registry.
10
+ *
11
+ * node alp-web.js [--service] [--project DIR]
12
+ * node alp-web.js --rotate [--project DIR]
13
+ * `--service` (how startIntegration starts it) writes the log to <home>/logs/integrations/alp-web.log.
14
+ * `--rotate` (how `alp web rotate` replaces the token) takes the web lock, which fails with exit 3
15
+ * while the service runs, creates a new credential, revokes every other one, records the new token
16
+ * in web.json for the next start, releases the lock and exits. It ignores web.enabled: turning alp
17
+ * web off must not keep an old token alive.
18
+ * ALP_WEB_APP names another directory of built app files (tests).
19
+ */
20
+ import { randomBytes } from 'node:crypto';
21
+ import { mkdirSync, openSync, writeSync } from 'node:fs';
22
+ import { chmod, link, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
23
+ import path from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { parseArgs } from 'node:util';
26
+ import { alpHome, connectSocket, daemonPaths } from '@anhlp/alp-client/index';
27
+ import { createIntegrationLock } from '@anhlp/alp-client/integration-lock';
28
+ import { superviseDaemon } from '@anhlp/alp-client/supervise';
29
+ import { validateUserSettings } from '@anhlp/alp-core/validation';
30
+ import { CredentialStore, createGateway, createGatewayLogger, parseToken, resolveConfig } from '@anhlp/alp-gateway';
31
+ import { TERMINAL_EXEC_WARNING } from '@anhlp/alp-gateway/policy';
32
+ import { createGrant, grantPermissions, webGatewayHome } from './grant.js';
33
+ import { createStaticServer } from './serve.js';
34
+
35
+ // __ALP_VERSION__ is replaced at build time (esbuild define); a run from source reports a placeholder.
36
+ // @ts-ignore -- a build-time constant, not a declared global
37
+ const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-source';
38
+
39
+ export const DEFAULT_WEB_PORT = 7433;
40
+ /** Ports tried from web.port: it and the next nine. */
41
+ const PORT_TRIES = 10;
42
+ /** How often the workspace grant follows alpd's registry. */
43
+ const REFRESH_MS = Number(process.env.ALP_WEB_GRANT_REFRESH_MS) > 0 ? Number(process.env.ALP_WEB_GRANT_REFRESH_MS) : 5_000;
44
+ const WEB_FILE_VERSION = 2;
45
+
46
+ const here = path.dirname(fileURLToPath(import.meta.url));
47
+ const appDir = () => path.resolve(process.env.ALP_WEB_APP || path.join(here, 'alp-web'));
48
+ const daemonEntry = () => process.env.ALP_DAEMON_ENTRY ?? path.join(here, 'alpd.js');
49
+ const webFile = (/** @type {string} */ home) => path.join(home, 'web.json');
50
+
51
+ /** The service's output goes to its own log: startIntegration starts it detached with stdio ignored. @param {string} home */
52
+ function serviceLog(home) {
53
+ const file = path.join(home, 'logs', 'integrations', 'alp-web.log');
54
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
55
+ const fd = openSync(file, 'a', 0o600);
56
+ for (const stream of [process.stdout, process.stderr]) {
57
+ stream.write = /** @type {any} */ ((/** @type {any} */ chunk) => { try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, Buffer.from(chunk)); } catch {} return true; });
58
+ }
59
+ }
60
+
61
+ /** @param {string} home @param {import('@anhlp/alp-core/log').Logger} log */
62
+ async function userSettings(home, log) {
63
+ const file = path.join(home, 'settings.json');
64
+ let text;
65
+ try { text = await readFile(file, 'utf8'); } catch { return {}; }
66
+ try { return /** @type {any} */ (validateUserSettings(JSON.parse(text), file)); }
67
+ catch (error) { log.warn(`ignoring ${file}: ${/** @type {any} */ (error)?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' }); return {}; }
68
+ }
69
+
70
+ /** What the last run published, if it was alp-web's. @param {string} home */
71
+ async function previousWeb(home) {
72
+ try {
73
+ const kept = JSON.parse(await readFile(webFile(home), 'utf8'));
74
+ if (kept?.app !== 'alp-web' || kept?.version !== WEB_FILE_VERSION || !parseToken(kept.token)) return {};
75
+ return { token: kept.token, credentialId: kept.credentialId };
76
+ } catch { return {}; }
77
+ }
78
+
79
+ /** Writes web.json whole, private, in one rename. @param {string} home @param {object} info */
80
+ async function publish(home, info) {
81
+ const file = webFile(home);
82
+ const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
83
+ try {
84
+ await writeFile(temporary, `${JSON.stringify(info)}\n`, { mode: 0o600, flag: 'wx' });
85
+ await chmod(temporary, 0o600);
86
+ await rename(temporary, file);
87
+ } catch (error) { await unlink(temporary).catch(() => {}); throw error; }
88
+ }
89
+
90
+ /** Exit code of `--rotate` when the service holds the web lock. */
91
+ const LOCK_HELD = 3;
92
+
93
+ /**
94
+ * Before the rename, the Paseo integration ran as integration `web` and kept its identity (the token
95
+ * paired devices sign in with, and its server id) in web.json, without `app`. Before alp-web first
96
+ * overwrites such a file, and only when the Paseo integration has no paseo.json yet, that identity
97
+ * is written to paseo.json, where the integration looks for it, so paired devices stay paired. The
98
+ * file appears whole (written aside, then linked into place) and an existing paseo.json is never
99
+ * replaced. Returns whether it carried anything.
100
+ * @param {string} home @param {import('@anhlp/alp-core/log').Logger} log
101
+ */
102
+ async function carryPaseoIdentity(home, log) {
103
+ let legacy;
104
+ try { legacy = JSON.parse(await readFile(webFile(home), 'utf8')); } catch { return false; }
105
+ if (!legacy || typeof legacy !== 'object' || legacy.app !== undefined) return false;
106
+ const identity = {
107
+ ...(typeof legacy.token === 'string' && /^[a-f0-9]{64}$/.test(legacy.token) ? { token: legacy.token } : {}),
108
+ ...(typeof legacy.serverId === 'string' && /^alp-[a-f0-9]{16}$/.test(legacy.serverId) ? { serverId: legacy.serverId } : {}),
109
+ };
110
+ if (!Object.keys(identity).length) return false;
111
+ const target = path.join(home, 'paseo.json');
112
+ const temporary = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
113
+ try {
114
+ await writeFile(temporary, `${JSON.stringify(identity)}\n`, { mode: 0o600, flag: 'wx' });
115
+ await chmod(temporary, 0o600);
116
+ await link(temporary, target);
117
+ } catch (error) {
118
+ if (/** @type {any} */ (error)?.code === 'EEXIST') return false;
119
+ throw new Error(`the Paseo integration's identity in ${webFile(home)} could not be kept in ${target}, so alp web leaves web.json alone: ${/** @type {any} */ (error)?.message ?? error}`, { cause: error });
120
+ } finally { await unlink(temporary).catch(() => {}); }
121
+ log.info(`kept the Paseo integration's identity from web.json in ${target}, so paired devices stay paired`, { code: 'ALP_WEB_PASEO_IDENTITY' });
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * `--rotate`: a new credential and token, recorded in web.json, under the web lock.
127
+ * @param {string} home @param {string | undefined} project @param {any} settings @param {import('@anhlp/alp-core/log').Logger} log
128
+ */
129
+ async function rotate(home, project, settings, log) {
130
+ const lock = createIntegrationLock(home, 'web');
131
+ const { acquired, lock: held } = await lock.acquire();
132
+ if (!acquired) {
133
+ process.stderr.write(`alp web runs (pid ${held.pid}); it must stop before its token is rotated\n`);
134
+ process.exit(LOCK_HELD);
135
+ }
136
+ let code = 0;
137
+ try {
138
+ await carryPaseoIdentity(home, log);
139
+ const permissions = grantPermissions(settings?.web?.permissions, message => log.warn(message, { code: 'ALP_WEB_PERMISSIONS_IGNORED' }));
140
+ const store = new CredentialStore({ home: webGatewayHome(home), logger: log });
141
+ try {
142
+ const socket = daemonPaths(home).socket;
143
+ const grant = createGrant({ home, store, permissions, project, socket: () => socket, log: message => log.info(message, { code: 'ALP_WEB_GRANT' }) });
144
+ // No previous token to keep: a new credential, and every other one revoked.
145
+ const token = await grant.ensure({});
146
+ await grant.settled();
147
+ await publish(home, { version: WEB_FILE_VERSION, app: 'alp-web', token, credentialId: grant.id });
148
+ log.info(`rotated the token: credential ${grant.id}`, { code: 'ALP_WEB_ROTATED' });
149
+ } finally { store.close(); }
150
+ } catch (error) {
151
+ log.error('alp web could not rotate its token', { code: 'ALP_WEB_ROTATE_FAILED', error });
152
+ code = 1;
153
+ }
154
+ // A failed release leaves the lock (fail closed); the next acquire reclaims it once this pid is gone.
155
+ await lock.release().catch(error => { log.error('web lock not released', { code: 'ALP_LOCK_RELEASE_FAILED', error }); code = 1; });
156
+ process.exit(code);
157
+ }
158
+
159
+ /** The page's Content-Security-Policy on `port`: its own origin only, the socket included. @param {number} port */
160
+ const policy = port => {
161
+ const origins = [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
162
+ return ["default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data:", "font-src 'self'",
163
+ `connect-src 'self' ${origins.map(origin => `http://${origin} ws://${origin}`).join(' ')}`,
164
+ "object-src 'none'", "base-uri 'none'", "form-action 'none'", "frame-ancestors 'none'"].join('; ');
165
+ };
166
+
167
+ async function run() {
168
+ const { values } = parseArgs({ options: { service: { type: 'boolean' }, rotate: { type: 'boolean' }, project: { type: 'string' } }, strict: true });
169
+ const home = alpHome();
170
+ await mkdir(home, { recursive: true, mode: 0o700 });
171
+ if (values.service) serviceLog(home);
172
+ const log = createGatewayLogger();
173
+ const settings = await userSettings(home, log);
174
+ if (values.rotate) return rotate(home, values.project ? path.resolve(values.project) : undefined, settings, log);
175
+ if (settings?.web?.enabled === false) {
176
+ log.info('alp web is disabled by settings ("web.enabled": false)', { code: 'ALP_WEB_DISABLED' });
177
+ process.exit(0);
178
+ }
179
+ const project = values.project ? path.resolve(values.project) : undefined;
180
+
181
+ const lock = createIntegrationLock(home, 'web');
182
+ const { acquired, lock: held } = await lock.acquire();
183
+ if (!acquired) {
184
+ log.info(`alp web already runs (pid ${held.pid})`, { code: 'ALP_LOCK_HELD' });
185
+ process.exit(0);
186
+ }
187
+ // A failed release leaves the lock and its guard in place (fail closed); report it and stop anyway.
188
+ const releaseLock = () => lock.release().catch(error => log.error('web lock not released; alp web stops anyway', { code: 'ALP_LOCK_RELEASE_FAILED', error }));
189
+
190
+ /** @type {Array<() => Promise<unknown>>} */
191
+ const cleanups = [];
192
+ let shuttingDown = false;
193
+ /** Startup, once it began; shutdown waits for it, so nothing it does lands after the lock is released. @type {Promise<unknown>} */
194
+ let startup = Promise.resolve();
195
+ /** @param {number} [code] */
196
+ const shutdown = async (code = 0) => {
197
+ // A later signal or uncaught exception starts no second shutdown; the first always reaches exit.
198
+ if (shuttingDown) return;
199
+ shuttingDown = true;
200
+ try {
201
+ // Startup stops at its next step once shuttingDown is set (each step is bounded).
202
+ await startup.catch(() => {});
203
+ for (const cleanup of cleanups.reverse()) await cleanup().catch(error => log.warn('a shutdown step failed', { code: 'ALP_WEB_SHUTDOWN_STEP', error }));
204
+ await releaseLock();
205
+ } finally { process.exit(code); }
206
+ };
207
+ for (const signal of /** @type {const} */ (['SIGINT', 'SIGTERM'])) process.on(signal, () => void shutdown());
208
+ process.on('uncaughtException', error => { log.error('uncaught exception; alp web stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
209
+
210
+ startup = (async () => {
211
+ const stopDaemon = process.env.ALP_SUPERVISE === '0'
212
+ ? async () => {}
213
+ : superviseDaemon({ home, entry: daemonEntry, by: 'alp web', log: (/** @type {string} */ message) => log.warn(message, { code: 'ALP_DAEMON_SUPERVISION' }) });
214
+ cleanups.push(() => stopDaemon());
215
+
216
+ const permissions = grantPermissions(settings?.web?.permissions, message => log.warn(message, { code: 'ALP_WEB_PERMISSIONS_IGNORED' }));
217
+ if (permissions.includes('terminal.exec')) log.warn(TERMINAL_EXEC_WARNING, { code: 'ALP_WEB_TERMINAL_EXEC' });
218
+ const store = new CredentialStore({ home: webGatewayHome(home), logger: log });
219
+ cleanups.push(async () => store.close());
220
+ const socket = daemonPaths(home).socket;
221
+ const grant = createGrant({
222
+ home, store, permissions, project,
223
+ socket: () => socket,
224
+ log: message => log.info(message, { code: 'ALP_WEB_GRANT' }),
225
+ });
226
+ // A credentials write under way finishes before the process exits (no half-done temporary file).
227
+ cleanups.push(() => grant.settled());
228
+ // Before web.json is first overwritten (publish, below).
229
+ await carryPaseoIdentity(home, log);
230
+ if (shuttingDown) return;
231
+ const token = await grant.ensure(await previousWeb(home));
232
+ if (shuttingDown) return;
233
+ // The registry, if alpd answers already, before the first page asks for it.
234
+ await grant.refresh();
235
+ if (shuttingDown) return;
236
+
237
+ const dir = appDir();
238
+ let bound = 0;
239
+ const serveStatic = createStaticServer({ dir, csp: () => policy(bound), log: message => log.warn(message, { code: 'ALP_WEB_STATIC' }) });
240
+ const base = settings?.web?.port ?? DEFAULT_WEB_PORT;
241
+ for (let attempt = 0; ; attempt++) {
242
+ if (shuttingDown) return;
243
+ const port = base + attempt;
244
+ const config = resolveConfig({
245
+ host: '127.0.0.1',
246
+ port,
247
+ socketPath: socket,
248
+ // The page's own origin, by every loopback name the gateway accepts as Host.
249
+ origins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`],
250
+ // One local user's browser: a stale token in an open tab must not lock that user out.
251
+ // (DEFAULT_LIMITS is frozen, so its type has the literal defaults; any positive number is valid.)
252
+ limits: /** @type {any} */ ({ authFailures: 1_000 }),
253
+ });
254
+ const candidate = createGateway({ config, store, logger: log, version: VERSION, openTransport: () => connectSocket(socket), serveStatic });
255
+ try {
256
+ await candidate.listen();
257
+ bound = port;
258
+ cleanups.push(() => candidate.close());
259
+ break;
260
+ }
261
+ catch (error) {
262
+ await candidate.close().catch(() => {});
263
+ if (/** @type {any} */ (error)?.code !== 'EADDRINUSE' || attempt + 1 >= PORT_TRIES) throw error;
264
+ log.info(`port ${port} is in use; trying ${port + 1}`, { code: 'ALP_WEB_PORT_BUSY' });
265
+ }
266
+ }
267
+ if (shuttingDown) return;
268
+ const url = `http://127.0.0.1:${bound}/`;
269
+ await publish(home, { version: WEB_FILE_VERSION, app: 'alp-web', pid: process.pid, port: bound, url, token, credentialId: grant.id });
270
+ if (shuttingDown) return;
271
+ const timer = setInterval(() => { if (!shuttingDown) void grant.refresh(); }, REFRESH_MS);
272
+ timer.unref();
273
+ cleanups.push(async () => clearInterval(timer));
274
+ // A lock that is no longer ours means another process may own the credentials file: stop writing it.
275
+ if (!(await lock.setReady(true))) throw new Error('the web lock is no longer held by this process');
276
+ log.info(`alp web on ${url}`, { code: 'ALP_WEB_LISTENING' });
277
+ })();
278
+ // A failed start stops the service; shutdown waits for startup, which has settled by now.
279
+ await startup.catch(error => {
280
+ log.error('alp web did not start', { code: 'ALP_WEB_START_FAILED', error });
281
+ void shutdown(1);
282
+ });
283
+ }
284
+
285
+ await run();
@@ -0,0 +1,144 @@
1
+ // @ts-check
2
+ import { createReadStream } from 'node:fs';
3
+ import { realpath, stat } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * The static side of `alp web` (docs/alp/web.md): the built apps/web files, served through the
8
+ * gateway's `serveStatic` hook on the gateway's own loopback listener. The gateway has refused an
9
+ * unknown Host (421) before a request reaches this, and hands over GET and HEAD only, with the RAW
10
+ * request target. This module normalizes that target itself and never serves a file whose real
11
+ * path lies outside the app directory:
12
+ * - the target must be origin-form (`/...`); it is parsed with `new URL` against a fixed origin,
13
+ * so `//host/x` stays a path and dot segments (also `%2e%2e`) are resolved by the URL parser;
14
+ * - each path segment is percent-decoded exactly once; a decoded segment holding `/`, `\`, `:`,
15
+ * NUL, a control character, or that is empty, `.`, `..` or starts with `.` is refused (400);
16
+ * - a backslash anywhere in the raw target or its decoded form is refused (400);
17
+ * - the file's realpath must lie under the app directory's realpath (no symlink escapes), else 404.
18
+ * Paths without an extension that name no file get index.html (the app's own routes); a missing
19
+ * file with an extension is a 404. index.html is never cached; files under /assets/ are named by
20
+ * content and immutable.
21
+ */
22
+
23
+ /** @type {Record<string, string>} */
24
+ const TYPES = {
25
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
26
+ '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8',
27
+ '.txt': 'text/plain; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
28
+ '.ico': 'image/x-icon', '.gif': 'image/gif', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2',
29
+ '.ttf': 'font/ttf', '.otf': 'font/otf', '.wasm': 'application/wasm', '.webmanifest': 'application/manifest+json',
30
+ };
31
+
32
+ // eslint-disable-next-line no-control-regex
33
+ // `:` names a drive or an NTFS stream on Windows; the built app has no such file anywhere.
34
+ const FORBIDDEN_IN_SEGMENT = /[\u0000-\u001f\u007f/\\:]/;
35
+
36
+ /** What a page without the built app says. @param {string} dir */
37
+ const missingPage = dir => `<!doctype html><meta charset="utf-8"><title>ALP</title><body style="font:16px system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem">
38
+ <h1>ALP web is not built</h1><p>The web app's files are missing from <code>${dir.replace(/[&<>"]/g, char => `&#${char.charCodeAt(0)};`)}</code>. Build them from a checkout with <code>node scripts/build-workspace.mjs cli</code> (or <code>node scripts/build-alp-web.mjs</code>), or install ALP from npm, which carries them. The gateway on this address keeps running.</p>`;
39
+
40
+ /**
41
+ * The path segments a raw request target names, each decoded once, or a refusal.
42
+ * @param {string | undefined} raw
43
+ * @returns {{ segments: string[] } | { status: 400 }}
44
+ */
45
+ export function parseTarget(raw) {
46
+ if (typeof raw !== 'string' || !raw.startsWith('/') || raw.includes('\\') || /%5c/i.test(raw) || raw.includes('\0')) return { status: 400 };
47
+ let url;
48
+ // Never `new URL(raw, base)`: a raw `//host/x` would name another host. The fixed origin keeps it a path.
49
+ try { url = new URL(`http://alp-web.invalid${raw}`); } catch { return { status: 400 }; }
50
+ if (url.host !== 'alp-web.invalid') return { status: 400 };
51
+ const parts = url.pathname.split('/').slice(1);
52
+ /** @type {string[]} */
53
+ const segments = [];
54
+ for (let index = 0; index < parts.length; index++) {
55
+ const part = parts[index];
56
+ // A trailing slash (`/` itself, or `/route/`) is the directory's index; any other empty segment is `//`.
57
+ if (part === '' && index === parts.length - 1) break;
58
+ let segment;
59
+ try { segment = decodeURIComponent(part); } catch { return { status: 400 }; }
60
+ if (!segment || segment === '.' || segment === '..' || segment.startsWith('.') || FORBIDDEN_IN_SEGMENT.test(segment)) return { status: 400 };
61
+ segments.push(segment);
62
+ }
63
+ return { segments };
64
+ }
65
+
66
+ /** @param {string} file */
67
+ const isFile = file => stat(file).then(info => info.isFile(), () => false);
68
+
69
+ /**
70
+ * @param {{ dir: string, csp: () => string, log?: (message: string) => void }} options
71
+ * `dir` holds the built app (index.html and assets/); `csp` is the Content-Security-Policy for the
72
+ * current listener (it names the bound port).
73
+ */
74
+ export function createStaticServer({ dir, csp, log = () => {} }) {
75
+ const configured = path.resolve(dir);
76
+ /** @type {Promise<string | undefined> | undefined} */
77
+ let root;
78
+ /** The app directory's real path while it holds an index.html; checked again after a miss. */
79
+ const appRoot = async () => {
80
+ const found = await (root ??= realpath(configured).then(async real => (await isFile(path.join(real, 'index.html')) ? real : undefined), () => undefined));
81
+ if (!found) root = undefined;
82
+ return found;
83
+ };
84
+
85
+ /** @param {string} type @param {string} cache */
86
+ const headers = (type, cache) => ({
87
+ 'content-type': type,
88
+ 'cache-control': cache,
89
+ 'x-content-type-options': 'nosniff',
90
+ 'x-frame-options': 'DENY',
91
+ 'referrer-policy': 'no-referrer',
92
+ 'cross-origin-opener-policy': 'same-origin',
93
+ 'cross-origin-resource-policy': 'same-origin',
94
+ 'content-security-policy': csp(),
95
+ });
96
+
97
+ /** @param {import('node:http').IncomingMessage} request @param {import('node:http').ServerResponse} response @param {number} status @param {string} text */
98
+ function plain(request, response, status, text) {
99
+ response.writeHead(status, { ...headers('text/plain; charset=utf-8', 'no-store'), 'content-length': String(Buffer.byteLength(text)) });
100
+ response.end(request.method === 'HEAD' ? undefined : text);
101
+ }
102
+
103
+ /** @param {string} base @param {string[]} segments @returns {Promise<string | undefined>} a regular file under `base`, by realpath */
104
+ async function contained(base, segments) {
105
+ const candidate = path.join(base, ...segments);
106
+ let real;
107
+ try { real = await realpath(candidate); } catch { return undefined; }
108
+ if (real !== base && !real.startsWith(base + path.sep)) return undefined;
109
+ return (await isFile(real)) ? real : undefined;
110
+ }
111
+
112
+ /**
113
+ * The gateway's serveStatic hook.
114
+ * @param {import('node:http').IncomingMessage} request @param {import('node:http').ServerResponse} response
115
+ */
116
+ return async function serveStatic(request, response) {
117
+ const base = await appRoot();
118
+ if (!base) {
119
+ const page = missingPage(configured);
120
+ response.writeHead(503, { ...headers('text/html; charset=utf-8', 'no-store'), 'content-length': String(Buffer.byteLength(page)) });
121
+ response.end(request.method === 'HEAD' ? undefined : page);
122
+ return true;
123
+ }
124
+ const target = parseTarget(request.url);
125
+ if ('status' in target) { plain(request, response, 400, 'Bad request'); return true; }
126
+ const { segments } = target;
127
+ let file = segments.length ? await contained(base, segments) : undefined;
128
+ if (!file) {
129
+ const last = segments.at(-1) ?? '';
130
+ if (path.extname(last)) { plain(request, response, 404, 'Not found'); return true; }
131
+ // The app's own routes (and `/`): its index page.
132
+ file = await contained(base, ['index.html']);
133
+ if (!file) { plain(request, response, 404, 'Not found'); return true; }
134
+ }
135
+ const relative = path.relative(base, file).split(path.sep).join('/');
136
+ const type = TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream';
137
+ const cache = relative === 'index.html' ? 'no-cache' : relative.startsWith('assets/') ? 'public, max-age=31536000, immutable' : 'no-cache';
138
+ const { size } = await stat(file);
139
+ response.writeHead(200, { ...headers(type, cache), 'content-length': String(size) });
140
+ if (request.method === 'HEAD') { response.end(); return true; }
141
+ createReadStream(file).on('error', error => { log(`could not read ${relative}: ${error.message}`); response.destroy(); }).pipe(response);
142
+ return true;
143
+ };
144
+ }
@@ -0,0 +1,143 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { lstat, readFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { promisify } from 'node:util';
7
+ import { bootTime, readLock } from '@anhlp/alp-client/index';
8
+ import { distributionEntry } from './paths.js';
9
+
10
+ /**
11
+ * The CLI's side of alp-web (packages/cli/src/web), the service behind `alp web`: where it is, which
12
+ * process owns its lock, and how to stop that process safely.
13
+ *
14
+ * Only a process proven to be the one that took `integrations/web.lock` is ever signalled, and only
15
+ * with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and `web.json` name the same pid, both files are the user's, the lock is
16
+ * from this boot, the pid answers signal 0 (so it is the user's own process), and that process
17
+ * started no later than the lock was written (so the pid was not reused). Anything else is reported
18
+ * and left alone. A stopped owner releases the lock; one that died holding it leaves it to the next
19
+ * acquire, which reclaims it only on proof of death (the integration lock protocol, t-e148).
20
+ */
21
+
22
+ const execFileAsync = promisify(execFile);
23
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
24
+
25
+ /** The alp-web service script beside this CLI; a clear error when this CLI was built without it. */
26
+ export function alpWebEntry() {
27
+ const entry = fileURLToPath(distributionEntry('alp-web.js'));
28
+ if (!existsSync(entry)) throw new Error(`alp web is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
29
+ return entry;
30
+ }
31
+
32
+ const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
33
+
34
+ /** When `pid` started, in ms since the epoch (to about a second), or undefined when ps cannot say. @param {number} pid */
35
+ async function processStart(pid) {
36
+ try {
37
+ const { stdout } = await execFileAsync('ps', ['-o', 'etime=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
38
+ // [[dd-]hh:]mm:ss
39
+ const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
40
+ if (!match) return undefined;
41
+ const [, days = '0', hours = '0', minutes, seconds] = match;
42
+ const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
43
+ return Date.now() - elapsed * 1000;
44
+ } catch { return undefined; }
45
+ }
46
+
47
+ /**
48
+ * The process that owns alp web's lock, if it is proven safe to stop; else why not. `kind` says
49
+ * whether waiting can help: `transient` (an owner still starting has not published web.json yet),
50
+ * `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
51
+ * `unknown` (it cannot be proven either way, for example without ps or on Windows).
52
+ *
53
+ * The reuse proof compares the lock's wall-clock `startedAt` with the process's start from ps: a
54
+ * wall clock stepped back by more than two seconds after the lock was written could make a reused
55
+ * pid look older than the lock. A step forward only refuses.
56
+ * @param {string} home
57
+ * @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
58
+ */
59
+ export async function webOwner(home) {
60
+ const lockFile = path.join(home, 'integrations', 'web.lock');
61
+ const infoFile = path.join(home, 'web.json');
62
+ let lock, lockInfo;
63
+ try { lockInfo = await lstat(lockFile); lock = await readJson(lockFile); } catch { return { reason: `${lockFile} is missing or unreadable`, alive: false }; }
64
+ if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== 'number' || !Number.isFinite(Date.parse(lock.startedAt))) {
65
+ return { reason: `${lockFile} is not a complete integration lock`, alive: false };
66
+ }
67
+ const { pid } = lock;
68
+ try { process.kill(pid, 0); } catch (error) {
69
+ if (error?.code === 'ESRCH') return { reason: `its pid ${pid} has exited`, alive: false };
70
+ if (error?.code === 'EPERM') return { reason: `pid ${pid} belongs to another user`, alive: true, kind: 'foreign' };
71
+ return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: 'unknown' };
72
+ }
73
+ const refuse = (/** @type {string} */ reason, /** @type {'transient' | 'foreign' | 'unknown'} */ kind) => ({ reason, alive: true, kind });
74
+ if (process.platform === 'win32') return refuse('alp does not stop it on Windows', 'unknown');
75
+ const uid = process.getuid?.();
76
+ if (lockInfo.uid !== uid) return refuse('its lock is not yours', 'foreign');
77
+ if (Math.abs(lock.bootTime - bootTime()) > 30) return refuse('its lock is from another boot', 'foreign');
78
+ if (pid === process.pid || pid === (await readLock(home).catch(() => undefined))?.pid) return refuse(`pid ${pid} is not an integration`, 'foreign');
79
+ const started = await processStart(pid);
80
+ if (started === undefined) return refuse(`the start time of pid ${pid} is unknown`, 'unknown');
81
+ // ps rounds the elapsed time down, so `started` may be up to a second late; allow two.
82
+ if (started > Date.parse(lock.startedAt) + 2_000) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, 'foreign');
83
+ // The lock's owner; web.json must name it too (an owner still starting has not written it yet).
84
+ let info, infoStat;
85
+ try { infoStat = await lstat(infoFile); info = await readJson(infoFile); } catch { return refuse(`${infoFile} is missing or unreadable`, 'transient'); }
86
+ if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, 'transient');
87
+ if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, 'foreign');
88
+ return { pid, app: info.app };
89
+ }
90
+
91
+ /**
92
+ * Sends SIGTERM to a proven owner and waits for it to exit.
93
+ * @param {number} pid @param {string} what @param {number} [timeoutMs]
94
+ */
95
+ async function terminate(pid, what, timeoutMs = 20_000) {
96
+ try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error?.code === 'ESRCH') return; throw error; }
97
+ const deadline = Date.now() + timeoutMs;
98
+ while (Date.now() < deadline) {
99
+ try { process.kill(pid, 0); } catch (error) { if (error?.code === 'ESRCH') return; }
100
+ await sleep(100);
101
+ }
102
+ throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1000} s of SIGTERM; stop it, then run the command again`);
103
+ }
104
+
105
+ /** Whether `web.json` is alp-web's own (the pre-rename Paseo integration wrote it without `app`). */
106
+ const isAlpWeb = app => app === 'alp-web';
107
+ const PASEO_BEFORE_RENAME = 'The Paseo integration from before its rename';
108
+
109
+ /**
110
+ * Stops the Paseo integration from before its rename when it still runs as integration `web` (its
111
+ * web.json has no `app: 'alp-web'`), so alp-web can take the lock and web.port. Returns the pid it
112
+ * stopped. A process that cannot be proven to be that integration is left alone.
113
+ * @param {string} home
114
+ */
115
+ export async function stopPreRenamePaseo(home) {
116
+ const owner = await webOwner(home);
117
+ if (!('pid' in owner) || isAlpWeb(owner.app)) return undefined;
118
+ await terminate(owner.pid, PASEO_BEFORE_RENAME);
119
+ return owner.pid;
120
+ }
121
+
122
+ /**
123
+ * Stops whatever runs as integration `web` (alp-web, or the Paseo integration from before its
124
+ * rename), waiting up to `timeoutMs` for a starting owner to publish what proves it. Resolves once
125
+ * no live process owns the lock; refuses at once an owner that is foreign or cannot be proven.
126
+ * @param {string} home @param {number} [timeoutMs]
127
+ */
128
+ export async function stopWebService(home, timeoutMs = 30_000) {
129
+ const deadline = Date.now() + timeoutMs;
130
+ for (;;) {
131
+ const owner = await webOwner(home);
132
+ if ('pid' in owner) { await terminate(owner.pid, isAlpWeb(owner.app) ? 'alp web' : PASEO_BEFORE_RENAME); return owner.pid; }
133
+ if (!owner.alive) return undefined;
134
+ // Only an owner still starting can become provable; waiting changes nothing else.
135
+ if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home)} (${owner.reason}); stop it, then run the command again`);
136
+ await sleep(200);
137
+ }
138
+ }
139
+
140
+ /** The opening of the message for a web lock held by a process alp would not stop. @param {string} home */
141
+ export function refusal(home) {
142
+ return `${path.join(home, 'integrations', 'web.lock')} is held by a process that alp cannot prove is alp web or the Paseo integration from before its rename, so it was left running`;
143
+ }