@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,77 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { alpHome } from '@anhlp/alp-client/index';
6
+ import { UsageError } from './usage.js';
7
+
8
+ /**
9
+ * `alp terminal allow|deny|status`: the host owner's switch for remote terminals
10
+ * (docs/protocol/alp-json-rpc-v1.md §12.10, issue #121 H). It lives in $ALP_HOME/terminal.json, a
11
+ * file only this user may read or write; no RPC changes it and no backup carries it.
12
+ */
13
+ export const TERMINAL_WARNING = (user = os.userInfo().username) => [
14
+ `A remote terminal runs a real shell on this computer as ${user}, with that account's full access:`,
15
+ 'every file it can read or write, any program, and the network.',
16
+ 'A workspace only picks the directory the shell starts in. It is NOT a sandbox.',
17
+ 'Only gateway credentials that hold the terminal.exec permission can open one (never a default);',
18
+ 'Paseo app devices paired with this host only after alp terminal allow --paseo.',
19
+ ].join('\n');
20
+
21
+ const file = home => path.join(home, 'terminal.json');
22
+
23
+ async function read(home) {
24
+ const info = await lstat(file(home)).catch(() => undefined);
25
+ if (!info) return { exists: false, value: undefined, private: true };
26
+ const own = !process.getuid || info.uid === process.getuid();
27
+ const value = info.isFile() ? await readFile(file(home), 'utf8').then(JSON.parse, () => undefined) : undefined;
28
+ return { exists: true, value, private: info.isFile() && own && !(info.mode & 0o077) };
29
+ }
30
+
31
+ async function write(home, value) {
32
+ await mkdir(home, { recursive: true, mode: 0o700 });
33
+ const temporary = `${file(home)}.${randomUUID().slice(0, 8)}.tmp`;
34
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
35
+ await chmod(temporary, 0o600);
36
+ await rename(temporary, file(home)).catch(async error => { await rm(temporary, { force: true }); throw error; });
37
+ }
38
+
39
+ export async function terminalCommand(args, { home = alpHome(), out = console.log } = {}) {
40
+ const [action, ...rest] = args;
41
+ const json = rest.includes('--json');
42
+ const current = await read(home);
43
+ const limits = current.value && typeof current.value.limits === 'object' && current.value.limits ? { limits: current.value.limits } : {};
44
+ const paseo = rest.includes('--paseo');
45
+ const paseoBefore = current.private && current.value?.allowPaseoTerminal === true;
46
+ if (action === 'allow') {
47
+ if (!rest.includes('--yes')) {
48
+ out(`${TERMINAL_WARNING()}\n\nRun again with --yes to allow remote terminals on this host.`);
49
+ process.exitCode = 1;
50
+ return;
51
+ }
52
+ const allowPaseoTerminal = paseo || paseoBefore;
53
+ await write(home, { version: 1, allowRemoteTerminal: true, ...(allowPaseoTerminal ? { allowPaseoTerminal: true } : {}), ...limits });
54
+ out(json ? JSON.stringify({ allowRemoteTerminal: true, allowPaseoTerminal }) : `${TERMINAL_WARNING()}\n\nRemote terminals are allowed on this host (${file(home)})${allowPaseoTerminal ? ', also for every Paseo app device paired with it' : ''}. alp terminal deny turns them off and ends every open one.`);
55
+ return;
56
+ }
57
+ if (action === 'deny') {
58
+ if (paseo) {
59
+ const allowed = current.private && current.value?.allowRemoteTerminal === true;
60
+ await write(home, { version: 1, allowRemoteTerminal: allowed, ...limits });
61
+ out(json ? JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal: false }) : 'Paseo app devices can no longer open terminals on this host; the bridge ends the terminals it holds.');
62
+ return;
63
+ }
64
+ await write(home, { version: 1, allowRemoteTerminal: false, ...limits });
65
+ out(json ? JSON.stringify({ allowRemoteTerminal: false, allowPaseoTerminal: false }) : 'Remote terminals are off on this host; alpd ends every open terminal within 5 seconds.');
66
+ return;
67
+ }
68
+ if (action === 'status') {
69
+ const allowed = current.private && current.value?.version === 1 && current.value.allowRemoteTerminal === true;
70
+ const allowPaseoTerminal = allowed && current.value.allowPaseoTerminal === true;
71
+ const problem = current.exists && !current.private ? `${file(home)} is not a private file of this user, so terminals stay off` : undefined;
72
+ if (json) out(JSON.stringify({ allowRemoteTerminal: allowed, allowPaseoTerminal, ...limits, ...(problem ? { problem } : {}) }));
73
+ else out([`Remote terminals: ${allowed ? 'allowed' : 'off'}${allowPaseoTerminal ? ' (also for paired Paseo app devices)' : ''}`, ...(problem ? [problem] : []), ...(allowed ? ['', TERMINAL_WARNING()] : [])].join('\n'));
74
+ return;
75
+ }
76
+ throw new UsageError();
77
+ }
package/src/usage.js CHANGED
@@ -10,18 +10,24 @@ const USAGE = `Usage:
10
10
  alp daemon status [--json] liveness and readiness; exit 0 ready, 3 not running, 4 not ready
11
11
  alp daemon <install|uninstall> run alpd as a login service that restarts after a crash
12
12
  alp acp serve ALP to an editor (Zed, JetBrains) over the Agent Client Protocol on stdio
13
- alp web [--print] open the local web app alpd serves; --print only prints its address
13
+ alp web [--print] open the ALP web app on this machine (alp-web, loopback); --print only prints its address
14
+ alp web rotate give alp web a new token: open pages lose access; prints the new address
14
15
  alp web pair [--on|--off] the link that pairs Paseo's app on another device through the relay; --on or --off turns the relay on or off
16
+ alp terminal <allow [--paseo] --yes|deny [--paseo]|status> [--json] remote terminals (a shell as you on this host; a workspace is not a sandbox), off by default
15
17
  alp doctor [--project DIR] [--fix] [--json] check this machine and project; --fix repairs what is safe to
16
18
  alp backup [-o FILE] [--project DIR]... [--no-projects] [--stop] [--json] sessions, settings, library and tasks in one file
17
19
  alp backup verify <file> [--json] | alp backup list [--json]
18
20
  alp restore <file> [--home-only] [--dry-run] [--stop] [--replace-newer] [--json] checks the whole backup first; keeps what it replaces
19
21
  alpd must be stopped for both; --stop stops it and starts it again after
20
22
  alp run [--agent A] [--team pho|cafe|ID] [--model M] [--mode read-only|workspace-write|full-access] [--thinking T] [--project DIR] [--json] <prompt>
23
+ alp schedule create --session ID --at ISO_WITH_OFFSET --prompt TEXT [--project DIR] [--json]
24
+ alp schedule list [--status pending|delivered|failed|cancelled] [--project DIR] [--json]
25
+ alp schedule <show|cancel> ID [--project DIR] [--json] one-shot wake; timer gates only unblock tasks
21
26
  alp ps [--all]
22
27
  alp top [session] [--once]
23
28
  alp attach <session> [--json]
24
- alp send <session> [--json] <text>
29
+ alp send <session> [--prompt] [--json] <text>
30
+ child default: user mail; --prompt: explicit new prompt to a live root or child
25
31
  alp questions [--json]
26
32
  alp answer <question> <text> | alp answer <question> --dismiss [--reason R]
27
33
  alp log <session> [--json]
@@ -0,0 +1,204 @@
1
+ // @ts-check
2
+ import { mkdir, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { assertPrivateDirectory, connect } from '@anhlp/alp-client/index';
5
+ import { createCredential, listCredentials, revokeCredential, updateCredential } from '@anhlp/alp-gateway';
6
+ import { DEFAULT_PERMISSIONS, PERMISSIONS } from '@anhlp/alp-gateway/policy';
7
+
8
+ /**
9
+ * The one gateway credential `alp web` hands the browser (docs/alp/web.md): its token travels in
10
+ * the URL the CLI opens, so it is a real `alpgw1.*` credential with the least the app needs.
11
+ *
12
+ * Single writer: the credentials live in `<home>/web/credentials.json`, a file of alp-web's own
13
+ * (not the standalone gateway's `<home>/gateway`). Only the process holding the `web` integration
14
+ * lock writes it, and inside that process every write goes through one queue (`serial`), so no
15
+ * two writes interleave their read-modify-write. Another tool must not write it while the service
16
+ * runs. Because the file is alp-web's own, `alp-gateway credential list/revoke` (which read
17
+ * `<home>/gateway`) do not see this credential: `alp web rotate` is the way to replace or end it.
18
+ * The gateway's own checks apply to this path as to its default one: the directory must be the
19
+ * user's and private (0700, checked on every start, not only on a write) and the file 0600 and the
20
+ * user's, else nothing is read or written and the service does not start.
21
+ *
22
+ * Grant: permissions are DEFAULT_PERMISSIONS + workspace.write, plus `web.permissions` from the
23
+ * user's settings when every entry is a permission a credential may hold (with any unknown entry
24
+ * the whole list is ignored, with a warning naming it, so the grant stays the default). Workspaces are alpd's project
25
+ * registry (live projects) ∪ the `--project` directory the caller named; with none, a private
26
+ * empty directory stands in (a credential needs one workspace, and it grants nothing).
27
+ */
28
+
29
+ export const LABEL = 'alp web (this machine)';
30
+ export const BASE_PERMISSIONS = Object.freeze([...DEFAULT_PERMISSIONS, 'workspace.write']);
31
+
32
+ /** Where alp-web keeps its credentials. @param {string} home */
33
+ export const webGatewayHome = home => path.join(home, 'web');
34
+
35
+ /**
36
+ * The permissions to grant: the base set and, when valid, `web.permissions`.
37
+ * @param {unknown} extra the `web.permissions` setting
38
+ * @param {(message: string) => void} [warn]
39
+ */
40
+ export function grantPermissions(extra, warn = () => {}) {
41
+ const wanted = new Set(BASE_PERMISSIONS);
42
+ if (extra !== undefined) {
43
+ const unknown = Array.isArray(extra) ? extra.filter(entry => typeof entry !== 'string' || !PERMISSIONS.includes(entry)) : [extra];
44
+ if (!unknown.length) for (const entry of /** @type {string[]} */ (extra)) wanted.add(entry);
45
+ else warn(`ignoring web.permissions: ${unknown.map(entry => JSON.stringify(entry)).join(', ')} ${unknown.length === 1 ? 'is not a permission' : 'are not permissions'} a credential may hold (${PERMISSIONS.join(', ')}); the default grant (${BASE_PERMISSIONS.join(', ')}) is in use`);
46
+ }
47
+ // As the gateway stores them: a write permission holds its read (credentials.js checkPermissions).
48
+ if (wanted.has('session.write')) wanted.add('session.read');
49
+ if (wanted.has('project.write') || wanted.has('library.write')) wanted.add('project.read');
50
+ return PERMISSIONS.filter(permission => wanted.has(permission));
51
+ }
52
+
53
+ /**
54
+ * Existing directories among `paths`, as the gateway stores workspaces: absolute and normalized as
55
+ * given, one per real path (the first wins). Anything else is dropped, never resolved further.
56
+ * @param {Iterable<unknown>} paths
57
+ * @returns {Promise<Array<{ path: string, canonical: string }>>}
58
+ */
59
+ export async function existingWorkspaces(paths) {
60
+ /** @type {Array<{ path: string, canonical: string }>} */
61
+ const found = [];
62
+ for (const entry of paths) {
63
+ if (typeof entry !== 'string' || !path.isAbsolute(entry) || path.resolve(entry) !== entry || entry.includes('\0')) continue;
64
+ const canonical = await realpath(entry).catch(() => undefined);
65
+ if (!canonical || !(await stat(canonical).then(info => info.isDirectory(), () => false))) continue;
66
+ if (!found.some(known => known.canonical === canonical)) found.push({ path: entry, canonical });
67
+ }
68
+ return found;
69
+ }
70
+
71
+ /**
72
+ * The live project roots in alpd's registry, through its socket; undefined when alpd cannot answer
73
+ * within `timeoutMs` (the grant is then left as it is).
74
+ * @param {string | undefined} socket @param {{ timeoutMs?: number }} [options]
75
+ */
76
+ export async function registryRoots(socket, { timeoutMs = 3_000 } = {}) {
77
+ if (!socket) return undefined;
78
+ /** @type {any} */
79
+ let client;
80
+ let finished = false;
81
+ let timer;
82
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), timeoutMs); });
83
+ // A connection that opens after the answer was given up on is closed at once.
84
+ const opened = (/** @type {any} */ value) => { if (finished) { try { value.close(); } catch {} } else client = value; };
85
+ try { return await Promise.race([listRoots(socket, opened), late]); }
86
+ finally { finished = true; clearTimeout(timer); try { client?.close(); } catch {} }
87
+ }
88
+
89
+ /** @param {string} socket @param {(client: any) => void} opened */
90
+ async function listRoots(socket, opened) {
91
+ let client;
92
+ try {
93
+ client = await connect(socket, { name: 'alp-web', version: '1' });
94
+ opened(client);
95
+ /** @type {string[]} */
96
+ const roots = [];
97
+ let cursor;
98
+ for (let page = 0; page < 100; page++) {
99
+ const result = /** @type {any} */ (await client.request('project.list', { limit: 500, ...(cursor ? { cursor } : {}) }));
100
+ for (const project of result?.projects ?? []) if (typeof project?.root === 'string' && !project.removedAt) roots.push(project.root);
101
+ cursor = result?.nextCursor;
102
+ if (!cursor) return roots;
103
+ }
104
+ return undefined;
105
+ } catch { return undefined; } finally { try { client?.close(); } catch {} }
106
+ }
107
+
108
+
109
+ /** @param {Array<{ path: string, canonical: string }>} a @param {Array<{ path: string, canonical: string }>} b */
110
+ const sameWorkspaces = (a, b) => {
111
+ const key = (/** @type {Array<{ path: string, canonical: string }>} */ list) => JSON.stringify(list.map(entry => [entry.path, entry.canonical]).sort());
112
+ return key(a) === key(b);
113
+ };
114
+ /** @param {string[]} a @param {string[]} b */
115
+ const samePermissions = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
116
+
117
+ /**
118
+ * Owns alp-web's credential while this process holds the web lock.
119
+ * @param {{
120
+ * home: string,
121
+ * store: import('@anhlp/alp-gateway').CredentialStore,
122
+ * permissions: string[],
123
+ * project?: string,
124
+ * socket: () => string | undefined,
125
+ * log?: (message: string) => void,
126
+ * }} options
127
+ */
128
+ export function createGrant({ home, store, permissions, project, socket, log = () => {} }) {
129
+ const credentialsHome = webGatewayHome(home);
130
+ const placeholder = path.join(credentialsHome, 'no-project');
131
+ /** @type {Promise<unknown>} */
132
+ let tail = Promise.resolve();
133
+ /** One credentials write at a time, in order. @template T @param {() => Promise<T>} run @returns {Promise<T>} */
134
+ const serial = run => { const result = tail.then(run); tail = result.catch(() => {}); return result; };
135
+ /** @type {string | undefined} */
136
+ let id;
137
+ /** The last registry answer, kept while alpd is down. @type {string[]} */
138
+ let known = [];
139
+ /** The refresh under way, if any: a timer tick while one runs joins it rather than queueing another. @type {Promise<boolean> | undefined} */
140
+ let refreshing;
141
+
142
+ /** The workspaces to grant now. */
143
+ async function wanted() {
144
+ const roots = await registryRoots(socket());
145
+ if (roots) known = roots;
146
+ const found = await existingWorkspaces([...(project ? [project] : []), ...known]);
147
+ if (found.length) return found;
148
+ await mkdir(placeholder, { recursive: true, mode: 0o700 });
149
+ return existingWorkspaces([placeholder]);
150
+ }
151
+
152
+ return {
153
+ get id() { return id; },
154
+ /** Resolves once every queued credentials write has finished. */
155
+ settled: () => tail.then(() => undefined),
156
+ /**
157
+ * Reuses the credential of `token` when it still verifies, else creates one; revokes every other
158
+ * live credential in alp-web's file. Returns the token to publish.
159
+ * @param {{ token?: unknown, credentialId?: unknown }} previous what web.json held
160
+ */
161
+ ensure: previous => serial(async () => {
162
+ // Throws unless the directory is the user's and private; creates it (0700) on the first start.
163
+ await assertPrivateDirectory(credentialsHome, { create: true }).catch(error => {
164
+ throw new Error(`alp web keeps its credentials in ${credentialsHome}, which must be a directory owned by you with private permissions (0700); run chmod 700 on it (${error?.message ?? error})`, { cause: error });
165
+ });
166
+ await store.reload();
167
+ const reused = typeof previous.token === 'string' ? store.verify(previous.token) : undefined;
168
+ let token;
169
+ if (reused && reused.id === previous.credentialId) { id = reused.id; token = /** @type {string} */ (previous.token); }
170
+ else {
171
+ const created = await createCredential(credentialsHome, { label: LABEL, workspaces: (await wanted()).map(entry => entry.path), permissions });
172
+ id = created.credential.id;
173
+ token = created.token;
174
+ log(`created credential ${id}`);
175
+ }
176
+ for (const entry of await listCredentials(credentialsHome)) {
177
+ if (entry.id !== id && !entry.revokedAt) { await revokeCredential(credentialsHome, entry.id); log(`revoked stale credential ${entry.id}`); }
178
+ }
179
+ await store.reload();
180
+ return token;
181
+ }),
182
+ /** Brings the credential's workspaces and permissions in line; keeps its token. Never throws. */
183
+ refresh: () => refreshing ??= serial(async () => {
184
+ if (!id) return false;
185
+ try {
186
+ const current = (await listCredentials(credentialsHome)).find(entry => entry.id === id);
187
+ if (!current || current.revokedAt) return false;
188
+ const workspaces = await wanted();
189
+ const update = {
190
+ ...(sameWorkspaces(current.workspaces, workspaces) ? {} : { workspaces: workspaces.map(entry => entry.path) }),
191
+ ...(samePermissions(current.permissions, permissions) ? {} : { permissions }),
192
+ };
193
+ if (!Object.keys(update).length) return false;
194
+ await updateCredential(credentialsHome, id, update);
195
+ await store.reload();
196
+ log(`updated the grant of ${id}: ${workspaces.length} workspace(s)`);
197
+ return true;
198
+ } catch (error) {
199
+ log(`grant not refreshed: ${/** @type {any} */ (error)?.message ?? error}`);
200
+ return false;
201
+ }
202
+ }).finally(() => { refreshing = undefined; }),
203
+ };
204
+ }
@@ -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();