@rarog/server 1.0.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 (140) hide show
  1. package/README.md +18 -5
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +64 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  6. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  7. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  8. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  9. package/node_modules/@rarog/shared/src/protocol.js +20 -47
  10. package/node_modules/@rarog/shared/src/rest.js +106 -12
  11. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  12. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +21 -0
  14. package/package.json +3 -3
  15. package/server/src/auth/admin.js +3 -1
  16. package/server/src/bootstrap/consent.js +99 -2
  17. package/server/src/bootstrap/folder-gate.js +55 -0
  18. package/server/src/bootstrap/http.js +3 -2
  19. package/server/src/bootstrap/inbox.js +29 -4
  20. package/server/src/bootstrap/sse.js +2 -1
  21. package/server/src/cli/doctor-no-hook.js +162 -0
  22. package/server/src/cli/doctor.js +2 -0
  23. package/server/src/cli/service-log.js +27 -0
  24. package/server/src/cli/service.js +5 -2
  25. package/server/src/cli/templates/launchd.plist +1 -1
  26. package/server/src/cli/templates/rarog.service +1 -1
  27. package/server/src/cli/update-channel.js +100 -0
  28. package/server/src/cli/update-provenance.js +37 -19
  29. package/server/src/cli/update-registry.js +160 -62
  30. package/server/src/cli/update.js +13 -3
  31. package/server/src/companion/turns-settle.js +4 -1
  32. package/server/src/companion/turns.js +36 -5
  33. package/server/src/config/files.js +32 -0
  34. package/server/src/config/flags.js +10 -1
  35. package/server/src/config/protected-dirs.js +2 -0
  36. package/server/src/config/roots.js +13 -8
  37. package/server/src/config/work-area.js +36 -12
  38. package/server/src/config-env.js +33 -0
  39. package/server/src/config.js +22 -2
  40. package/server/src/demo/control.js +9 -1
  41. package/server/src/demo/files.js +49 -0
  42. package/server/src/demo/inbox.js +73 -0
  43. package/server/src/demo/review-routes.js +6 -1
  44. package/server/src/device-effects.js +3 -1
  45. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  46. package/server/src/drivers/herdr/consent-no-hook.js +411 -0
  47. package/server/src/drivers/herdr/refusals.js +226 -0
  48. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  49. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  50. package/server/src/drivers/herdr-driver.js +193 -295
  51. package/server/src/files/file-index.js +248 -0
  52. package/server/src/files/ignored.js +119 -0
  53. package/server/src/files/listing.js +82 -0
  54. package/server/src/files/path-rule.js +199 -0
  55. package/server/src/files/refusals.js +50 -0
  56. package/server/src/files/send-file.js +115 -0
  57. package/server/src/files/session-download.js +51 -0
  58. package/server/src/files/session-files.js +38 -0
  59. package/server/src/files/session-gate.js +53 -0
  60. package/server/src/folder-gate/client.js +314 -0
  61. package/server/src/folder-gate/disk.js +455 -0
  62. package/server/src/folder-gate/folders.js +23 -0
  63. package/server/src/folder-gate/gate.js +220 -0
  64. package/server/src/folder-gate/helper.js +118 -0
  65. package/server/src/folder-gate/install.js +27 -0
  66. package/server/src/folder-gate/relay-worker.js +147 -0
  67. package/server/src/folder-gate/types.js +115 -0
  68. package/server/src/folder-gate/wire.js +170 -0
  69. package/server/src/fs-browse.js +55 -23
  70. package/server/src/fs-mkdir.js +3 -1
  71. package/server/src/git-status.js +16 -7
  72. package/server/src/git-watch.js +130 -19
  73. package/server/src/git-work-tree.js +3 -3
  74. package/server/src/herdr/audit.js +1 -1
  75. package/server/src/herdr/client.js +2 -2
  76. package/server/src/herdr/commands/discover.js +21 -9
  77. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  78. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  79. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  80. package/server/src/herdr/dialogs/index.js +12 -2
  81. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  82. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +166 -86
  83. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  84. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  85. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  86. package/server/src/herdr/dialogs/no-hook.js +63 -0
  87. package/server/src/herdr/dialogs/router.js +21 -6
  88. package/server/src/herdr/dialogs/screen/block.js +10 -0
  89. package/server/src/herdr/dialogs/screen/parse.js +33 -3
  90. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  91. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  92. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  93. package/server/src/herdr/jsonl-follow.js +55 -14
  94. package/server/src/herdr/jsonl-pending.js +25 -1
  95. package/server/src/herdr/provenance.js +3 -3
  96. package/server/src/herdr/socket.js +25 -28
  97. package/server/src/herdr/supervisor.js +13 -10
  98. package/server/src/herdr/transcript-path.js +36 -0
  99. package/server/src/herdr/trust.js +11 -8
  100. package/server/src/herdr/uploads-registry.js +3 -2
  101. package/server/src/herdr/uploads.js +170 -47
  102. package/server/src/inbox/card.js +18 -9
  103. package/server/src/inbox/dialogs.js +40 -12
  104. package/server/src/inbox/heads.js +55 -0
  105. package/server/src/inbox/inbox.js +24 -2
  106. package/server/src/inbox/index.js +3 -1
  107. package/server/src/index.js +44 -21
  108. package/server/src/install/repair.js +8 -0
  109. package/server/src/iroh/listener.js +3 -0
  110. package/server/src/iroh/log-budget.js +1 -0
  111. package/server/src/iroh/socket.js +2 -1
  112. package/server/src/log-timestamps.js +9 -4
  113. package/server/src/notes/store.js +3 -2
  114. package/server/src/router.js +20 -2
  115. package/server/src/routes/devices.js +2 -2
  116. package/server/src/routes/inbox.js +91 -0
  117. package/server/src/routes/projects.js +5 -1
  118. package/server/src/routes/sessions.js +145 -18
  119. package/server/src/routes/system.js +9 -4
  120. package/server/src/safe-read.js +86 -1
  121. package/server/src/sessions/companion-scope.js +16 -7
  122. package/server/src/sessions/demo-modules.js +16 -0
  123. package/server/src/sessions/diff-measure.js +30 -0
  124. package/server/src/sessions/done-retention.js +57 -0
  125. package/server/src/sessions/launch-gate.js +2 -2
  126. package/server/src/sessions/manager.js +78 -190
  127. package/server/src/sessions/project-scan.js +9 -3
  128. package/server/src/sessions/ring-buffer.js +5 -3
  129. package/server/src/sessions/seen-marks.js +9 -6
  130. package/server/src/sessions/session-git.js +31 -2
  131. package/server/src/sessions/session-scope.js +30 -0
  132. package/server/src/sessions/session.js +19 -0
  133. package/server/src/sessions/state-sentences.js +1 -1
  134. package/server/src/sessions/waiting-line.js +72 -0
  135. package/server/src/sse.js +143 -10
  136. package/server/src/term/herdr-backend.js +2 -2
  137. package/server/src/term/index.js +2 -15
  138. package/server/src/term/registry.js +4 -3
  139. package/server/src/term/ws.js +9 -1
  140. package/server/src/version.js +30 -0
