@anhlp/alp-cli 0.0.1-beta.3 → 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 (43) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +25 -0
  2. package/dist/acp/main.js +1 -1
  3. package/dist/acp.js +37 -4
  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 +10350 -3346
  17. package/dist/backup.js +2 -2
  18. package/dist/build-manifest.json +99 -1
  19. package/dist/cli.js +4 -2
  20. package/dist/interfaces.d.ts +9 -1
  21. package/dist/interfaces.js +99 -39
  22. package/dist/schedules.d.ts +2 -0
  23. package/dist/schedules.js +45 -0
  24. package/dist/sessions.d.ts +3 -1
  25. package/dist/sessions.js +22 -11
  26. package/dist/terminal.d.ts +8 -0
  27. package/dist/terminal.js +79 -0
  28. package/dist/usage.d.ts +1 -1
  29. package/dist/usage.js +8 -2
  30. package/dist/web-service.d.ts +38 -0
  31. package/dist/web-service.js +119 -0
  32. package/package.json +10 -4
  33. package/src/backup.js +1 -1
  34. package/src/cli.js +3 -1
  35. package/src/interfaces.js +136 -31
  36. package/src/schedules.js +38 -0
  37. package/src/sessions.js +21 -11
  38. package/src/terminal.js +77 -0
  39. package/src/usage.js +8 -2
  40. package/src/web/grant.js +204 -0
  41. package/src/web/main.js +285 -0
  42. package/src/web/serve.js +144 -0
  43. package/src/web-service.js +143 -0
@@ -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
+ }