@rarog/server 1.0.1 → 1.1.0-beta.1

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 (78) hide show
  1. package/README.md +4 -3
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +49 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  6. package/node_modules/@rarog/shared/src/protocol.js +16 -17
  7. package/node_modules/@rarog/shared/src/rest.js +106 -12
  8. package/node_modules/@rarog/shared/src/sentences/rest.js +13 -0
  9. package/package.json +3 -3
  10. package/server/src/bootstrap/consent.js +88 -2
  11. package/server/src/bootstrap/http.js +3 -2
  12. package/server/src/bootstrap/inbox.js +29 -4
  13. package/server/src/bootstrap/sse.js +2 -1
  14. package/server/src/cli/doctor-no-hook.js +162 -0
  15. package/server/src/cli/doctor.js +2 -0
  16. package/server/src/cli/update-channel.js +100 -0
  17. package/server/src/cli/update-registry.js +160 -62
  18. package/server/src/cli/update.js +13 -3
  19. package/server/src/companion/turns-settle.js +4 -1
  20. package/server/src/companion/turns.js +36 -5
  21. package/server/src/config/files.js +32 -0
  22. package/server/src/config/flags.js +10 -1
  23. package/server/src/config-env.js +24 -0
  24. package/server/src/config.js +6 -2
  25. package/server/src/demo/files.js +49 -0
  26. package/server/src/demo/inbox.js +73 -0
  27. package/server/src/demo/review-routes.js +6 -1
  28. package/server/src/device-effects.js +3 -1
  29. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  30. package/server/src/drivers/herdr/consent-no-hook.js +316 -0
  31. package/server/src/drivers/herdr/refusals.js +226 -0
  32. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  33. package/server/src/drivers/herdr-driver.js +116 -287
  34. package/server/src/files/file-index.js +246 -0
  35. package/server/src/files/ignored.js +119 -0
  36. package/server/src/files/listing.js +76 -0
  37. package/server/src/files/path-rule.js +145 -0
  38. package/server/src/files/refusals.js +36 -0
  39. package/server/src/files/send-file.js +115 -0
  40. package/server/src/files/session-download.js +51 -0
  41. package/server/src/files/session-files.js +38 -0
  42. package/server/src/files/session-gate.js +48 -0
  43. package/server/src/git-status.js +3 -2
  44. package/server/src/herdr/audit.js +1 -1
  45. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  46. package/server/src/herdr/dialogs/index.js +6 -1
  47. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +132 -59
  48. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  49. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  50. package/server/src/herdr/dialogs/no-hook.js +63 -0
  51. package/server/src/herdr/dialogs/screen/block.js +10 -0
  52. package/server/src/herdr/dialogs/screen/parse.js +10 -1
  53. package/server/src/herdr/jsonl-pending.js +25 -1
  54. package/server/src/inbox/card.js +18 -9
  55. package/server/src/inbox/dialogs.js +40 -12
  56. package/server/src/inbox/heads.js +55 -0
  57. package/server/src/inbox/inbox.js +24 -2
  58. package/server/src/inbox/index.js +3 -1
  59. package/server/src/index.js +22 -18
  60. package/server/src/install/repair.js +8 -0
  61. package/server/src/log-timestamps.js +9 -4
  62. package/server/src/router.js +7 -1
  63. package/server/src/routes/devices.js +2 -2
  64. package/server/src/routes/inbox.js +91 -0
  65. package/server/src/routes/sessions.js +135 -14
  66. package/server/src/routes/system.js +5 -4
  67. package/server/src/safe-read.js +86 -1
  68. package/server/src/sessions/companion-scope.js +6 -2
  69. package/server/src/sessions/demo-modules.js +16 -0
  70. package/server/src/sessions/diff-measure.js +30 -0
  71. package/server/src/sessions/manager.js +64 -152
  72. package/server/src/sessions/ring-buffer.js +18 -3
  73. package/server/src/sessions/seen-marks.js +9 -6
  74. package/server/src/sessions/session-scope.js +30 -0
  75. package/server/src/sessions/session.js +20 -1
  76. package/server/src/sessions/waiting-line.js +72 -0
  77. package/server/src/sse.js +40 -6
  78. package/server/src/version.js +30 -0