@@ -0,0 +1,248 @@
1
+ import { MAX_FILE_ENTRIES } from '@rarog/shared';
2
+ import { listSessionDir } from './listing.js';
3
+ import { FILES_DISK } from './path-rule.js';
4
+ import { isClosedFolder } from './refusals.js';
5
+ import { filesSession } from './session-gate.js';
6
+ export const FILE_INDEX_LIMITS = {
7
+ maxFiles: 20_000, maxBodyBytes: 2 * 1024 * 1024, budgetMs: 3_000, maxEntries: MAX_FILE_ENTRIES,
8
+ };
9
+ /**
10
+ * The files git does not ignore under the directory it runs in: tracked ones (`--cached`) and untracked ones that no
11
+ * ignore rule matches (`--others --exclude-standard`), NUL-separated (`-z`), so a name is never quoted. A submodule
12
+ * comes as one path (its gitlink) and an untracked nested repository as its path with a trailing `/`: git lists
13
+ * neither's files.
14
+ */
15
+ export const LS_FILES_COMMAND = {
16
+ sub: 'ls-files', rest: ['-z', '--cached', '--others', '--exclude-standard'],
17
+ };
18
+ const emptyDir = () => ({ listed: new Set(), repos: new Set(), dirs: new Map() });
19
+ /** The tree from one `ls-files` read, or `null` when git did not answer it whole (then the walk keeps every file). */
20
+ export function gitScope(result) {
21
+ if (result.exitCode !== 0 || result.capped === true || result.timedOut === true)
22
+ return null;
23
+ const top = emptyDir();
24
+ for (const record of result.stdout.split('\0')) {
25
+ if (record === '')
26
+ continue;
27
+ const repo = record.endsWith('/');
28
+ const segments = (repo ? record.slice(0, -1) : record).split('/');
29
+ const last = segments.pop() ?? '';
30
+ let dir = top;
31
+ for (const segment of segments) {
32
+ const known = dir.dirs.get(segment);
33
+ const next = known ?? emptyDir();
34
+ if (known === undefined)
35
+ dir.dirs.set(segment, next);
36
+ dir = next;
37
+ }
38
+ (repo ? dir.repos : dir.listed).add(last);
39
+ }
40
+ return top;
41
+ }
42
+ /**
43
+ * The key two spellings of one name share: the Unicode form (git on macOS reports a decomposed name composed,
44
+ * `core.precomposeunicode`) and the letter case (`core.ignorecase` keeps a name renamed only in case under its old
45
+ * spelling).
46
+ */
47
+ const folded = (name) => name.normalize('NFC').toLowerCase();
48
+ /**
49
+ * The git names of one directory mapped to the names of its listing: a git name goes to the entry with exactly its
50
+ * bytes, else to the one entry that no git name matched exactly and has the same folded key; with two or more such
51
+ * entries, to none. An entry no git name maps to stays out, so two names on disk that one key would merge never
52
+ * both enter on one git name.
53
+ */
54
+ function matchNames(gitNames, diskNames) {
55
+ const onDisk = new Set(diskNames);
56
+ const mapped = new Map();
57
+ const add = (disk, name) => {
58
+ const names = mapped.get(disk);
59
+ if (names === undefined)
60
+ mapped.set(disk, [name]);
61
+ else
62
+ names.push(name);
63
+ };
64
+ const loose = [];
65
+ for (const name of gitNames) {
66
+ if (onDisk.has(name))
67
+ add(name, name);
68
+ else
69
+ loose.push(name);
70
+ }
71
+ if (loose.length === 0)
72
+ return mapped;
73
+ const byKey = new Map();
74
+ for (const disk of diskNames) {
75
+ if (mapped.has(disk))
76
+ continue;
77
+ const key = folded(disk);
78
+ byKey.set(key, [...(byKey.get(key) ?? []), disk]);
79
+ }
80
+ for (const name of loose) {
81
+ const candidates = byKey.get(folded(name)) ?? [];
82
+ if (candidates.length === 1)
83
+ add(candidates[0], name);
84
+ }
85
+ return mapped;
86
+ }
87
+ /** Every git name of the directories `git` mapped to the names of a listing ({@link matchNames}). */
88
+ function namesOf(git, diskNames) {
89
+ const gitNames = new Set();
90
+ for (const one of git)
91
+ for (const name of [...one.listed, ...one.repos, ...one.dirs.keys()])
92
+ gitNames.add(name);
93
+ return matchNames(gitNames, diskNames);
94
+ }
95
+ /**
96
+ * How a directory of a narrowed listing goes on, from the git names mapped to it: walked whole when git named it as a
97
+ * path (a submodule's gitlink) or as a nested repository, walked narrowed when git has files under it, else not.
98
+ */
99
+ function nextDir(git, gitNames, rel) {
100
+ const below = [];
101
+ for (const one of git) {
102
+ for (const name of gitNames) {
103
+ if (one.listed.has(name) || one.repos.has(name))
104
+ return { rel, narrowed: false, git: [] };
105
+ const dir = one.dirs.get(name);
106
+ if (dir !== undefined)
107
+ below.push(dir);
108
+ }
109
+ }
110
+ return below.length === 0 ? null : { rel, narrowed: true, git: below };
111
+ }
112
+ /** The index under construction: the paths, the bytes of the body they make, and whether a ceiling cut it. */
113
+ class IndexBody {
114
+ paths = [];
115
+ truncated = false;
116
+ #limits;
117
+ #maxBytes;
118
+ #bytes;
119
+ constructor(limits, maxBytes) {
120
+ this.#limits = limits;
121
+ this.#maxBytes = maxBytes;
122
+ // The body with no path, `"truncated":false` being the longer of the two values.
123
+ this.#bytes = Buffer.byteLength(JSON.stringify({ paths: [], truncated: false, maxBytes }));
124
+ }
125
+ /** Adds `rel`, or marks the body cut and returns `false` when it would pass a ceiling. */
126
+ add(rel) {
127
+ const cost = Buffer.byteLength(JSON.stringify(rel)) + (this.paths.length === 0 ? 0 : 1);
128
+ if (this.paths.length >= this.#limits.maxFiles || this.#bytes + cost > this.#limits.maxBodyBytes) {
129
+ this.truncated = true;
130
+ return false;
131
+ }
132
+ this.paths.push(rel);
133
+ this.#bytes += cost;
134
+ return true;
135
+ }
136
+ value() {
137
+ return { paths: this.paths, truncated: this.truncated, maxBytes: this.#maxBytes };
138
+ }
139
+ }
140
+ /**
141
+ * The walk of the session directory of `area`. A directory whose listing is refused (swapped, gone) is skipped; a
142
+ * refused session directory is the answer, and so is a guarded folder that closes during the walk: an index cut
143
+ * there would read as complete. The budget runs from before the git read and is checked between two directories, so
144
+ * the session directory is always listed.
145
+ */
146
+ async function walk(area, maxBytes, run, limits, now, disk) {
147
+ const startedAt = now();
148
+ let scope;
149
+ try {
150
+ scope = gitScope(await run(LS_FILES_COMMAND, area.realCwd));
151
+ }
152
+ catch {
153
+ scope = null;
154
+ }
155
+ const body = new IndexBody(limits, maxBytes);
156
+ const queue = [{ rel: '', narrowed: scope !== null, git: scope === null ? [] : [scope] }];
157
+ for (let next = 0; next < queue.length; next += 1) {
158
+ if (next > 0 && now() - startedAt > limits.budgetMs) {
159
+ body.truncated = true;
160
+ break;
161
+ }
162
+ const dir = queue[next];
163
+ const listing = await listSessionDir(area, dir.rel, { maxBytes, maxEntries: limits.maxEntries }, disk);
164
+ if (!listing.ok) {
165
+ if (dir.rel === '' || isClosedFolder(listing.refusal))
166
+ return listing;
167
+ continue;
168
+ }
169
+ if (listing.value.truncated)
170
+ body.truncated = true;
171
+ const names = dir.narrowed ? namesOf(dir.git, listing.value.entries.map((entry) => entry.name)) : null;
172
+ for (const entry of listing.value.entries) {
173
+ const rel = dir.rel === '' ? entry.name : `${dir.rel}/${entry.name}`;
174
+ const gitNames = names?.get(entry.name);
175
+ if (names !== null && gitNames === undefined)
176
+ continue;
177
+ if (entry.kind === 'dir') {
178
+ const pending = gitNames === undefined ? { rel, narrowed: false, git: [] } : nextDir(dir.git, gitNames, rel);
179
+ if (pending !== null)
180
+ queue.push(pending);
181
+ continue;
182
+ }
183
+ if (gitNames !== undefined && !dir.git.some((one) => gitNames.some((name) => one.listed.has(name))))
184
+ continue;
185
+ if (!body.add(rel))
186
+ return { ok: true, value: body.value() };
187
+ }
188
+ }
189
+ return { ok: true, value: body.value() };
190
+ }
191
+ /** The demo index: every file of the demo data its git does not ignore, breadth first as on a server. */
192
+ function demoIndex(maxBytes, entriesOf) {
193
+ const paths = [];
194
+ const queue = [''];
195
+ for (let next = 0; next < queue.length; next += 1) {
196
+ const dir = queue[next];
197
+ for (const entry of entriesOf(dir) ?? []) {
198
+ if (entry.ignored === true)
199
+ continue;
200
+ const rel = dir === '' ? entry.name : `${dir}/${entry.name}`;
201
+ if (entry.kind === 'dir')
202
+ queue.push(rel);
203
+ else
204
+ paths.push(rel);
205
+ }
206
+ }
207
+ return { ok: true, value: { paths, truncated: false, maxBytes } };
208
+ }
209
+ /** The index route's walks: one per session and directory at a time, never kept after it answers. */
210
+ export class SessionFileIndex {
211
+ #limits;
212
+ #now;
213
+ #disk;
214
+ #walks = new Map();
215
+ constructor(opts = {}) {
216
+ this.#limits = { ...FILE_INDEX_LIMITS, ...opts.limits };
217
+ this.#now = opts.now ?? (() => Date.now());
218
+ this.#disk = opts.disk ?? FILES_DISK;
219
+ }
220
+ /**
221
+ * The index of the session `id` with `maxBytes` announced. The gate runs for every request, before any disk call:
222
+ * an unknown session throws the manager's 404 (`port.require`), a Codex entry, a pane out of scope and a session
223
+ * without a pane are refused. A request while a walk of the same session directory runs gets that walk's answer.
224
+ */
225
+ index(id, maxBytes, port) {
226
+ let gate;
227
+ try {
228
+ gate = filesSession(id, port, this.#disk.area);
229
+ }
230
+ catch (error) {
231
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
232
+ }
233
+ if (gate.kind === 'refused')
234
+ return Promise.resolve({ ok: false, refusal: gate.refusal });
235
+ if (gate.kind === 'demo')
236
+ return Promise.resolve(demoIndex(maxBytes, port.demoEntries));
237
+ const key = JSON.stringify([id, gate.area.realCwd, maxBytes]);
238
+ const running = this.#walks.get(key);
239
+ if (running !== undefined)
240
+ return running;
241
+ const started = walk(gate.area, maxBytes, port.run, this.#limits, this.#now, this.#disk).finally(() => {
242
+ if (this.#walks.get(key) === started)
243
+ this.#walks.delete(key);
244
+ });
245
+ this.#walks.set(key, started);
246
+ return started;
247
+ }
248
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Names per `check-ignore` process. The runner gives git no stdin, so the names go as arguments; 200 names of at
3
+ * most 255 bytes each stay far below the argument limit of the system.
4
+ */
5
+ export const CHECK_IGNORE_BATCH = 200;
6
+ /** What stands before every name: the listed directory itself, so the argument is never pathspec magic. */
7
+ const HERE = './';
8
+ /**
9
+ * One batch: every name after `--` and after `./`. `check-ignore` refuses `--literal-pathspecs` (git 2.54.0: "pathspec
10
+ * magic not supported by this command: 'literal'"), and a name that starts with `:` would be read as magic (`:!x`
11
+ * kills the batch); `./` keeps it a path in the listed directory, and `--` keeps a name that starts with `-` from
12
+ * being an option. Git prints each reported path as given, `./` included.
13
+ */
14
+ export function checkIgnoreCommand(names) {
15
+ return { sub: 'check-ignore', rest: ['--', ...names.map((name) => `${HERE}${name}`)] };
16
+ }
17
+ /** The escapes of git's C-style quoting (`quote_c_style`) other than the three octal digits of a byte. */
18
+ const ESCAPES = {
19
+ a: 0x07, b: 0x08, t: 0x09, n: 0x0a, v: 0x0b, f: 0x0c, r: 0x0d, '"': 0x22, '\\': 0x5c,
20
+ };
21
+ /**
22
+ * A path as `check-ignore` prints it: as given, or in C-style quotes when it holds a byte git quotes (a byte over
23
+ * 0x7f under `core.quotePath`, `"`, `\`, a control character). `null` for a line that is not a valid quoted path.
24
+ */
25
+ export function unquotedPath(line) {
26
+ if (!line.startsWith('"'))
27
+ return line;
28
+ if (line.length < 2 || !line.endsWith('"'))
29
+ return null;
30
+ const chars = [...line.slice(1, -1)];
31
+ const bytes = [];
32
+ for (let i = 0; i < chars.length; i += 1) {
33
+ const char = chars[i] ?? '';
34
+ if (char !== '\\') {
35
+ bytes.push(...Buffer.from(char, 'utf8'));
36
+ continue;
37
+ }
38
+ const octal = chars.slice(i + 1, i + 4).join('');
39
+ if (/^[0-3][0-7]{2}$/.test(octal)) {
40
+ bytes.push(Number.parseInt(octal, 8));
41
+ i += 3;
42
+ continue;
43
+ }
44
+ const escaped = ESCAPES[chars[i + 1] ?? ''];
45
+ if (escaped === undefined)
46
+ return null;
47
+ bytes.push(escaped);
48
+ i += 1;
49
+ }
50
+ return Buffer.from(bytes).toString('utf8');
51
+ }
52
+ /**
53
+ * The names one batch reported, or `null` for a failed read. `-z` would give raw bytes, but git takes it only with
54
+ * `--stdin`, so the output is one path per line. Exit code 0: the paths on stdout; 1: none of the names is ignored;
55
+ * anything else (128 outside a repository or on a broken one, no exit code, a read cut at its cap) is a failure.
56
+ */
57
+ function reportedNames(result) {
58
+ if (result.capped === true || result.timedOut === true)
59
+ return null;
60
+ if (result.exitCode === 1)
61
+ return [];
62
+ if (result.exitCode !== 0)
63
+ return null;
64
+ const names = [];
65
+ for (const line of result.stdout.split('\n')) {
66
+ if (line === '')
67
+ continue;
68
+ const path = unquotedPath(line);
69
+ if (path?.startsWith(HERE) !== true)
70
+ return null;
71
+ names.push(path.slice(HERE.length));
72
+ }
73
+ return names;
74
+ }
75
+ /** The names of `names` git ignores in `dir`, or `null` when one batch failed. */
76
+ export async function ignoredNames(dir, names, run) {
77
+ const wanted = new Set(names);
78
+ // Git on macOS (`core.precomposeunicode`) reports a decomposed name composed: such a name maps back to the entry
79
+ // when exactly one entry composes to it, and gets no label when two do.
80
+ const composed = new Map();
81
+ for (const name of names) {
82
+ const key = name.normalize('NFC');
83
+ composed.set(key, composed.has(key) ? null : name);
84
+ }
85
+ const ignored = new Set();
86
+ for (let start = 0; start < names.length; start += CHECK_IGNORE_BATCH) {
87
+ let result;
88
+ try {
89
+ result = await run(checkIgnoreCommand(names.slice(start, start + CHECK_IGNORE_BATCH)), dir);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ const reported = reportedNames(result);
95
+ if (reported === null)
96
+ return null;
97
+ for (const name of reported) {
98
+ const entry = wanted.has(name) ? name : composed.get(name);
99
+ if (entry)
100
+ ignored.add(entry);
101
+ }
102
+ }
103
+ return ignored;
104
+ }
105
+ /**
106
+ * `listing` with `ignored: true` on every entry git ignores in `dir`, the directory on disk the listing read. An
107
+ * empty listing runs no git; a failed read gives the listing without labels.
108
+ */
109
+ export async function labelIgnored(listing, dir, run) {
110
+ if (listing.entries.length === 0)
111
+ return listing;
112
+ const ignored = await ignoredNames(dir, listing.entries.map((entry) => entry.name), run);
113
+ if (ignored === null || ignored.size === 0)
114
+ return listing;
115
+ return {
116
+ ...listing,
117
+ entries: listing.entries.map((entry) => (ignored.has(entry.name) ? { ...entry, ignored: true } : entry)),
118
+ };
119
+ }
@@ -0,0 +1,82 @@
1
+ import path from 'node:path';
2
+ import { MAX_FILE_ENTRIES, compareFileEntries } from '@rarog/shared';
3
+ import { insideWorkArea } from '../config/work-area.js';
4
+ import { FolderGateError } from '../folder-gate/types.js';
5
+ import { FILES_DISK, inAreaText, isHiddenName, resolveSessionDir, stillSessionDir, } from './path-rule.js';
6
+ import { NOT_FOUND, closedFolder } from './refusals.js';
7
+ /** The name as a string when its bytes are valid UTF-8, otherwise `null`. */
8
+ function utf8Name(bytes) {
9
+ const name = bytes.toString('utf8');
10
+ return Buffer.from(name, 'utf8').equals(bytes) ? name : null;
11
+ }
12
+ /**
13
+ * The entries of the directory, read through its identity: `[]` for a directory the server may not read (`EACCES`,
14
+ * `EPERM`), as in the directory browser; `null` (404) when the read cannot be bound to the directory the walk found
15
+ * (another platform, another directory under the path now) or fails otherwise; the refusal of a guarded folder the
16
+ * folder gate holds closed, never an empty listing. Never a read by path.
17
+ */
18
+ async function entriesOf(dir, disk) {
19
+ try {
20
+ return await disk.readdirByIdentity(dir);
21
+ }
22
+ catch (error) {
23
+ if (error instanceof FolderGateError)
24
+ return error;
25
+ const code = error?.code;
26
+ return code === 'EACCES' || code === 'EPERM' ? [] : null;
27
+ }
28
+ }
29
+ /**
30
+ * An entry of the listing, or `null` for one the server leaves out. Its `lstat` under the directory's path must show
31
+ * the kind the read gave: an entry swapped for a symlink since the read drops. The device is not compared, because a
32
+ * mount point under the session directory is a directory the path rule allows, on a device of its own.
33
+ */
34
+ async function entryOf(area, dir, name, kind, disk) {
35
+ if (isHiddenName(name))
36
+ return null;
37
+ if (!inAreaText(area, path.join(dir.path, name)))
38
+ return null;
39
+ if (!insideWorkArea(path.join(dir.real, name), area.realRoots, area.realHome))
40
+ return null;
41
+ try {
42
+ const info = await disk.lstat(path.join(dir.real, name));
43
+ if (kind === 'dir')
44
+ return info.isDirectory() ? { name, kind } : null;
45
+ return info.isFile() && info.nlink === 1n ? { name, kind, size: Number(info.size) } : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ /**
52
+ * Lists the directory `rel` of the session (`''` = the session directory). A directory the server may not read gives
53
+ * an empty listing, as in the directory browser; a directory swapped while it was read gives 404.
54
+ */
55
+ export async function listSessionDir(area, rel, opts, disk = FILES_DISK) {
56
+ const dir = await resolveSessionDir(area, rel, disk);
57
+ if (!dir.ok)
58
+ return dir;
59
+ const read = await entriesOf(dir.value, disk);
60
+ if (read === null)
61
+ return { ok: false, refusal: NOT_FOUND };
62
+ if (read instanceof FolderGateError)
63
+ return { ok: false, refusal: closedFolder(read) };
64
+ const pending = [];
65
+ for (const entry of read) {
66
+ const name = utf8Name(entry.name);
67
+ if (name === null)
68
+ continue;
69
+ if (entry.isDirectory())
70
+ pending.push(entryOf(area, dir.value, name, 'dir', disk));
71
+ else if (entry.isFile())
72
+ pending.push(entryOf(area, dir.value, name, 'file', disk));
73
+ }
74
+ const entries = (await Promise.all(pending)).filter((entry) => entry !== null).sort(compareFileEntries);
75
+ if (!(await stillSessionDir(dir.value, disk)))
76
+ return { ok: false, refusal: NOT_FOUND };
77
+ const max = opts.maxEntries ?? MAX_FILE_ENTRIES;
78
+ return {
79
+ ok: true,
80
+ value: { dir: rel, entries: entries.slice(0, max), truncated: entries.length > max, maxBytes: opts.maxBytes },
81
+ };
82
+ }
@@ -0,0 +1,199 @@
1
+ import path from 'node:path';
2
+ import { areaDiskOf, insideWorkArea, resolveInWorkArea } from '../config/work-area.js';
3
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
4
+ import { FolderGateError } from '../folder-gate/types.js';
5
+ import { validateDiffPath } from '../git-diff.js';
6
+ import { BAD_PATH, NOT_FOUND, closedFolder } from './refusals.js';
7
+ /**
8
+ * The rule's view of the work-area disk port. `realpath` is the native one (`fs.promises.realpath`, letter case of
9
+ * the disk), the walk's `area.realpath` the JavaScript one. The open of a file gives the port's handle, which the
10
+ * download reads and closes through the same port.
11
+ */
12
+ export function filesDiskOf(disk) {
13
+ return {
14
+ // `buffer` gives every name as bytes.
15
+ readdir: async (dir) => [...await disk.call('readdir', { path: dir, encoding: 'buffer' })],
16
+ readdirByIdentity: async (dir) => {
17
+ const entries = await disk.call('readdirByIdentity', { path: dir.real, dev: dir.dev, ino: dir.ino });
18
+ return entries === null ? null : [...entries];
19
+ },
20
+ lstat: (file) => disk.call('lstat', { path: file }),
21
+ stat: (file) => disk.call('stat', { path: file }),
22
+ realpath: (file) => disk.call('realpathNative', { path: file }),
23
+ open: async (file) => {
24
+ const opened = await disk.call('openRead', { path: file, followSymlink: false });
25
+ if (opened === null)
26
+ return null;
27
+ const { handle } = opened;
28
+ return {
29
+ handle: {
30
+ read: (length, position) => disk.call('read', { handle, length, position }),
31
+ close: () => disk.call('close', { handle }),
32
+ },
33
+ stats: opened.stats,
34
+ };
35
+ },
36
+ area: areaDiskOf(disk),
37
+ };
38
+ }
39
+ export const FILES_DISK = filesDiskOf(DIRECT_DISK);
40
+ const refused = (refusal) => ({ ok: false, refusal });
41
+ /** Step 1: the segments of the path, or `null` for 400. `''` is the session directory where `allowEmpty`. */
42
+ function segmentsOf(rel, allowEmpty) {
43
+ if (rel === '')
44
+ return allowEmpty ? [] : null;
45
+ if (validateDiffPath(rel) === null)
46
+ return null;
47
+ const segments = rel.split('/');
48
+ return segments.includes('') ? null : segments;
49
+ }
50
+ /**
51
+ * Step 1 alone, for the demo, which has no disk: the refusal of a path that fails the shape check, or `null`. `''`
52
+ * is the session directory where `allowEmpty`.
53
+ */
54
+ export function shapeRefusal(rel, allowEmpty) {
55
+ return segmentsOf(rel, allowEmpty) === null ? BAD_PATH : null;
56
+ }
57
+ /** The text of a name the server never shows: it starts with a dot, or it is `node_modules` in any letter case. */
58
+ export function isHiddenName(name) {
59
+ return name.startsWith('.') || name.toLowerCase() === 'node_modules';
60
+ }
61
+ /**
62
+ * Whether `file` lies in the work area, as text, against the roots in both forms and the configured home, as the
63
+ * session gate asks about the session directory (`inWorkAreaOnDisk`). No disk call.
64
+ */
65
+ export function inAreaText(area, file) {
66
+ return insideWorkArea(file, [...area.roots, ...area.realRoots], area.home);
67
+ }
68
+ /** Steps 1 and 2: the segments of a path that may go to the disk, or the refusal. */
69
+ function checkText(area, rel, allowEmpty) {
70
+ const segments = segmentsOf(rel, allowEmpty);
71
+ if (segments === null)
72
+ return refused(BAD_PATH);
73
+ if (segments.some(isHiddenName))
74
+ return refused(NOT_FOUND);
75
+ if (!inAreaText(area, path.join(area.cwd, ...segments)))
76
+ return refused(NOT_FOUND);
77
+ // The on-disk form against the on-disk home, so a home reached through a symlink keeps its protected folders.
78
+ if (!insideWorkArea(path.join(area.realCwd, ...segments), area.realRoots, area.realHome))
79
+ return refused(NOT_FOUND);
80
+ return { ok: true, value: segments };
81
+ }
82
+ /** The value of a disk call, or `null` for any error but the refusal of a closed folder, which goes on. */
83
+ async function attempt(call) {
84
+ try {
85
+ return await call();
86
+ }
87
+ catch (error) {
88
+ if (error instanceof FolderGateError)
89
+ throw error;
90
+ return null;
91
+ }
92
+ }
93
+ /** The answer of `rule`, or the refusal of a closed folder any of its disk calls met. */
94
+ async function orClosed(rule) {
95
+ try {
96
+ return await rule();
97
+ }
98
+ catch (error) {
99
+ if (error instanceof FolderGateError)
100
+ return refused(closedFolder(error));
101
+ throw error;
102
+ }
103
+ }
104
+ /** Step 3: the walk down from `cwd` and the path on disk, or `null` for 404. */
105
+ async function walk(area, segments, last, disk) {
106
+ let current = area.cwd;
107
+ for (const [index, segment] of segments.entries()) {
108
+ const entries = await attempt(() => disk.readdir(current));
109
+ const wanted = Buffer.from(segment, 'utf8');
110
+ if (entries?.some((entry) => entry.name.equals(wanted)) !== true)
111
+ return null;
112
+ const next = path.join(current, segment);
113
+ const info = await attempt(() => disk.lstat(next));
114
+ if (info === null || info.isSymbolicLink())
115
+ return null;
116
+ const isLast = index === segments.length - 1;
117
+ if (isLast && last === 'file' ? !info.isFile() : !info.isDirectory())
118
+ return null;
119
+ current = next;
120
+ }
121
+ const resolved = resolveInWorkArea(current, area.realRoots, area.realHome, disk.area);
122
+ if (resolved.kind === 'excluded' && resolved.closed !== undefined)
123
+ throw resolved.closed;
124
+ if (resolved.kind !== 'resolved')
125
+ return null;
126
+ const real = await attempt(() => disk.realpath(current));
127
+ if (real !== path.join(area.realCwd, ...segments))
128
+ return null;
129
+ if (!insideWorkArea(real, area.realRoots, area.realHome))
130
+ return null;
131
+ return { path: current, real };
132
+ }
133
+ /** Steps 1 to 3 for a directory: the listing's directory (`''` = the session directory) or the refusal. */
134
+ export async function resolveSessionDir(area, rel, disk = FILES_DISK) {
135
+ const text = checkText(area, rel, true);
136
+ if (!text.ok)
137
+ return text;
138
+ const segments = text.value;
139
+ return orClosed(async () => {
140
+ const walked = await walk(area, segments, 'dir', disk);
141
+ if (walked === null)
142
+ return refused(NOT_FOUND);
143
+ const info = await attempt(() => disk.stat(walked.real));
144
+ if (info === null || !info.isDirectory())
145
+ return refused(NOT_FOUND);
146
+ return { ok: true, value: { rel, segments, path: walked.path, real: walked.real, dev: info.dev, ino: info.ino } };
147
+ });
148
+ }
149
+ /**
150
+ * Whether `dir` is still the directory the walk found: `realpath` of its path gives the same directory on disk with
151
+ * the same `dev` and `ino`. The listing asks after its read of the entries, as the open does after the open.
152
+ */
153
+ export async function stillSessionDir(dir, disk = FILES_DISK) {
154
+ try {
155
+ const real = await attempt(() => disk.realpath(dir.path));
156
+ if (real !== dir.real)
157
+ return false;
158
+ const info = await attempt(() => disk.stat(real));
159
+ return info !== null && info.isDirectory() && info.dev === dir.dev && info.ino === dir.ino;
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ /** Steps 1 to 5 for a file: the open file, or the refusal with no descriptor left open. */
166
+ export async function openSessionFile(area, rel, disk = FILES_DISK) {
167
+ const text = checkText(area, rel, false);
168
+ if (!text.ok)
169
+ return text;
170
+ const segments = text.value;
171
+ return orClosed(async () => {
172
+ const walked = await walk(area, segments, 'file', disk);
173
+ if (walked === null)
174
+ return refused(NOT_FOUND);
175
+ const opened = await attempt(() => disk.open(walked.real));
176
+ if (opened === null)
177
+ return refused(NOT_FOUND);
178
+ const { handle, stats } = opened;
179
+ let same = false;
180
+ try {
181
+ same = stats.nlink <= 1n && await sameFileAgain(walked, stats, disk);
182
+ }
183
+ finally {
184
+ if (!same)
185
+ await handle.close();
186
+ }
187
+ if (!same)
188
+ return refused(NOT_FOUND);
189
+ return { ok: true, value: { handle, size: Number(stats.size), stats } };
190
+ });
191
+ }
192
+ /** Step 5: the path resolves to the same place, and that place is the file the descriptor holds. */
193
+ async function sameFileAgain(walked, opened, disk) {
194
+ const real = await attempt(() => disk.realpath(walked.path));
195
+ if (real !== walked.real)
196
+ return false;
197
+ const info = await attempt(() => disk.stat(real));
198
+ return info !== null && info.dev === opened.dev && info.ino === opened.ino;
199
+ }