@rarog/server 1.1.0-beta.1 → 1.1.0

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 (93) hide show
  1. package/README.md +14 -2
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +16 -1
  4. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  5. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  6. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  7. package/node_modules/@rarog/shared/src/protocol.js +5 -31
  8. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  9. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  10. package/node_modules/@rarog/shared/src/sentences/rest.js +8 -0
  11. package/package.json +2 -2
  12. package/server/src/auth/admin.js +3 -1
  13. package/server/src/bootstrap/consent.js +11 -0
  14. package/server/src/bootstrap/folder-gate.js +55 -0
  15. package/server/src/cli/service-log.js +27 -0
  16. package/server/src/cli/service.js +5 -2
  17. package/server/src/cli/templates/launchd.plist +1 -1
  18. package/server/src/cli/templates/rarog.service +1 -1
  19. package/server/src/cli/update-provenance.js +37 -19
  20. package/server/src/config/protected-dirs.js +2 -0
  21. package/server/src/config/roots.js +13 -8
  22. package/server/src/config/work-area.js +36 -12
  23. package/server/src/config-env.js +9 -0
  24. package/server/src/config.js +17 -1
  25. package/server/src/demo/control.js +9 -1
  26. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  27. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  28. package/server/src/drivers/herdr-driver.js +78 -9
  29. package/server/src/files/file-index.js +5 -3
  30. package/server/src/files/listing.js +8 -2
  31. package/server/src/files/path-rule.js +95 -41
  32. package/server/src/files/refusals.js +14 -0
  33. package/server/src/files/session-gate.js +11 -6
  34. package/server/src/folder-gate/client.js +314 -0
  35. package/server/src/folder-gate/disk.js +455 -0
  36. package/server/src/folder-gate/folders.js +23 -0
  37. package/server/src/folder-gate/gate.js +220 -0
  38. package/server/src/folder-gate/helper.js +118 -0
  39. package/server/src/folder-gate/install.js +27 -0
  40. package/server/src/folder-gate/relay-worker.js +147 -0
  41. package/server/src/folder-gate/types.js +115 -0
  42. package/server/src/folder-gate/wire.js +170 -0
  43. package/server/src/fs-browse.js +55 -23
  44. package/server/src/fs-mkdir.js +3 -1
  45. package/server/src/git-status.js +13 -5
  46. package/server/src/git-watch.js +130 -19
  47. package/server/src/git-work-tree.js +3 -3
  48. package/server/src/herdr/client.js +2 -2
  49. package/server/src/herdr/commands/discover.js +21 -9
  50. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  51. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  52. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  53. package/server/src/herdr/dialogs/index.js +7 -2
  54. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  55. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  56. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  57. package/server/src/herdr/dialogs/router.js +21 -6
  58. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  59. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  60. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  61. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  62. package/server/src/herdr/jsonl-follow.js +55 -14
  63. package/server/src/herdr/provenance.js +3 -3
  64. package/server/src/herdr/socket.js +25 -28
  65. package/server/src/herdr/supervisor.js +13 -10
  66. package/server/src/herdr/transcript-path.js +36 -0
  67. package/server/src/herdr/trust.js +11 -8
  68. package/server/src/herdr/uploads-registry.js +3 -2
  69. package/server/src/herdr/uploads.js +170 -47
  70. package/server/src/index.js +22 -3
  71. package/server/src/iroh/listener.js +3 -0
  72. package/server/src/iroh/log-budget.js +1 -0
  73. package/server/src/iroh/socket.js +2 -1
  74. package/server/src/notes/store.js +3 -2
  75. package/server/src/router.js +13 -1
  76. package/server/src/routes/projects.js +5 -1
  77. package/server/src/routes/sessions.js +10 -4
  78. package/server/src/routes/system.js +4 -0
  79. package/server/src/safe-read.js +12 -12
  80. package/server/src/sessions/companion-scope.js +10 -5
  81. package/server/src/sessions/done-retention.js +57 -0
  82. package/server/src/sessions/launch-gate.js +2 -2
  83. package/server/src/sessions/manager.js +35 -59
  84. package/server/src/sessions/project-scan.js +9 -3
  85. package/server/src/sessions/ring-buffer.js +8 -21
  86. package/server/src/sessions/session-git.js +31 -2
  87. package/server/src/sessions/session.js +1 -1
  88. package/server/src/sessions/state-sentences.js +1 -1
  89. package/server/src/sse.js +121 -22
  90. package/server/src/term/herdr-backend.js +2 -2
  91. package/server/src/term/index.js +2 -15
  92. package/server/src/term/registry.js +4 -3
  93. package/server/src/term/ws.js +9 -1
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The state of each macOS-guarded folder: whether a call in it goes to its helper or is refused without the disk.
3
+ * The gate takes the events of the port's calls (`report`) and the late answers of the client, checks a folder with
4
+ * a helper, kills a hung helper and checks again on a new one, rechecks a closed folder on a timer and tells
5
+ * listeners about each change. A folder nobody judged yet opens on the first listing or read its helper answers, so a
6
+ * folder with consent needs no check of its own. It never touches the disk itself and starts no helper on its own:
7
+ * the client does.
8
+ */
9
+ import path from 'node:path';
10
+ import { gatedFolderOf } from './folders.js';
11
+ /** How often a waiting folder is checked again on a new helper. */
12
+ export const FOLDER_RECHECK_MS = 60_000;
13
+ /** How often a denied, absent or unchecked folder is checked again; after a refusal macOS answers at once. */
14
+ export const FOLDER_RECHECK_SLOW_MS = 5 * 60_000;
15
+ const BLOCKED_STATES = new Set(['waiting', 'denied', 'unchecked']);
16
+ const DENIED_CODES = new Set(['EPERM', 'EACCES']);
17
+ const ABSENT_CODES = new Set(['ENOENT', 'ENOTDIR']);
18
+ /** The state a check answer leads to, with the reason for the log line. */
19
+ function checkOutcome(answer, boundMs) {
20
+ switch (answer.kind) {
21
+ case 'ok':
22
+ return { state: 'open', reason: '' };
23
+ case 'timeout':
24
+ return { state: 'waiting', reason: `no answer in ${boundMs} ms` };
25
+ case 'gone':
26
+ return { state: 'unchecked', reason: 'helper gone' };
27
+ case 'fs-error': {
28
+ const code = answer.error.code ?? 'no code';
29
+ if (DENIED_CODES.has(code))
30
+ return { state: 'denied', reason: code };
31
+ if (ABSENT_CODES.has(code))
32
+ return { state: 'absent', reason: code };
33
+ return { state: 'unchecked', reason: code };
34
+ }
35
+ }
36
+ }
37
+ export class MacFolderGate {
38
+ enabled = true;
39
+ #home;
40
+ #client;
41
+ #boundMs;
42
+ #log;
43
+ #entries = new Map();
44
+ #listeners = new Set();
45
+ #offLate;
46
+ #disposed = false;
47
+ constructor(options) {
48
+ this.#home = options.home;
49
+ this.#client = options.client;
50
+ this.#boundMs = options.boundMs;
51
+ this.#log = options.log ?? (() => undefined);
52
+ // The gate's own check times out at the client's bound while the helper keeps waiting on the macOS window; the
53
+ // answer to the click arrives only as a late answer.
54
+ this.#offLate = this.#client.onLate((folder, gen, answer) => {
55
+ if (answer.kind === 'ok')
56
+ this.report(folder, gen, 'late-ok');
57
+ else if (answer.kind === 'fs-error' && DENIED_CODES.has(answer.error.code ?? ''))
58
+ this.report(folder, gen, 'eperm');
59
+ });
60
+ }
61
+ stateOf(candidate) {
62
+ const folder = gatedFolderOf(candidate, this.#home);
63
+ if (folder === null)
64
+ return null;
65
+ return { folder, state: this.#entries.get(folder)?.state ?? 'unknown' };
66
+ }
67
+ report(folder, gen, event) {
68
+ if (this.#disposed)
69
+ return;
70
+ const entry = this.#entry(folder);
71
+ if (entry.gen !== undefined && gen < entry.gen) {
72
+ this.#log(`folder gate: ${entry.name} ignores ${event} of helper generation ${gen} (current ${entry.gen})`);
73
+ return;
74
+ }
75
+ const passable = entry.state === 'unknown' || entry.state === 'open';
76
+ switch (event) {
77
+ case 'timeout':
78
+ // Only the first timeout kills and retries; later ones of calls already in flight change nothing.
79
+ if (!passable)
80
+ return;
81
+ this.#enter(entry, 'waiting', `no answer in ${this.#boundMs} ms`);
82
+ this.#startRun(entry, 'after-timeout', true);
83
+ return;
84
+ case 'eperm':
85
+ if (entry.run === undefined)
86
+ this.#startRun(entry, 'request', true);
87
+ return;
88
+ case 'gone':
89
+ if (passable && entry.run === undefined)
90
+ this.#startRun(entry, 'request', true);
91
+ return;
92
+ case 'ok':
93
+ // An answer proves access only where no one judged the folder; a closed folder opens by a check or a late
94
+ // answer, and a check in flight still settles its callers.
95
+ if (entry.state !== 'unknown')
96
+ return;
97
+ this.#enter(entry, 'open', 'a call answered');
98
+ return;
99
+ case 'late-ok':
100
+ if (entry.state === 'open')
101
+ return;
102
+ // A check still in flight would answer for a moment that has passed.
103
+ entry.run = undefined;
104
+ this.#enter(entry, 'open', 'a late answer');
105
+ this.#settle(entry);
106
+ this.#schedule(entry);
107
+ return;
108
+ }
109
+ }
110
+ check(folder, waitMs) {
111
+ const entry = this.#entry(folder);
112
+ if (this.#disposed)
113
+ return Promise.resolve(entry.state);
114
+ // A helper of a closed folder may hang on a window or be gone, so a check there starts a new one.
115
+ if (entry.run === undefined)
116
+ this.#startRun(entry, 'request', entry.state !== 'unknown' && entry.state !== 'open');
117
+ return new Promise((resolve) => {
118
+ const done = () => {
119
+ clearTimeout(timer);
120
+ entry.waiters.delete(done);
121
+ resolve(entry.state);
122
+ };
123
+ const timer = setTimeout(done, waitMs);
124
+ timer.unref();
125
+ entry.waiters.add(done);
126
+ });
127
+ }
128
+ blocked() {
129
+ const out = [];
130
+ for (const entry of this.#entries.values()) {
131
+ if (!BLOCKED_STATES.has(entry.state))
132
+ continue;
133
+ out.push({ name: entry.name, path: entry.folder, state: entry.state, since: entry.since });
134
+ }
135
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
136
+ }
137
+ onChange(listener) {
138
+ this.#listeners.add(listener);
139
+ return () => { this.#listeners.delete(listener); };
140
+ }
141
+ /** Stops timers and listening; the client and its helpers belong to whoever made them. */
142
+ dispose() {
143
+ if (this.#disposed)
144
+ return;
145
+ this.#disposed = true;
146
+ this.#offLate();
147
+ for (const entry of this.#entries.values()) {
148
+ clearTimeout(entry.timer);
149
+ entry.timer = undefined;
150
+ entry.run = undefined;
151
+ this.#settle(entry);
152
+ }
153
+ this.#listeners.clear();
154
+ }
155
+ #entry(folder) {
156
+ let entry = this.#entries.get(folder);
157
+ if (entry === undefined) {
158
+ entry = {
159
+ folder, name: path.basename(folder), state: 'unknown', since: new Date().toISOString(), gen: undefined,
160
+ run: undefined, timer: undefined, waiters: new Set(),
161
+ };
162
+ this.#entries.set(folder, entry);
163
+ }
164
+ return entry;
165
+ }
166
+ /** Starts a check of the folder, on a new helper generation when `fresh`; it replaces any check in flight. */
167
+ #startRun(entry, kind, fresh) {
168
+ clearTimeout(entry.timer);
169
+ entry.timer = undefined;
170
+ if (fresh)
171
+ entry.gen = this.#client.restart(entry.folder);
172
+ const run = { kind };
173
+ entry.run = run;
174
+ this.#client.call(entry.folder, 'check', { path: entry.folder }).then((answer) => { this.#finish(entry, run, answer); }, () => { this.#finish(entry, run, { kind: 'gone' }); });
175
+ }
176
+ #finish(entry, run, answer) {
177
+ if (this.#disposed)
178
+ return;
179
+ if (entry.run !== run) {
180
+ this.#log(`folder gate: ${entry.name} drops the answer of a superseded check`);
181
+ return;
182
+ }
183
+ entry.run = undefined;
184
+ const outcome = checkOutcome(answer, this.#boundMs);
185
+ const slowRead = outcome.state === 'open' && run.kind === 'after-timeout' && entry.state === 'waiting';
186
+ this.#enter(entry, outcome.state, slowRead ? 'slow read: a new helper answered at once' : outcome.reason);
187
+ // A timeout keeps the callers of `check` waiting: the answer to the window may still come late.
188
+ if (outcome.state !== 'waiting')
189
+ this.#settle(entry);
190
+ this.#schedule(entry);
191
+ }
192
+ #enter(entry, state, reason) {
193
+ if (entry.state === state)
194
+ return;
195
+ entry.state = state;
196
+ entry.since = new Date().toISOString();
197
+ this.#log(`folder gate: ${entry.name} ${state}${reason === '' ? '' : ` (${reason})`}`);
198
+ for (const listener of [...this.#listeners])
199
+ listener(entry.folder, state);
200
+ }
201
+ #settle(entry) {
202
+ for (const done of [...entry.waiters])
203
+ done();
204
+ }
205
+ /** Arms the recheck of a closed folder; an open or unknown folder has none. */
206
+ #schedule(entry) {
207
+ clearTimeout(entry.timer);
208
+ entry.timer = undefined;
209
+ const delay = entry.state === 'waiting' ? FOLDER_RECHECK_MS
210
+ : BLOCKED_STATES.has(entry.state) || entry.state === 'absent' ? FOLDER_RECHECK_SLOW_MS : undefined;
211
+ if (delay === undefined)
212
+ return;
213
+ entry.timer = setTimeout(() => {
214
+ entry.timer = undefined;
215
+ if (entry.run === undefined)
216
+ this.#startRun(entry, 'recheck', true);
217
+ }, delay);
218
+ entry.timer.unref();
219
+ }
220
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The folder helper: a child `node` process that runs the disk calls of one gated folder, so a call that waits in the
3
+ * kernel (a macOS consent window) waits in a process the server can kill, never in a thread of the server. It reads
4
+ * requests of the line codec (`wire.ts`) on stdin, runs each through the port's own disk (`disk.ts`) and writes the
5
+ * answer on stdout. This module also gives the command that starts it; it never judges a path or a folder state.
6
+ */
7
+ import path from 'node:path';
8
+ import { INSTALL_MODE, INSTALL_ROOT } from '../install/mode.js';
9
+ import { runDisk } from './disk.js';
10
+ import { decodeRequest, encodeResponse } from './wire.js';
11
+ /**
12
+ * The source run with `--input-type=module -e`: `argv[1]` is this module's file, which the source imports and serves.
13
+ * The serving loop lives in the module, so the helper and the server share one codec and one disk.
14
+ */
15
+ export const FOLDER_HELPER_BOOTSTRAP = `import { pathToFileURL } from 'node:url';
16
+ const { serveFolderHelper } = await import(pathToFileURL(process.argv[1]).href);
17
+ serveFolderHelper();
18
+ `;
19
+ /** Spawn options of every helper: `/` as the start directory (no folder held open) and an empty environment. */
20
+ export const FOLDER_HELPER_SPAWN = { cwd: '/', env: {} };
21
+ /**
22
+ * The command for the install at `root`. The package runs the built JavaScript. The clone runs this module's
23
+ * TypeScript with Node's own type stripping, not tsx: under an empty environment tsx would keep its cache in `/tmp`.
24
+ * The flag goes only to a Node that does not strip types by default; `typescript` is `process.features.typescript`.
25
+ */
26
+ export function folderHelperCommand(root = INSTALL_ROOT, mode = INSTALL_MODE, typescript = process.features.typescript) {
27
+ const entry = path.join(root, 'server', 'src', 'folder-gate', mode === 'package' ? 'helper.js' : 'helper.ts');
28
+ const strip = mode === 'clone' && typescript === false ? ['--experimental-strip-types'] : [];
29
+ return {
30
+ file: process.execPath,
31
+ args: [...strip, '--input-type=module', '-e', FOLDER_HELPER_BOOTSTRAP, '--', entry],
32
+ ...FOLDER_HELPER_SPAWN,
33
+ };
34
+ }
35
+ /**
36
+ * Ends the helper with SIGKILL. A thread stuck in the kernel keeps `process.exit` waiting, so with a call still in
37
+ * flight this is the only way out.
38
+ */
39
+ const killSelf = () => { process.kill(process.pid, 'SIGKILL'); };
40
+ /** A request whose line decodes to JSON with an integer `id` but is not a valid request. */
41
+ function malformed(message) {
42
+ return Object.assign(new Error(`folder helper: ${message}`), { code: 'EINVAL' });
43
+ }
44
+ /** The id of a line that is not a valid request, when it has one; such a request still gets an answer. */
45
+ function idOf(line) {
46
+ try {
47
+ const message = JSON.parse(line);
48
+ if (typeof message !== 'object' || message === null)
49
+ return null;
50
+ const id = message.id;
51
+ return Number.isSafeInteger(id) ? id : null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ /**
58
+ * Serves requests until stdin ends. Every call runs as a promise, so one call that waits does not hold the answers of
59
+ * the others; answers go out in the order calls finish. A line without an integer id has no one to answer and is
60
+ * dropped. At the end of stdin the helper exits with 0 when idle and kills itself when a call is still in flight.
61
+ */
62
+ export function serveFolderHelper() {
63
+ let inFlight = 0;
64
+ /** The start of a line whose end has not come yet. */
65
+ const parts = [];
66
+ const send = (line) => { process.stdout.write(`${line}\n`); };
67
+ const answer = async (id, op, args) => {
68
+ let reply;
69
+ try {
70
+ const value = await runDisk(op, args);
71
+ reply = encodeResponse(id, { ok: true, value });
72
+ }
73
+ catch (error) {
74
+ reply = encodeResponse(id, { ok: false, error: error instanceof Error ? error : new Error(String(error)) });
75
+ }
76
+ send(reply);
77
+ };
78
+ const handle = (line) => {
79
+ let request;
80
+ try {
81
+ request = decodeRequest(line);
82
+ }
83
+ catch (error) {
84
+ const id = idOf(line);
85
+ const message = error instanceof Error ? error.message : String(error);
86
+ if (id !== null)
87
+ send(encodeResponse(id, { ok: false, error: malformed(message) }));
88
+ return;
89
+ }
90
+ inFlight += 1;
91
+ void answer(request.id, request.op, request.args).finally(() => { inFlight -= 1; });
92
+ };
93
+ process.stdin.setEncoding('utf8');
94
+ // Only the new chunk is searched for a line end, so a large `writeFile` that comes in many chunks stays linear.
95
+ process.stdin.on('data', (chunk) => {
96
+ let from = 0;
97
+ let end = chunk.indexOf('\n');
98
+ while (end >= 0) {
99
+ parts.push(chunk.slice(from, end));
100
+ const line = parts.join('');
101
+ parts.length = 0;
102
+ if (line.length > 0)
103
+ handle(line);
104
+ from = end + 1;
105
+ end = chunk.indexOf('\n', from);
106
+ }
107
+ if (from < chunk.length)
108
+ parts.push(chunk.slice(from));
109
+ });
110
+ process.stdin.on('end', () => {
111
+ if (inFlight === 0)
112
+ process.exit(0);
113
+ else
114
+ killSelf();
115
+ });
116
+ // The server is gone and no answer can reach it.
117
+ process.stdout.on('error', killSelf);
118
+ }
@@ -0,0 +1,27 @@
1
+ /** The gate of Linux, the demo, the kill switch and tests: it judges nothing and never waits. */
2
+ export const DISABLED_FOLDER_GATE = Object.freeze({
3
+ enabled: false,
4
+ stateOf: () => null,
5
+ report: () => undefined,
6
+ check: () => Promise.resolve('unknown'),
7
+ blocked: () => [],
8
+ onChange: () => () => undefined,
9
+ dispose: () => undefined,
10
+ });
11
+ let installed;
12
+ export function folderGate() {
13
+ return installed ?? DISABLED_FOLDER_GATE;
14
+ }
15
+ /**
16
+ * Makes `gate` the gate of the process and returns its removal, which gives the disabled gate back; removing does not
17
+ * dispose the gate. A second install while one stands is a programming error and throws.
18
+ */
19
+ export function installFolderGate(gate) {
20
+ if (installed !== undefined)
21
+ throw new Error('a folder gate is already installed in this process');
22
+ installed = gate;
23
+ return () => {
24
+ if (installed === gate)
25
+ installed = undefined;
26
+ };
27
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The relay thread of the folder gate: it starts one helper process per folder with the command it was given, writes
3
+ * request lines to the helper's stdin and passes every answer line back to the server thread, tagged with the folder
4
+ * and the generation. It never touches the disk and never decodes a value; ids, generations and timeouts belong to
5
+ * the client (`client.ts`). After each message it bumps a shared counter, so a server thread blocked in
6
+ * `Atomics.wait` wakes up, and it keeps the pid of each live helper in a shared table the server thread kills from.
7
+ */
8
+ import { spawn } from 'node:child_process';
9
+ import { workerData } from 'node:worker_threads';
10
+ /** The id of an answer line, without decoding its value; `null` for a line that names none. */
11
+ function idOf(line) {
12
+ try {
13
+ const message = JSON.parse(line);
14
+ if (typeof message !== 'object' || message === null)
15
+ return null;
16
+ const id = message.id;
17
+ return Number.isSafeInteger(id) ? id : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function run(data) {
24
+ const { port, helper: command } = data;
25
+ const signal = new Int32Array(data.signal);
26
+ const pids = new Int32Array(data.pids);
27
+ const helpers = new Map();
28
+ const generations = new Map();
29
+ const post = (event) => {
30
+ port.postMessage(event);
31
+ Atomics.add(signal, 0, 1);
32
+ Atomics.notify(signal, 0);
33
+ };
34
+ const end = (folder, helper) => {
35
+ if (helper.ended)
36
+ return;
37
+ helper.ended = true;
38
+ if (helper.slot >= 0)
39
+ Atomics.compareExchange(pids, helper.slot, helper.pid, 0);
40
+ if (helpers.get(folder) === helper)
41
+ helpers.delete(folder);
42
+ post({ type: 'gone', folder, gen: helper.gen, ids: [...helper.open] });
43
+ helper.open.clear();
44
+ };
45
+ const start = (folder, gen) => {
46
+ let child = null;
47
+ try {
48
+ child = spawn(command.file, [...command.args], { cwd: '/', env: {}, stdio: ['pipe', 'pipe', 'ignore'] });
49
+ }
50
+ catch {
51
+ child = null;
52
+ }
53
+ const helper = { gen, child, open: new Set(), slot: -1, pid: 0, ended: false };
54
+ helpers.set(folder, helper);
55
+ if (child === null) {
56
+ // `end` runs once the caller has written its id into `open`, so that call gets `gone`.
57
+ queueMicrotask(() => { end(folder, helper); });
58
+ return helper;
59
+ }
60
+ if (child.pid !== undefined) {
61
+ helper.pid = child.pid;
62
+ for (let slot = 0; slot < pids.length; slot += 1) {
63
+ if (Atomics.compareExchange(pids, slot, 0, child.pid) === 0) {
64
+ helper.slot = slot;
65
+ break;
66
+ }
67
+ }
68
+ }
69
+ child.stdin?.on('error', () => { });
70
+ let buffer = '';
71
+ child.stdout?.setEncoding('utf8');
72
+ child.stdout?.on('data', (chunk) => {
73
+ buffer += chunk;
74
+ let newline = buffer.indexOf('\n');
75
+ while (newline >= 0) {
76
+ const line = buffer.slice(0, newline);
77
+ buffer = buffer.slice(newline + 1);
78
+ newline = buffer.indexOf('\n');
79
+ const id = idOf(line);
80
+ if (id === null || !helper.open.delete(id))
81
+ continue;
82
+ post({ type: 'line', folder, gen, id, line });
83
+ }
84
+ });
85
+ child.on('error', () => { end(folder, helper); });
86
+ // `close` comes after stdout is drained, so every answer the helper wrote is posted before `gone`.
87
+ child.on('close', () => { end(folder, helper); });
88
+ child.on('exit', () => {
89
+ if (helper.slot >= 0)
90
+ Atomics.compareExchange(pids, helper.slot, helper.pid, 0);
91
+ });
92
+ return helper;
93
+ };
94
+ const kill = (helper) => {
95
+ try {
96
+ helper.child?.kill('SIGKILL');
97
+ }
98
+ catch {
99
+ // Already gone.
100
+ }
101
+ };
102
+ // The server thread closed the channel or asked to stop: kill every helper; the thread ends once they are reaped.
103
+ const shutdown = () => {
104
+ for (const helper of helpers.values())
105
+ kill(helper);
106
+ helpers.clear();
107
+ port.close();
108
+ };
109
+ port.on('close', shutdown);
110
+ port.on('message', (request) => {
111
+ switch (request.type) {
112
+ case 'call': {
113
+ const { folder, gen, id, line } = request;
114
+ if (gen < (generations.get(folder) ?? gen)) {
115
+ post({ type: 'gone', folder, gen, ids: [id] });
116
+ return;
117
+ }
118
+ generations.set(folder, gen);
119
+ let helper = helpers.get(folder);
120
+ if (helper !== undefined && helper.gen !== gen) {
121
+ kill(helper);
122
+ helpers.delete(folder);
123
+ helper = undefined;
124
+ }
125
+ helper ??= start(folder, gen);
126
+ helper.open.add(id);
127
+ helper.child?.stdin?.write(`${line}\n`);
128
+ return;
129
+ }
130
+ case 'restart': {
131
+ generations.set(request.folder, Math.max(request.gen, generations.get(request.folder) ?? 0));
132
+ const helper = helpers.get(request.folder);
133
+ if (helper !== undefined) {
134
+ helpers.delete(request.folder);
135
+ kill(helper);
136
+ }
137
+ return;
138
+ }
139
+ case 'dispose':
140
+ shutdown();
141
+ return;
142
+ }
143
+ });
144
+ }
145
+ const data = workerData;
146
+ if (data?.port !== undefined)
147
+ run(data);
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Shared shapes of the folder gate: the states of a macOS-guarded folder in the home directory, the error a call in a
3
+ * closed folder fails with, the disk operations of the work-area port with their arguments and values, and the client
4
+ * and gate interfaces. Values are plain data (`DiskStats` and `DiskDirent` are snapshots, not `node:fs` objects), so
5
+ * the same value can cross the line codec of a helper process (`wire.ts`). The module never touches the disk.
6
+ */
7
+ import { say } from '@rarog/shared/sentences';
8
+ export const FOLDER_STATES = ['unknown', 'open', 'waiting', 'denied', 'absent', 'unchecked'];
9
+ /** The states in which a call in the folder is refused without a disk call. */
10
+ export const CLOSED_STATES = ['waiting', 'denied', 'absent', 'unchecked'];
11
+ /** The sentence of a refusal for each closed state; a missing folder reads like any missing directory. */
12
+ const CLOSED_SENTENCE = {
13
+ waiting: () => say('rest.cwd-folder-waiting'),
14
+ denied: () => say('rest.cwd-folder-denied'),
15
+ absent: () => say('rest.cwd-not-found'),
16
+ unchecked: () => say('rest.cwd-folder-unchecked'),
17
+ };
18
+ /**
19
+ * A disk call refused because its folder is closed. A consumer that treats a file system error as an unreadable path
20
+ * treats this one the same way; `sentence` is what the user reads.
21
+ */
22
+ export class FolderGateError extends Error {
23
+ code = 'EFOLDERGATE';
24
+ name = 'FolderGateError';
25
+ folder;
26
+ state;
27
+ sentence;
28
+ constructor(folder, state) {
29
+ const sentence = CLOSED_SENTENCE[state]();
30
+ super(sentence.text);
31
+ this.folder = folder;
32
+ this.state = state;
33
+ this.sentence = sentence;
34
+ }
35
+ }
36
+ // ---------------------------------------------------------------------------
37
+ // Values of the disk operations
38
+ // ---------------------------------------------------------------------------
39
+ const S_IFMT = 0o170000;
40
+ const FILE_TYPES = {
41
+ file: 0o100000, dir: 0o040000, link: 0o120000, fifo: 0o010000, socket: 0o140000, block: 0o060000, char: 0o020000,
42
+ };
43
+ /** The numeric fields of a `stat` with `bigint: true`, the form the port always gives. */
44
+ export const STATS_FIELDS = [
45
+ 'dev', 'ino', 'mode', 'nlink', 'uid', 'gid', 'rdev', 'size', 'blksize', 'blocks',
46
+ 'atimeMs', 'mtimeMs', 'ctimeMs', 'birthtimeMs', 'atimeNs', 'mtimeNs', 'ctimeNs', 'birthtimeNs',
47
+ ];
48
+ // A plain function, not a private member: callers wrap stats in a `Proxy`, which cannot reach private fields.
49
+ const hasType = (mode, type) => (Number(mode) & S_IFMT) === FILE_TYPES[type];
50
+ /** A snapshot of `BigIntStats`: the same fields, type checks and dates, as plain data. */
51
+ export class DiskStats {
52
+ dev;
53
+ ino;
54
+ mode;
55
+ nlink;
56
+ uid;
57
+ gid;
58
+ rdev;
59
+ size;
60
+ blksize;
61
+ blocks;
62
+ atimeMs;
63
+ mtimeMs;
64
+ ctimeMs;
65
+ birthtimeMs;
66
+ atimeNs;
67
+ mtimeNs;
68
+ ctimeNs;
69
+ birthtimeNs;
70
+ constructor(fields) {
71
+ for (const field of STATS_FIELDS)
72
+ this[field] = fields[field];
73
+ }
74
+ isFile() { return hasType(this.mode, 'file'); }
75
+ isDirectory() { return hasType(this.mode, 'dir'); }
76
+ isSymbolicLink() { return hasType(this.mode, 'link'); }
77
+ isFIFO() { return hasType(this.mode, 'fifo'); }
78
+ isSocket() { return hasType(this.mode, 'socket'); }
79
+ isBlockDevice() { return hasType(this.mode, 'block'); }
80
+ isCharacterDevice() { return hasType(this.mode, 'char'); }
81
+ get atime() { return new Date(Number(this.atimeMs)); }
82
+ get mtime() { return new Date(Number(this.mtimeMs)); }
83
+ get ctime() { return new Date(Number(this.ctimeMs)); }
84
+ get birthtime() { return new Date(Number(this.birthtimeMs)); }
85
+ }
86
+ /** The snapshot of a `stat` result taken with `bigint: true`. */
87
+ export function diskStats(stats) {
88
+ const fields = {};
89
+ for (const field of STATS_FIELDS)
90
+ fields[field] = stats[field];
91
+ return new DiskStats(fields);
92
+ }
93
+ /** A snapshot of a `Dirent`: the name (string or bytes, as asked), the parent path and the type. */
94
+ export class DiskDirent {
95
+ name;
96
+ parentPath;
97
+ type;
98
+ constructor(name, parentPath, type) {
99
+ this.name = name;
100
+ this.parentPath = parentPath;
101
+ this.type = type;
102
+ }
103
+ /** The parent path under the name `node:fs` also gives it. */
104
+ get path() { return this.parentPath; }
105
+ isFile() { return this.type === 'file'; }
106
+ isDirectory() { return this.type === 'dir'; }
107
+ isSymbolicLink() { return this.type === 'link'; }
108
+ isFIFO() { return this.type === 'fifo'; }
109
+ isSocket() { return this.type === 'socket'; }
110
+ isBlockDevice() { return this.type === 'block'; }
111
+ isCharacterDevice() { return this.type === 'char'; }
112
+ }
113
+ export function diskDirent(name, parentPath, type) {
114
+ return new DiskDirent(name, parentPath, type);
115
+ }