@@ -0,0 +1,246 @@
1
+ import { MAX_FILE_ENTRIES } from '@rarog/shared';
2
+ import { listSessionDir } from './listing.js';
3
+ import { FILES_DISK } from './path-rule.js';
4
+ import { filesSession } from './session-gate.js';
5
+ export const FILE_INDEX_LIMITS = {
6
+ maxFiles: 20_000, maxBodyBytes: 2 * 1024 * 1024, budgetMs: 3_000, maxEntries: MAX_FILE_ENTRIES,
7
+ };
8
+ /**
9
+ * The files git does not ignore under the directory it runs in: tracked ones (`--cached`) and untracked ones that no
10
+ * ignore rule matches (`--others --exclude-standard`), NUL-separated (`-z`), so a name is never quoted. A submodule
11
+ * comes as one path (its gitlink) and an untracked nested repository as its path with a trailing `/`: git lists
12
+ * neither's files.
13
+ */
14
+ export const LS_FILES_COMMAND = {
15
+ sub: 'ls-files', rest: ['-z', '--cached', '--others', '--exclude-standard'],
16
+ };
17
+ const emptyDir = () => ({ listed: new Set(), repos: new Set(), dirs: new Map() });
18
+ /** The tree from one `ls-files` read, or `null` when git did not answer it whole (then the walk keeps every file). */
19
+ export function gitScope(result) {
20
+ if (result.exitCode !== 0 || result.capped === true || result.timedOut === true)
21
+ return null;
22
+ const top = emptyDir();
23
+ for (const record of result.stdout.split('\0')) {
24
+ if (record === '')
25
+ continue;
26
+ const repo = record.endsWith('/');
27
+ const segments = (repo ? record.slice(0, -1) : record).split('/');
28
+ const last = segments.pop() ?? '';
29
+ let dir = top;
30
+ for (const segment of segments) {
31
+ const known = dir.dirs.get(segment);
32
+ const next = known ?? emptyDir();
33
+ if (known === undefined)
34
+ dir.dirs.set(segment, next);
35
+ dir = next;
36
+ }
37
+ (repo ? dir.repos : dir.listed).add(last);
38
+ }
39
+ return top;
40
+ }
41
+ /**
42
+ * The key two spellings of one name share: the Unicode form (git on macOS reports a decomposed name composed,
43
+ * `core.precomposeunicode`) and the letter case (`core.ignorecase` keeps a name renamed only in case under its old
44
+ * spelling).
45
+ */
46
+ const folded = (name) => name.normalize('NFC').toLowerCase();
47
+ /**
48
+ * The git names of one directory mapped to the names of its listing: a git name goes to the entry with exactly its
49
+ * bytes, else to the one entry that no git name matched exactly and has the same folded key; with two or more such
50
+ * entries, to none. An entry no git name maps to stays out, so two names on disk that one key would merge never
51
+ * both enter on one git name.
52
+ */
53
+ function matchNames(gitNames, diskNames) {
54
+ const onDisk = new Set(diskNames);
55
+ const mapped = new Map();
56
+ const add = (disk, name) => {
57
+ const names = mapped.get(disk);
58
+ if (names === undefined)
59
+ mapped.set(disk, [name]);
60
+ else
61
+ names.push(name);
62
+ };
63
+ const loose = [];
64
+ for (const name of gitNames) {
65
+ if (onDisk.has(name))
66
+ add(name, name);
67
+ else
68
+ loose.push(name);
69
+ }
70
+ if (loose.length === 0)
71
+ return mapped;
72
+ const byKey = new Map();
73
+ for (const disk of diskNames) {
74
+ if (mapped.has(disk))
75
+ continue;
76
+ const key = folded(disk);
77
+ byKey.set(key, [...(byKey.get(key) ?? []), disk]);
78
+ }
79
+ for (const name of loose) {
80
+ const candidates = byKey.get(folded(name)) ?? [];
81
+ if (candidates.length === 1)
82
+ add(candidates[0], name);
83
+ }
84
+ return mapped;
85
+ }
86
+ /** Every git name of the directories `git` mapped to the names of a listing ({@link matchNames}). */
87
+ function namesOf(git, diskNames) {
88
+ const gitNames = new Set();
89
+ for (const one of git)
90
+ for (const name of [...one.listed, ...one.repos, ...one.dirs.keys()])
91
+ gitNames.add(name);
92
+ return matchNames(gitNames, diskNames);
93
+ }
94
+ /**
95
+ * How a directory of a narrowed listing goes on, from the git names mapped to it: walked whole when git named it as a
96
+ * path (a submodule's gitlink) or as a nested repository, walked narrowed when git has files under it, else not.
97
+ */
98
+ function nextDir(git, gitNames, rel) {
99
+ const below = [];
100
+ for (const one of git) {
101
+ for (const name of gitNames) {
102
+ if (one.listed.has(name) || one.repos.has(name))
103
+ return { rel, narrowed: false, git: [] };
104
+ const dir = one.dirs.get(name);
105
+ if (dir !== undefined)
106
+ below.push(dir);
107
+ }
108
+ }
109
+ return below.length === 0 ? null : { rel, narrowed: true, git: below };
110
+ }
111
+ /** The index under construction: the paths, the bytes of the body they make, and whether a ceiling cut it. */
112
+ class IndexBody {
113
+ paths = [];
114
+ truncated = false;
115
+ #limits;
116
+ #maxBytes;
117
+ #bytes;
118
+ constructor(limits, maxBytes) {
119
+ this.#limits = limits;
120
+ this.#maxBytes = maxBytes;
121
+ // The body with no path, `"truncated":false` being the longer of the two values.
122
+ this.#bytes = Buffer.byteLength(JSON.stringify({ paths: [], truncated: false, maxBytes }));
123
+ }
124
+ /** Adds `rel`, or marks the body cut and returns `false` when it would pass a ceiling. */
125
+ add(rel) {
126
+ const cost = Buffer.byteLength(JSON.stringify(rel)) + (this.paths.length === 0 ? 0 : 1);
127
+ if (this.paths.length >= this.#limits.maxFiles || this.#bytes + cost > this.#limits.maxBodyBytes) {
128
+ this.truncated = true;
129
+ return false;
130
+ }
131
+ this.paths.push(rel);
132
+ this.#bytes += cost;
133
+ return true;
134
+ }
135
+ value() {
136
+ return { paths: this.paths, truncated: this.truncated, maxBytes: this.#maxBytes };
137
+ }
138
+ }
139
+ /**
140
+ * The walk of the session directory of `area`. A directory whose listing is refused (swapped, gone) is skipped; a
141
+ * refused session directory is the answer. The budget runs from before the git read and is checked between two
142
+ * directories, so the session directory is always listed.
143
+ */
144
+ async function walk(area, maxBytes, run, limits, now, disk) {
145
+ const startedAt = now();
146
+ let scope;
147
+ try {
148
+ scope = gitScope(await run(LS_FILES_COMMAND, area.realCwd));
149
+ }
150
+ catch {
151
+ scope = null;
152
+ }
153
+ const body = new IndexBody(limits, maxBytes);
154
+ const queue = [{ rel: '', narrowed: scope !== null, git: scope === null ? [] : [scope] }];
155
+ for (let next = 0; next < queue.length; next += 1) {
156
+ if (next > 0 && now() - startedAt > limits.budgetMs) {
157
+ body.truncated = true;
158
+ break;
159
+ }
160
+ const dir = queue[next];
161
+ const listing = await listSessionDir(area, dir.rel, { maxBytes, maxEntries: limits.maxEntries }, disk);
162
+ if (!listing.ok) {
163
+ if (dir.rel === '')
164
+ return listing;
165
+ continue;
166
+ }
167
+ if (listing.value.truncated)
168
+ body.truncated = true;
169
+ const names = dir.narrowed ? namesOf(dir.git, listing.value.entries.map((entry) => entry.name)) : null;
170
+ for (const entry of listing.value.entries) {
171
+ const rel = dir.rel === '' ? entry.name : `${dir.rel}/${entry.name}`;
172
+ const gitNames = names?.get(entry.name);
173
+ if (names !== null && gitNames === undefined)
174
+ continue;
175
+ if (entry.kind === 'dir') {
176
+ const pending = gitNames === undefined ? { rel, narrowed: false, git: [] } : nextDir(dir.git, gitNames, rel);
177
+ if (pending !== null)
178
+ queue.push(pending);
179
+ continue;
180
+ }
181
+ if (gitNames !== undefined && !dir.git.some((one) => gitNames.some((name) => one.listed.has(name))))
182
+ continue;
183
+ if (!body.add(rel))
184
+ return { ok: true, value: body.value() };
185
+ }
186
+ }
187
+ return { ok: true, value: body.value() };
188
+ }
189
+ /** The demo index: every file of the demo data its git does not ignore, breadth first as on a server. */
190
+ function demoIndex(maxBytes, entriesOf) {
191
+ const paths = [];
192
+ const queue = [''];
193
+ for (let next = 0; next < queue.length; next += 1) {
194
+ const dir = queue[next];
195
+ for (const entry of entriesOf(dir) ?? []) {
196
+ if (entry.ignored === true)
197
+ continue;
198
+ const rel = dir === '' ? entry.name : `${dir}/${entry.name}`;
199
+ if (entry.kind === 'dir')
200
+ queue.push(rel);
201
+ else
202
+ paths.push(rel);
203
+ }
204
+ }
205
+ return { ok: true, value: { paths, truncated: false, maxBytes } };
206
+ }
207
+ /** The index route's walks: one per session and directory at a time, never kept after it answers. */
208
+ export class SessionFileIndex {
209
+ #limits;
210
+ #now;
211
+ #disk;
212
+ #walks = new Map();
213
+ constructor(opts = {}) {
214
+ this.#limits = { ...FILE_INDEX_LIMITS, ...opts.limits };
215
+ this.#now = opts.now ?? (() => Date.now());
216
+ this.#disk = opts.disk ?? FILES_DISK;
217
+ }
218
+ /**
219
+ * The index of the session `id` with `maxBytes` announced. The gate runs for every request, before any disk call:
220
+ * an unknown session throws the manager's 404 (`port.require`), a Codex entry, a pane out of scope and a session
221
+ * without a pane are refused. A request while a walk of the same session directory runs gets that walk's answer.
222
+ */
223
+ index(id, maxBytes, port) {
224
+ let gate;
225
+ try {
226
+ gate = filesSession(id, port, this.#disk.area);
227
+ }
228
+ catch (error) {
229
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
230
+ }
231
+ if (gate.kind === 'refused')
232
+ return Promise.resolve({ ok: false, refusal: gate.refusal });
233
+ if (gate.kind === 'demo')
234
+ return Promise.resolve(demoIndex(maxBytes, port.demoEntries));
235
+ const key = JSON.stringify([id, gate.area.realCwd, maxBytes]);
236
+ const running = this.#walks.get(key);
237
+ if (running !== undefined)
238
+ return running;
239
+ const started = walk(gate.area, maxBytes, port.run, this.#limits, this.#now, this.#disk).finally(() => {
240
+ if (this.#walks.get(key) === started)
241
+ this.#walks.delete(key);
242
+ });
243
+ this.#walks.set(key, started);
244
+ return started;
245
+ }
246
+ }
@@ -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,76 @@
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 { FILES_DISK, inAreaText, isHiddenName, resolveSessionDir, stillSessionDir, } from './path-rule.js';
5
+ import { NOT_FOUND } from './refusals.js';
6
+ /** The name as a string when its bytes are valid UTF-8, otherwise `null`. */
7
+ function utf8Name(bytes) {
8
+ const name = bytes.toString('utf8');
9
+ return Buffer.from(name, 'utf8').equals(bytes) ? name : null;
10
+ }
11
+ /**
12
+ * The entries of the directory, read through its identity: `[]` for a directory the server may not read (`EACCES`,
13
+ * `EPERM`), as in the directory browser; `null` (404) when the read cannot be bound to the directory the walk found
14
+ * (another platform, another directory under the path now) or fails otherwise. Never a read by path.
15
+ */
16
+ async function entriesOf(dir, disk) {
17
+ try {
18
+ return await disk.readdirByIdentity(dir);
19
+ }
20
+ catch (error) {
21
+ const code = error?.code;
22
+ return code === 'EACCES' || code === 'EPERM' ? [] : null;
23
+ }
24
+ }
25
+ /**
26
+ * An entry of the listing, or `null` for one the server leaves out. Its `lstat` under the directory's path must show
27
+ * the kind the read gave: an entry swapped for a symlink since the read drops. The device is not compared, because a
28
+ * mount point under the session directory is a directory the path rule allows, on a device of its own.
29
+ */
30
+ async function entryOf(area, dir, name, kind, disk) {
31
+ if (isHiddenName(name))
32
+ return null;
33
+ if (!inAreaText(area, path.join(dir.path, name)))
34
+ return null;
35
+ if (!insideWorkArea(path.join(dir.real, name), area.realRoots, area.realHome))
36
+ return null;
37
+ try {
38
+ const info = await disk.lstat(path.join(dir.real, name));
39
+ if (kind === 'dir')
40
+ return info.isDirectory() ? { name, kind } : null;
41
+ return info.isFile() && info.nlink === 1n ? { name, kind, size: Number(info.size) } : null;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /**
48
+ * Lists the directory `rel` of the session (`''` = the session directory). A directory the server may not read gives
49
+ * an empty listing, as in the directory browser; a directory swapped while it was read gives 404.
50
+ */
51
+ export async function listSessionDir(area, rel, opts, disk = FILES_DISK) {
52
+ const dir = await resolveSessionDir(area, rel, disk);
53
+ if (!dir.ok)
54
+ return dir;
55
+ const read = await entriesOf(dir.value, disk);
56
+ if (read === null)
57
+ return { ok: false, refusal: NOT_FOUND };
58
+ const pending = [];
59
+ for (const entry of read) {
60
+ const name = utf8Name(entry.name);
61
+ if (name === null)
62
+ continue;
63
+ if (entry.isDirectory())
64
+ pending.push(entryOf(area, dir.value, name, 'dir', disk));
65
+ else if (entry.isFile())
66
+ pending.push(entryOf(area, dir.value, name, 'file', disk));
67
+ }
68
+ const entries = (await Promise.all(pending)).filter((entry) => entry !== null).sort(compareFileEntries);
69
+ if (!(await stillSessionDir(dir.value, disk)))
70
+ return { ok: false, refusal: NOT_FOUND };
71
+ const max = opts.maxEntries ?? MAX_FILE_ENTRIES;
72
+ return {
73
+ ok: true,
74
+ value: { dir: rel, entries: entries.slice(0, max), truncated: entries.length > max, maxBytes: opts.maxBytes },
75
+ };
76
+ }
@@ -0,0 +1,145 @@
1
+ import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
+ import { lstat, readdir, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { insideWorkArea, resolveInWorkArea } from '../config/work-area.js';
5
+ import { validateDiffPath } from '../git-diff.js';
6
+ import { openRegularFile, readDirectoryByIdentity } from '../safe-read.js';
7
+ import { BAD_PATH, NOT_FOUND } from './refusals.js';
8
+ export const FILES_DISK = {
9
+ readdir: (dir) => readdir(dir, { withFileTypes: true, encoding: 'buffer' }),
10
+ readdirByIdentity: (dir) => readDirectoryByIdentity(dir.real, dir),
11
+ lstat: (file) => lstat(file, { bigint: true }),
12
+ stat: (file) => stat(file, { bigint: true }),
13
+ realpath: (file) => realpath(file),
14
+ open: (file) => openRegularFile(file, { followSymlink: false }),
15
+ area: {
16
+ lstat: (file) => lstatSync(file), readlink: (file) => readlinkSync(file), realpath: (file) => realpathSync(file),
17
+ },
18
+ };
19
+ const refused = (refusal) => ({ ok: false, refusal });
20
+ /** Step 1: the segments of the path, or `null` for 400. `''` is the session directory where `allowEmpty`. */
21
+ function segmentsOf(rel, allowEmpty) {
22
+ if (rel === '')
23
+ return allowEmpty ? [] : null;
24
+ if (validateDiffPath(rel) === null)
25
+ return null;
26
+ const segments = rel.split('/');
27
+ return segments.includes('') ? null : segments;
28
+ }
29
+ /**
30
+ * Step 1 alone, for the demo, which has no disk: the refusal of a path that fails the shape check, or `null`. `''`
31
+ * is the session directory where `allowEmpty`.
32
+ */
33
+ export function shapeRefusal(rel, allowEmpty) {
34
+ return segmentsOf(rel, allowEmpty) === null ? BAD_PATH : null;
35
+ }
36
+ /** The text of a name the server never shows: it starts with a dot, or it is `node_modules` in any letter case. */
37
+ export function isHiddenName(name) {
38
+ return name.startsWith('.') || name.toLowerCase() === 'node_modules';
39
+ }
40
+ /**
41
+ * Whether `file` lies in the work area, as text, against the roots in both forms and the configured home, as the
42
+ * session gate asks about the session directory (`inWorkAreaOnDisk`). No disk call.
43
+ */
44
+ export function inAreaText(area, file) {
45
+ return insideWorkArea(file, [...area.roots, ...area.realRoots], area.home);
46
+ }
47
+ /** Steps 1 and 2: the segments of a path that may go to the disk, or the refusal. */
48
+ function checkText(area, rel, allowEmpty) {
49
+ const segments = segmentsOf(rel, allowEmpty);
50
+ if (segments === null)
51
+ return refused(BAD_PATH);
52
+ if (segments.some(isHiddenName))
53
+ return refused(NOT_FOUND);
54
+ if (!inAreaText(area, path.join(area.cwd, ...segments)))
55
+ return refused(NOT_FOUND);
56
+ // The on-disk form against the on-disk home, so a home reached through a symlink keeps its protected folders.
57
+ if (!insideWorkArea(path.join(area.realCwd, ...segments), area.realRoots, area.realHome))
58
+ return refused(NOT_FOUND);
59
+ return { ok: true, value: segments };
60
+ }
61
+ async function attempt(call) {
62
+ try {
63
+ return await call();
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** Step 3: the walk down from `cwd` and the path on disk, or `null` for 404. */
70
+ async function walk(area, segments, last, disk) {
71
+ let current = area.cwd;
72
+ for (const [index, segment] of segments.entries()) {
73
+ const entries = await attempt(() => disk.readdir(current));
74
+ const wanted = Buffer.from(segment, 'utf8');
75
+ if (entries?.some((entry) => entry.name.equals(wanted)) !== true)
76
+ return null;
77
+ const next = path.join(current, segment);
78
+ const info = await attempt(() => disk.lstat(next));
79
+ if (info === null || info.isSymbolicLink())
80
+ return null;
81
+ const isLast = index === segments.length - 1;
82
+ if (isLast && last === 'file' ? !info.isFile() : !info.isDirectory())
83
+ return null;
84
+ current = next;
85
+ }
86
+ if (resolveInWorkArea(current, area.realRoots, area.realHome, disk.area).kind !== 'resolved')
87
+ return null;
88
+ const real = await attempt(() => disk.realpath(current));
89
+ if (real !== path.join(area.realCwd, ...segments))
90
+ return null;
91
+ if (!insideWorkArea(real, area.realRoots, area.realHome))
92
+ return null;
93
+ return { path: current, real };
94
+ }
95
+ /** Steps 1 to 3 for a directory: the listing's directory (`''` = the session directory) or the refusal. */
96
+ export async function resolveSessionDir(area, rel, disk = FILES_DISK) {
97
+ const text = checkText(area, rel, true);
98
+ if (!text.ok)
99
+ return text;
100
+ const segments = text.value;
101
+ const walked = await walk(area, segments, 'dir', disk);
102
+ if (walked === null)
103
+ return refused(NOT_FOUND);
104
+ const info = await attempt(() => disk.stat(walked.real));
105
+ if (info === null || !info.isDirectory())
106
+ return refused(NOT_FOUND);
107
+ return { ok: true, value: { rel, segments, path: walked.path, real: walked.real, dev: info.dev, ino: info.ino } };
108
+ }
109
+ /**
110
+ * Whether `dir` is still the directory the walk found: `realpath` of its path gives the same directory on disk with
111
+ * the same `dev` and `ino`. The listing asks after its read of the entries, as the open does after the open.
112
+ */
113
+ export async function stillSessionDir(dir, disk = FILES_DISK) {
114
+ const real = await attempt(() => disk.realpath(dir.path));
115
+ if (real !== dir.real)
116
+ return false;
117
+ const info = await attempt(() => disk.stat(real));
118
+ return info !== null && info.isDirectory() && info.dev === dir.dev && info.ino === dir.ino;
119
+ }
120
+ /** Steps 1 to 5 for a file: the open file, or the refusal with no descriptor left open. */
121
+ export async function openSessionFile(area, rel, disk = FILES_DISK) {
122
+ const text = checkText(area, rel, false);
123
+ if (!text.ok)
124
+ return text;
125
+ const walked = await walk(area, text.value, 'file', disk);
126
+ if (walked === null)
127
+ return refused(NOT_FOUND);
128
+ const opened = await attempt(() => disk.open(walked.real));
129
+ if (opened === null)
130
+ return refused(NOT_FOUND);
131
+ const { handle, stats } = opened;
132
+ if (stats.nlink > 1n || !(await sameFileAgain(walked, stats, disk))) {
133
+ await handle.close();
134
+ return refused(NOT_FOUND);
135
+ }
136
+ return { ok: true, value: { handle, size: Number(stats.size), stats } };
137
+ }
138
+ /** Step 5: the path resolves to the same place, and that place is the file the descriptor holds. */
139
+ async function sameFileAgain(walked, opened, disk) {
140
+ const real = await attempt(() => disk.realpath(walked.path));
141
+ if (real !== walked.real)
142
+ return false;
143
+ const info = await attempt(() => disk.stat(real));
144
+ return info !== null && info.dev === opened.dev && info.ino === opened.ino;
145
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The refusals of the session file routes: status, contract code and sentence, ready for `sendError` of the router.
3
+ * One table for the gate, the path rule and the listing, so both routes refuse a path the same way. The module only
4
+ * builds values; it reads nothing.
5
+ */
6
+ import { FILES_BAD_PATH_ERROR, FILES_CODEX_ERROR, FILES_NOT_FOUND_ERROR, FILES_OUT_OF_SCOPE_ERROR, FILE_TOO_LARGE_ERROR, } from '@rarog/shared';
7
+ import { say } from '@rarog/shared/sentences';
8
+ /** The path failed the shape check; the same sentence as a bad path of the diff routes. */
9
+ export const BAD_PATH = { status: 400, code: FILES_BAD_PATH_ERROR, sentence: say('rest.diff-bad-path') };
10
+ /** Nothing to list or send under the path, or the server never shows it: one answer, so it tells nothing apart. */
11
+ export const NOT_FOUND = {
12
+ status: 404, code: FILES_NOT_FOUND_ERROR, sentence: say('rest.files-not-found'),
13
+ };
14
+ /** A Codex entry: Rarog only observes it. */
15
+ export const CODEX = { status: 400, code: FILES_CODEX_ERROR, sentence: say('rest.files-codex') };
16
+ /** A pane outside the work area, or a session directory outside it on disk. */
17
+ export const OUT_OF_SCOPE = {
18
+ status: 400, code: FILES_OUT_OF_SCOPE_ERROR, sentence: say('rest.files-out-of-scope'),
19
+ };
20
+ /** A session without a herdr pane: out of scope too, with its own sentence. */
21
+ export const NO_PANE = {
22
+ status: 400, code: FILES_OUT_OF_SCOPE_ERROR, sentence: say('rest.files-no-pane'),
23
+ };
24
+ const MIB = 1024 * 1024;
25
+ /**
26
+ * The refusal of a file of `size` bytes over `maxBytes`. The sentence gives whole megabytes, the size rounded up, so
27
+ * a file one byte over the limit never reads as equal to it.
28
+ */
29
+ export function fileTooLarge(size, maxBytes) {
30
+ return {
31
+ status: 413,
32
+ code: FILE_TOO_LARGE_ERROR,
33
+ sentence: say('rest.file-too-large', { size: Math.ceil(size / MIB), limit: Math.floor(maxBytes / MIB) }),
34
+ extra: { size, maxBytes },
35
+ };
36
+ }