@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,38 @@
1
+ import path from 'node:path';
2
+ import { parseArgs } from 'node:util';
3
+ import { running } from './daemon.js';
4
+ import { UsageError } from './usage.js';
5
+
6
+ /** One-shot continuations of an existing root session; timestamps need an explicit offset. */
7
+ export async function scheduleCommand(args) {
8
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
9
+ project: { type: 'string' }, session: { type: 'string' }, at: { type: 'string' },
10
+ prompt: { type: 'string' }, status: { type: 'string' }, json: { type: 'boolean' },
11
+ } });
12
+ const [action, id, ...extra] = positionals;
13
+ if (!['create', 'list', 'show', 'cancel'].includes(action) || extra.length) throw new UsageError();
14
+ if ((action === 'show' || action === 'cancel') ? !id : !!id) throw new UsageError();
15
+ if (action !== 'create' && (values.session || values.at || values.prompt)) throw new UsageError();
16
+ if (action !== 'list' && values.status) throw new UsageError();
17
+ if (action === 'create' && (!values.session || !values.prompt?.trim() ||
18
+ !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.test(values.at ?? '') ||
19
+ !Number.isFinite(Date.parse(values.at)))) throw new Error('create needs --session, --prompt and --at ISO timestamp with Z or a UTC offset (for example 2026-10-20T16:00:00+07:00)');
20
+ const projectRoot = path.resolve(values.project ?? process.cwd());
21
+ const params = action === 'create'
22
+ ? { projectRoot, sessionId: values.session, dueAt: values.at, prompt: values.prompt }
23
+ : { projectRoot, ...(id ? { id } : {}), ...(values.status ? { status: values.status } : {}) };
24
+ const client = await running();
25
+ try {
26
+ const result = await client.request(`schedule.${action === 'show' ? 'get' : action}`, params);
27
+ if (values.json) { console.log(JSON.stringify(result)); return; }
28
+ const jobs = result.jobs ?? [result.job];
29
+ if (!jobs.length) console.log('No scheduled continuations');
30
+ for (const job of jobs) {
31
+ console.log(`${job.id} ${job.status} ${job.dueAt} session ${job.sessionId}`);
32
+ console.log(` ${job.prompt}`);
33
+ if (job.attemptedAt) console.log(` attempted ${job.attemptedAt}; attempts ${job.attempts}; late ${job.lateByMs ?? 0} ms`);
34
+ for (const field of ['deliveredAt', 'failedAt', 'cancelledAt']) if (job[field]) console.log(` ${field}: ${job[field]}`);
35
+ if (job.lastError) console.log(` ${job.lastError.code ?? 'error'}: ${job.lastError.message}`);
36
+ }
37
+ } finally { client.close(); }
38
+ }
package/src/sessions.js CHANGED
@@ -108,7 +108,7 @@ function answerer(client) {
108
108
 
109
109
  /** Streams a tree until its root is idle; the first Ctrl-C interrupts it, the second detaches. */
110
110
 
111
- function follow(client, rootId, print, { untilIdle, interactive = false }) {
111
+ function follow(client, rootId, print, { untilIdle, interactive = false, targetOnly = false, promptId }) {
112
112
  const answering = interactive ? answerer(client) : undefined;
113
113
  const done = new Promise((resolve, reject) => {
114
114
  let failed = false;
@@ -121,9 +121,11 @@ function follow(client, rootId, print, { untilIdle, interactive = false }) {
121
121
  client.request('session.interrupt', { sessionId: rootId }).catch(() => {});
122
122
  };
123
123
  process.on('SIGINT', onSignal);
124
- client.onClose(error => { process.off('SIGINT', onSignal); reject(error); });
124
+ client.onClose(error => { process.off('SIGINT', onSignal); answering?.close(); reject(error); });
125
125
  let rootEnded = false;
126
126
  client.onEvent(envelope => {
127
+ if (targetOnly && envelope.sessionId !== rootId) return;
128
+ if (promptId && envelope.event.type === 'prompt.failed' && envelope.event.clientMessageId !== promptId) return;
127
129
  print(envelope);
128
130
  answering?.accept(envelope.event);
129
131
  const { sessionId, event } = envelope;
@@ -207,28 +209,36 @@ async function attach(args) {
207
209
  /** Steers a running root, prompts an idle one, or resumes a closed one; then follows it until idle. */
208
210
 
209
211
  async function send(args) {
210
- const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' } } });
212
+ const { values, positionals: [sessionId, ...words] } = parseArgs({ args, allowPositionals: true, options: { json: { type: 'boolean' }, prompt: { type: 'boolean' } } });
211
213
  const text = words.join(' ').trim();
212
214
  if (!sessionId || !text) throw new UsageError();
213
215
  const client = await connect(await start(), { name: 'alp-cli', version: '1' });
216
+ let subscriptionId;
214
217
  try {
215
218
  const { session } = await client.request('session.get', { sessionId });
216
- if (session.parentId) {
219
+ if (session.parentId && !values.prompt) {
217
220
  // An assignment gets the text as mail from the user, in its running turn.
218
221
  await client.request('session.message', { sessionId, text });
219
222
  if (!values.json) console.error(`Sent to ${session.agent} as mail from the user`);
220
223
  return;
221
224
  }
222
- const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY });
223
225
  const live = session.status === 'idle' || session.status === 'running';
224
- if (live) await client.request('session.attach', { sessionId, replay: false });
225
- else await client.request('session.create', { sessionId, spec: { cwd: session.projectRoot } });
226
- const steer = live && !!session.activeTurnId;
227
- await client.request('session.prompt', { sessionId, clientMessageId: randomUUID(), delivery: steer ? 'steer' : 'auto', content: [{ type: 'text', text }] });
228
- if (!values.json) console.error(steer ? 'Steered the running turn' : live ? 'Started a turn' : 'Resumed the session');
226
+ if (values.prompt && !live) throw new Error('Explicit prompts require a live session; use default alp send to reopen a root');
227
+ const clientMessageId = randomUUID();
228
+ const done = follow(client, sessionId, printer(values.json), { untilIdle: true, interactive: !values.json && process.stdin.isTTY, targetOnly: !!session.parentId, promptId: clientMessageId });
229
+ if (live) {
230
+ const attached = await client.request('session.attach', { sessionId, replay: false });
231
+ subscriptionId = attached.session.id; // A child attaches its root for observation only.
232
+ } else {
233
+ await client.request('session.create', { sessionId, spec: { cwd: session.projectRoot } });
234
+ subscriptionId = sessionId;
235
+ }
236
+ const steer = !values.prompt && live && !!session.activeTurnId;
237
+ await client.request('session.prompt', { sessionId, clientMessageId, delivery: steer ? 'steer' : 'auto', content: [{ type: 'text', text }] });
238
+ if (!values.json) console.error(values.prompt ? 'Submitted an explicit prompt' : steer ? 'Steered the running turn' : live ? 'Started a turn' : 'Resumed the session');
229
239
  if (!await done) process.exitCode = 1;
230
- await client.request('session.release', { sessionId }).catch(() => {});
231
240
  } finally {
241
+ if (subscriptionId) await client.request('session.release', { sessionId: subscriptionId }).catch(() => {});
232
242
  client.close();
233
243
  }
234
244
  }
@@ -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
+ }