@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,455 @@
1
+ import { chmodSync, lstatSync, mkdirSync, opendirSync, readdirSync, readlinkSync, realpath as realpathCallback, realpathSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
2
+ import { chmod, lstat, mkdir, opendir, readdir, readlink, realpath as realpathNative, stat, unlink, writeFile, } from 'node:fs/promises';
3
+ import { constants } from 'node:os';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { foldCase } from '../config/protected-dirs.js';
7
+ import { appendRegularFile, openRegularFile, readDirectoryByIdentity, readRegularFile, readRegularFileSync, } from '../safe-read.js';
8
+ import { CLOSED_STATES, FolderGateError, diskDirent, diskStats, } from './types.js';
9
+ /** `fs.realpath` with a callback is the JavaScript walk, like `realpathSync`; the promise form is the native one. */
10
+ const realpathJs = promisify(realpathCallback);
11
+ function typeOf(entry) {
12
+ if (entry.isFile())
13
+ return 'file';
14
+ if (entry.isDirectory())
15
+ return 'dir';
16
+ if (entry.isSymbolicLink())
17
+ return 'link';
18
+ if (entry.isFIFO())
19
+ return 'fifo';
20
+ if (entry.isSocket())
21
+ return 'socket';
22
+ if (entry.isBlockDevice())
23
+ return 'block';
24
+ if (entry.isCharacterDevice())
25
+ return 'char';
26
+ return 'unknown';
27
+ }
28
+ const entries = (list) => list.map((entry) => diskDirent(entry.name, entry.parentPath, typeOf(entry)));
29
+ const bufferEntries = (list) => list.map((entry) => diskDirent(entry.name, entry.parentPath, typeOf(entry)));
30
+ const mkdirOptions = (args) => ({
31
+ recursive: args.recursive === true,
32
+ ...(args.mode === undefined ? {} : { mode: args.mode }),
33
+ });
34
+ const writeOptions = (args) => ({
35
+ ...(args.mode === undefined ? {} : { mode: args.mode }),
36
+ ...(args.flag === undefined ? {} : { flag: args.flag }),
37
+ });
38
+ /** Files left open by `openRead`, by the descriptor number the caller holds as its handle. */
39
+ const OPEN_FILES = new Map();
40
+ function badHandle(syscall) {
41
+ const error = new Error(`EBADF: bad file descriptor, ${syscall}`);
42
+ error.code = 'EBADF';
43
+ error.errno = -constants.errno.EBADF;
44
+ error.syscall = syscall;
45
+ return error;
46
+ }
47
+ function openFile(handle, syscall) {
48
+ const file = OPEN_FILES.get(handle);
49
+ if (file !== undefined)
50
+ return file;
51
+ throw badHandle(syscall);
52
+ }
53
+ const SYNC = {
54
+ lstat: (args) => diskStats(lstatSync(args.path, { bigint: true })),
55
+ stat: (args) => diskStats(statSync(args.path, { bigint: true })),
56
+ readlink: (args) => readlinkSync(args.path),
57
+ realpath: (args) => realpathSync(args.path),
58
+ realpathNative: (args) => realpathSync.native(args.path),
59
+ readdir: (args) => entries(readdirSync(args.path, { withFileTypes: true, encoding: args.encoding })),
60
+ readdirNames: (args) => readdirSync(args.path),
61
+ readHead: (args) => readRegularFileSync(args.path, { maxBytes: args.maxBytes, followSymlink: args.followSymlink }),
62
+ mkdir: (args) => mkdirSync(args.path, mkdirOptions(args)),
63
+ writeFile: (args) => writeFileSync(args.path, args.data, writeOptions(args)),
64
+ chmod: (args) => chmodSync(args.path, args.mode),
65
+ unlink: (args) => unlinkSync(args.path),
66
+ check: (args) => {
67
+ const dir = opendirSync(args.path);
68
+ try {
69
+ dir.readSync();
70
+ }
71
+ finally {
72
+ dir.closeSync();
73
+ }
74
+ return undefined;
75
+ },
76
+ };
77
+ const ASYNC = {
78
+ lstat: async (args) => diskStats(await lstat(args.path, { bigint: true })),
79
+ stat: async (args) => diskStats(await stat(args.path, { bigint: true })),
80
+ readlink: (args) => readlink(args.path),
81
+ realpath: (args) => realpathJs(args.path),
82
+ realpathNative: (args) => realpathNative(args.path),
83
+ readdir: async (args) => entries(await readdir(args.path, { withFileTypes: true, encoding: args.encoding })),
84
+ readdirNames: (args) => readdir(args.path),
85
+ readHead: (args) => readRegularFile(args.path, { maxBytes: args.maxBytes, followSymlink: args.followSymlink }),
86
+ readdirByIdentity: async (args) => {
87
+ const list = await readDirectoryByIdentity(args.path, { dev: args.dev, ino: args.ino });
88
+ return list === null ? null : bufferEntries(list);
89
+ },
90
+ openRead: async (args) => {
91
+ const opened = await openRegularFile(args.path, { followSymlink: args.followSymlink });
92
+ if (opened === null)
93
+ return null;
94
+ OPEN_FILES.set(opened.handle.fd, opened.handle);
95
+ return { handle: opened.handle.fd, stats: diskStats(opened.stats) };
96
+ },
97
+ read: async (args) => {
98
+ const buffer = Buffer.alloc(args.length);
99
+ const { bytesRead } = await openFile(args.handle, 'read').read(buffer, 0, args.length, args.position);
100
+ return bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead);
101
+ },
102
+ close: async (args) => {
103
+ const file = openFile(args.handle, 'close');
104
+ OPEN_FILES.delete(args.handle);
105
+ await file.close();
106
+ return undefined;
107
+ },
108
+ mkdir: (args) => mkdir(args.path, mkdirOptions(args)),
109
+ writeFile: (args) => writeFile(args.path, args.data, writeOptions(args)),
110
+ appendRegular: (args) => appendRegularFile(args.path, args.text),
111
+ chmod: (args) => chmod(args.path, args.mode),
112
+ unlink: (args) => unlink(args.path),
113
+ check: async (args) => {
114
+ const dir = await opendir(args.path);
115
+ try {
116
+ await dir.read();
117
+ }
118
+ finally {
119
+ await dir.close();
120
+ }
121
+ return undefined;
122
+ },
123
+ };
124
+ /** One operation, synchronously, on the disk of this process. Throws the error `node:fs` throws. */
125
+ export function runDiskSync(op, args) {
126
+ return SYNC[op](args);
127
+ }
128
+ /** One operation as a promise on the disk of this process. Rejects with the error `node:fs` gives. */
129
+ export function runDisk(op, args) {
130
+ return ASYNC[op](args);
131
+ }
132
+ let routed = null;
133
+ const segmentsOf = (file) => file.split(path.sep).filter((part) => part !== '');
134
+ /**
135
+ * Sends the port's calls through the gate of `route` and returns the removal, which gives this process the calls
136
+ * back. Home goes through `realpath` once here, so a path that reaches a guarded folder through the on-disk form of
137
+ * home still finds it. A second route while one stands is a programming error and throws.
138
+ */
139
+ export function routeWorkAreaDisk(route) {
140
+ if (routed !== null)
141
+ throw new Error('the work-area disk is already routed through a folder gate');
142
+ const home = path.resolve(route.home);
143
+ let onDisk = home;
144
+ try {
145
+ onDisk = runDiskSync('realpathNative', { path: home });
146
+ }
147
+ catch {
148
+ // Home stays as written.
149
+ }
150
+ const homes = [...new Set([home, onDisk])].map((form) => segmentsOf(form).map(foldCase));
151
+ const installed = { ...route, home, homes };
152
+ routed = installed;
153
+ return () => {
154
+ if (routed === installed)
155
+ routed = null;
156
+ };
157
+ }
158
+ /**
159
+ * Metadata of a path in a guarded folder never waits for a macOS consent window, so these calls stay in this
160
+ * process in every state of the folder, also while it is closed.
161
+ */
162
+ const METADATA = new Set(['lstat', 'stat', 'readlink', 'realpath', 'realpathNative']);
163
+ /** Whether a call acts on what a symlink in the last segment points to, not on the link itself. */
164
+ function followsLast(op, args) {
165
+ if (op === 'unlink' || op === 'appendRegular')
166
+ return false;
167
+ if (op === 'readHead' || op === 'openRead')
168
+ return args.followSymlink;
169
+ return true;
170
+ }
171
+ /**
172
+ * The guarded folder `candidate` lies in by its text, with the folder's state, or `null`. Besides the gate's own
173
+ * judgement, a path under another spelling of home (on disk, another letter case, as the default macOS disk folds it)
174
+ * counts as the same path under home.
175
+ */
176
+ function folderOf(route, candidate) {
177
+ const byGate = route.gate.stateOf(candidate);
178
+ if (byGate !== null)
179
+ return byGate;
180
+ const parts = segmentsOf(path.resolve(candidate));
181
+ for (const home of route.homes) {
182
+ if (parts.length <= home.length || !home.every((part, index) => part === foldCase(parts[index] ?? '')))
183
+ continue;
184
+ return route.gate.stateOf(path.join(route.home, ...parts.slice(home.length)));
185
+ }
186
+ return null;
187
+ }
188
+ /** Symlinks followed in one walk before it gives up, as `ELOOP` of the system. */
189
+ const MAX_LINKS = 40;
190
+ /**
191
+ * The guarded folder that holds the target of a call on `file`: by its text first, then by a walk from `/` one
192
+ * segment at a time with `lstat` and `readlink` in this process, so a symlink anywhere on the way into a guarded
193
+ * folder sends the call there. The walk stops at the first segment in a guarded folder and never reads inside it.
194
+ * `..` climbs from where the walk stands, as the system does after a link. A segment that cannot be read counts as a
195
+ * plain directory, so a path a call is about to create is judged by its text. The last segment is followed only for
196
+ * a call that follows it. `null`: the call stays in this process.
197
+ */
198
+ function targetFolder(route, file, followLast) {
199
+ const byText = folderOf(route, file);
200
+ if (byText !== null)
201
+ return byText;
202
+ let pending = segmentsOf(path.isAbsolute(file) ? file : `${process.cwd()}${path.sep}${file}`);
203
+ let current = path.sep;
204
+ let links = 0;
205
+ while (pending.length > 0) {
206
+ const [part, ...rest] = pending;
207
+ pending = rest;
208
+ if (part === undefined || part === '.')
209
+ continue;
210
+ if (part === '..') {
211
+ current = path.dirname(current);
212
+ continue;
213
+ }
214
+ const next = path.join(current, part);
215
+ const found = folderOf(route, next);
216
+ if (found !== null)
217
+ return found;
218
+ current = next;
219
+ if (pending.length === 0 && !followLast)
220
+ break;
221
+ let link = null;
222
+ try {
223
+ if (runDiskSync('lstat', { path: next }).isSymbolicLink())
224
+ link = runDiskSync('readlink', { path: next });
225
+ }
226
+ catch {
227
+ continue;
228
+ }
229
+ if (link === null)
230
+ continue;
231
+ links += 1;
232
+ if (links > MAX_LINKS)
233
+ return null;
234
+ current = path.isAbsolute(link) ? path.sep : path.dirname(next);
235
+ pending = [...segmentsOf(link), ...pending];
236
+ }
237
+ return null;
238
+ }
239
+ const isClosed = (state) => CLOSED_STATES.includes(state);
240
+ /**
241
+ * The guarded folder `file` lies in by its text, under any spelling of home, with the gate's state of that folder;
242
+ * `null` without a route and outside the guarded folders. Text only, without the disk.
243
+ */
244
+ export function guardedFolderOf(file) {
245
+ const route = routed;
246
+ return route === null ? null : folderOf(route, file);
247
+ }
248
+ /**
249
+ * The refusal a call on `file` meets for its folder alone, by its text and without the disk: the guarded folder it
250
+ * lies in, under any spelling of home, while the gate holds that folder closed. `null` without a route, outside the
251
+ * guarded folders and in a folder that is open or unknown. Metadata passes a closed folder, so a walk that must not
252
+ * enter one asks here before each segment.
253
+ */
254
+ export function closedFolderOf(file) {
255
+ const target = guardedFolderOf(file);
256
+ return target !== null && isClosed(target.state) ? new FolderGateError(target.folder, target.state) : null;
257
+ }
258
+ /** Codes of an `lstat` that finds no directory to read under the path. */
259
+ const NOTHING_UNDER_PATH = new Set(['ENOENT', 'ENOTDIR']);
260
+ /**
261
+ * Whether the directory a read by identity names stands under its path now. On macOS that read goes through
262
+ * `/.vol/<dev>/<ino>` and follows the directory wherever it went, so a directory moved into a guarded folder after
263
+ * its path was judged would be read there, by whichever process runs the read. The check is metadata in this process
264
+ * and runs in the same turn that starts the read; a move that lands between the two is not seen. An `lstat` that
265
+ * finds nothing gives `false`; any other error of it is the error of the read.
266
+ */
267
+ function standsUnderPath(args) {
268
+ let info;
269
+ try {
270
+ info = runDiskSync('lstat', { path: args.path });
271
+ }
272
+ catch (error) {
273
+ if (NOTHING_UNDER_PATH.has(error.code ?? ''))
274
+ return false;
275
+ throw error;
276
+ }
277
+ return info.isDirectory() && info.dev === args.dev && info.ino === args.ino;
278
+ }
279
+ /**
280
+ * Calls whose success shows that macOS lets the helper read the folder: a listing, or a regular file opened and read
281
+ * (`null`, no regular file opened, proves nothing). Metadata passes without consent. For a write, a change of mode, a
282
+ * removal and a read by identity it is not known whether macOS asks first, so they prove nothing either.
283
+ */
284
+ const PROVES_ACCESS = new Set(['readdir', 'readdirNames', 'readHead', 'openRead']);
285
+ /**
286
+ * Tells the gate that a folder nobody judged yet (`unknown`) answered a listing or a read, so it opens without a check
287
+ * of its own. Only when what was read lies in the folder on disk: a lookup in the folder never waits for consent, so
288
+ * a path that leaves it through a symlink inside it was read elsewhere and proves nothing. `realpath` is metadata.
289
+ */
290
+ function reportAccess(route, target, gen, op, args) {
291
+ if (target.state !== 'unknown' || !PROVES_ACCESS.has(op))
292
+ return;
293
+ let real;
294
+ try {
295
+ real = runDiskSync('realpathNative', { path: args.path });
296
+ }
297
+ catch {
298
+ return;
299
+ }
300
+ if (folderOf(route, real)?.folder === target.folder)
301
+ route.gate.report(target.folder, gen, 'ok');
302
+ }
303
+ /** The refusal of a call in `folder` the helper did not answer: the folder's closed state, else `fallback`. */
304
+ function refusal(route, folder, fallback) {
305
+ const state = route.gate.stateOf(folder)?.state;
306
+ return new FolderGateError(folder, state !== undefined && isClosed(state) ? state : fallback);
307
+ }
308
+ /**
309
+ * A helper's answer as a caller of `node:fs` sees it. A timeout, a helper that is gone and `EPERM` go to the gate
310
+ * first, with the generation the call went to; a call the helper did not answer is refused with the folder's state.
311
+ * A success goes to the gate from {@link settleCall}, which knows what the call read.
312
+ */
313
+ function settle(route, folder, gen, answer) {
314
+ switch (answer.kind) {
315
+ case 'ok':
316
+ return answer.value;
317
+ case 'fs-error':
318
+ if (answer.error.code === 'EPERM')
319
+ route.gate.report(folder, gen, 'eperm');
320
+ throw answer.error;
321
+ case 'timeout':
322
+ route.gate.report(folder, gen, 'timeout');
323
+ throw refusal(route, folder, 'waiting');
324
+ case 'gone':
325
+ route.gate.report(folder, gen, 'gone');
326
+ throw refusal(route, folder, 'unchecked');
327
+ }
328
+ }
329
+ /** {@link settle} for a call that names a path in `target`: a listing or read that succeeded may open the folder. */
330
+ function settleCall(route, target, gen, op, args, answer) {
331
+ if (answer.kind === 'ok' && answer.value !== null)
332
+ reportAccess(route, target, gen, op, args);
333
+ return settle(route, target.folder, gen, answer);
334
+ }
335
+ /** The target of a call that names a path; a closed folder refuses it here, without the disk. */
336
+ function openTarget(route, op, args) {
337
+ if (route === null || METADATA.has(op))
338
+ return null;
339
+ const target = targetFolder(route, args.path, followsLast(op, args));
340
+ if (target !== null && isClosed(target.state))
341
+ throw new FolderGateError(target.folder, target.state);
342
+ return target;
343
+ }
344
+ function gatedSync(op, args) {
345
+ const route = routed;
346
+ const target = openTarget(route, op, args);
347
+ if (route === null || target === null)
348
+ return runDiskSync(op, args);
349
+ const gen = route.client.generationOf(target.folder);
350
+ return settleCall(route, target, gen, op, args, route.client.callSync(target.folder, op, args));
351
+ }
352
+ /**
353
+ * Files open through the port, by the port's own handle number: a descriptor here and the handles of two helpers
354
+ * can carry the same number, so `read` and `close` find their file by the port's number.
355
+ */
356
+ const PORT_FILES = new Map();
357
+ let nextPortHandle = 1;
358
+ async function openPortFile(args) {
359
+ const route = routed;
360
+ const target = openTarget(route, 'openRead', args);
361
+ let helper = null;
362
+ let opened;
363
+ if (route === null || target === null) {
364
+ opened = await runDisk('openRead', args);
365
+ }
366
+ else {
367
+ // Read once, before the call: a helper of a later generation did not open the file.
368
+ helper = { route, folder: target.folder, gen: route.client.generationOf(target.folder) };
369
+ const answer = await route.client.call(helper.folder, 'openRead', args);
370
+ opened = settleCall(route, target, helper.gen, 'openRead', args, answer);
371
+ }
372
+ if (opened === null)
373
+ return null;
374
+ const handle = nextPortHandle++;
375
+ PORT_FILES.set(handle, { handle: opened.handle, helper });
376
+ return { handle, stats: opened.stats };
377
+ }
378
+ /**
379
+ * `close` of a file in a helper. A helper that no longer holds the file (killed, so the handle is stale, or gone) or
380
+ * does not answer (the gate kills it) closes nothing more, so the close succeeds: a caller that closes in `finally`
381
+ * keeps the refusal it is handling. The gate still hears of a timeout, `gone` and `EPERM`.
382
+ */
383
+ function settleClose(route, folder, gen, answer) {
384
+ if (answer.kind === 'ok' || (answer.kind === 'fs-error' && answer.error.code === 'EBADF'))
385
+ return;
386
+ if (answer.kind === 'timeout' || answer.kind === 'gone') {
387
+ route.gate.report(folder, gen, answer.kind);
388
+ return;
389
+ }
390
+ settle(route, folder, gen, answer);
391
+ }
392
+ /**
393
+ * `read` and `close` of a port handle, where the file was opened; a closed folder refuses a read. A file in a helper
394
+ * that ended (its generation is over, or the route was removed) went with it: a read gives `EBADF` and a close has
395
+ * nothing left to close, and neither reaches the folder's next helper, which may hold another file under that number.
396
+ */
397
+ async function onPortFile(op, args) {
398
+ const file = PORT_FILES.get(args.handle);
399
+ if (file === undefined)
400
+ throw badHandle(op);
401
+ if (op === 'close')
402
+ PORT_FILES.delete(args.handle);
403
+ const inner = { ...args, handle: file.handle };
404
+ if (file.helper === null)
405
+ return runDisk(op, inner);
406
+ const { route, folder, gen } = file.helper;
407
+ const ended = () => {
408
+ if (op === 'close')
409
+ return undefined;
410
+ throw badHandle(op);
411
+ };
412
+ if (routed !== route)
413
+ return ended();
414
+ if (op === 'read') {
415
+ // Before the generation: a folder that enters `waiting` gets a new helper, and its refusal names the state.
416
+ const state = route.gate.stateOf(folder)?.state;
417
+ if (state !== undefined && isClosed(state))
418
+ throw new FolderGateError(folder, state);
419
+ }
420
+ if (route.client.generationOf(folder) !== gen)
421
+ return ended();
422
+ const answer = await route.client.call(folder, op, inner, gen);
423
+ if (op === 'close') {
424
+ settleClose(route, folder, gen, answer);
425
+ return undefined;
426
+ }
427
+ return settle(route, folder, gen, answer);
428
+ }
429
+ async function gatedCall(op, args) {
430
+ if (op === 'openRead')
431
+ return await openPortFile(args);
432
+ if (op === 'read' || op === 'close') {
433
+ return await onPortFile(op, args);
434
+ }
435
+ const route = routed;
436
+ const target = openTarget(route, op, args);
437
+ if (route === null)
438
+ return runDisk(op, args);
439
+ // Checked after the walk and in the turn that starts the read, so nothing waits between the check and the read.
440
+ if (op === 'readdirByIdentity' && !standsUnderPath(args)) {
441
+ return null;
442
+ }
443
+ if (target === null)
444
+ return runDisk(op, args);
445
+ const gen = route.client.generationOf(target.folder);
446
+ return settleCall(route, target, gen, op, args, await route.client.call(target.folder, op, args));
447
+ }
448
+ /**
449
+ * The port of the work area. Without a route, every call on the disk of this process. With one, metadata and paths
450
+ * outside the guarded folders stay here, a closed folder refuses with `FolderGateError`, and the rest goes to the
451
+ * folder's helper; a read by identity runs only while the directory still stands under its path. A handle from
452
+ * `openRead` is the port's own number, valid only for `read` and `close` of the port, and only while the helper that
453
+ * opened the file lives.
454
+ */
455
+ export const DIRECT_DISK = { sync: gatedSync, call: gatedCall };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Which macOS-guarded folder of the home directory a path lies in: `gatedFolderOf`. The folder gate keys its state,
3
+ * its helpers and its refusals by that folder. The module only judges path text; it never touches the disk and never
4
+ * follows a symbolic link (the port walks links before it asks).
5
+ */
6
+ import path from 'node:path';
7
+ import { PROTECTED_HOME_DIRS, foldCase } from '../config/protected-dirs.js';
8
+ const BY_FOLDED_NAME = new Map(PROTECTED_HOME_DIRS.map((name) => [foldCase(name), name]));
9
+ /**
10
+ * The absolute path of the folder from `PROTECTED_HOME_DIRS` directly in `home` that `candidate` is or lies in, spelled
11
+ * as the list spells it (`H/DESKTOP/p` gives `H/Desktop`), or `null`. The name compares by `foldCase`, the same rule as
12
+ * `inProtectedFolder`; a relative `candidate` or `home`, home itself and a path outside home give `null`.
13
+ */
14
+ export function gatedFolderOf(candidate, home) {
15
+ if (!path.isAbsolute(candidate) || !path.isAbsolute(home))
16
+ return null;
17
+ const resolvedHome = path.resolve(home);
18
+ const relative = path.relative(resolvedHome, path.resolve(candidate));
19
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative))
20
+ return null;
21
+ const name = BY_FOLDED_NAME.get(foldCase(relative.split(path.sep)[0] ?? ''));
22
+ return name === undefined ? null : path.join(resolvedHome, name);
23
+ }