@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
@@ -34,18 +34,24 @@
34
34
  * - **The start sweep reads a registry, not the disk tree.** Every successful write records the real path of its
35
35
  * `<cwd>` in `<dataDir>/uploads-dirs.json` (`uploads-registry.ts`), and `sweepAll` cleans only those directories,
36
36
  * each only while `realpath` still gives the entry itself. It walks the roots once, when the registry is missing
37
- * or unreadable, and writes the registry from what it found.
37
+ * or unreadable, and writes the registry from what it found once every part of the walk ran.
38
+ * - **A guarded folder of home waits for the folder gate.** A write in a folder the gate holds closed is refused with
39
+ * the sentence of the folder's state. A write the folder's helper did not answer in time may still land, so its
40
+ * `<cwd>` goes to the registry anyway and the next sweep removes the file. The start sweep does not enter a guarded
41
+ * folder until the gate holds it `open`: that part waits for the change and runs then, only while its directory
42
+ * still resolves to itself. Until it ran, the walk writes no registry, so a restart before then walks again.
38
43
  */
39
44
  import { randomBytes } from 'node:crypto';
40
- import { chmod, lstat, mkdir, readdir, realpath, unlink, writeFile } from 'node:fs/promises';
41
45
  import { homedir } from 'node:os';
42
- import { basename, isAbsolute, join } from 'node:path';
46
+ import { basename, isAbsolute, join, relative } from 'node:path';
43
47
  import { FILE_DATA_URL_PATTERN, IMAGE_DATA_URL_PATTERN, UPLOAD_IMAGE_FILE_PATTERN, } from '@rarog/shared';
44
48
  import { foreign, say, textOf } from '@rarog/shared/sentences';
45
49
  import { HERDR_UPLOAD_TTL_MS } from '../config.js';
46
50
  import { inWorkAreaOnDisk } from '../config/work-area.js';
47
51
  import { isProtectedPath } from '../config/protected-dirs.js';
48
- import { appendRegularFile, readRegularFile } from '../safe-read.js';
52
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
53
+ import { folderGate } from '../folder-gate/install.js';
54
+ import { FolderGateError } from '../folder-gate/types.js';
49
55
  /** Katalog załączników (zdjęć i plików) wewnątrz workspace'u panelu: zapis, odczyt miniatur i sprzątanie. */
50
56
  export const UPLOAD_DIR_NAME = '.rarog-uploads';
51
57
  /** Po tylu godzinach plik jest śmieciem, nie załącznikiem (definicja: `config.ts`). */
@@ -279,10 +285,10 @@ function notDirectory(info, dir) {
279
285
  * tym sprawdzeniem a `chmod` wymagałby ŻYWEGO procesu atakującego na Macu, a wektor, przed którym
280
286
  * ta bramka stoi (sklonowane repozytorium z dowiązaniem w drzewie), takiego procesu nie daje.
281
287
  */
282
- async function assertPlainUploadDir(dir) {
288
+ async function assertPlainUploadDir(disk, dir) {
283
289
  let info;
284
290
  try {
285
- info = await lstat(dir);
291
+ info = await disk.call('lstat', { path: dir });
286
292
  }
287
293
  catch {
288
294
  return; // wpisu nie ma (albo nie da się go obejrzeć) — resztę powie `mkdir`
@@ -307,25 +313,25 @@ async function assertPlainUploadDir(dir) {
307
313
  * {@link EXCLUDE_MAX_BYTES} bez linii — dopisanie; cokolwiek innego (dowiązanie, FIFO, urządzenie, plik
308
314
  * ponad sufit) — BEZ zapisu. Zapis po nieudanym odczycie byłby `appendFile`, które na FIFO bez
309
315
  * czytelnika blokuje wątek puli libuv. Dopisanie sprawdza typ jeszcze raz na własnym deskryptorze
310
- * (`appendRegularFile`).
316
+ * (`appendRegular` portu dysku).
311
317
  */
312
- async function ensureGitExclude(cwd) {
318
+ async function ensureGitExclude(disk, cwd) {
313
319
  const gitDir = join(cwd, '.git');
314
320
  try {
315
- const info = await lstat(gitDir);
321
+ const info = await disk.call('lstat', { path: gitDir });
316
322
  if (!info.isDirectory())
317
323
  return;
318
324
  const infoDir = join(gitDir, 'info');
319
- await mkdir(infoDir).catch((err) => {
325
+ await disk.call('mkdir', { path: infoDir }).catch((err) => {
320
326
  if (err.code !== 'EEXIST')
321
327
  throw err;
322
328
  });
323
- if (!(await lstat(infoDir)).isDirectory())
329
+ if (!(await disk.call('lstat', { path: infoDir })).isDirectory())
324
330
  return;
325
331
  const file = join(infoDir, 'exclude');
326
332
  let current = '';
327
333
  try {
328
- const read = await readRegularFile(file, { maxBytes: EXCLUDE_MAX_BYTES, followSymlink: false });
334
+ const read = await disk.call('readHead', { path: file, maxBytes: EXCLUDE_MAX_BYTES, followSymlink: false });
329
335
  if (read === null || read.truncated)
330
336
  return;
331
337
  current = read.bytes.toString('utf8');
@@ -338,7 +344,7 @@ async function ensureGitExclude(cwd) {
338
344
  if (present.has(EXCLUDE_LINE))
339
345
  return;
340
346
  const prefix = current === '' || current.endsWith('\n') ? '' : '\n';
341
- await appendRegularFile(file, `${prefix}${EXCLUDE_LINE}\n`);
347
+ await disk.call('appendRegular', { path: file, text: `${prefix}${EXCLUDE_LINE}\n` });
342
348
  }
343
349
  catch {
344
350
  // celowo cicho — patrz komentarz nad funkcją
@@ -350,29 +356,35 @@ class Uploads {
350
356
  #maxDepth;
351
357
  #home;
352
358
  #registry;
359
+ #disk;
360
+ /** Start sweeps that wait for a guarded folder to open, by folder. */
361
+ #waiting = new Map();
362
+ #offGate = null;
353
363
  constructor(opts = {}) {
354
364
  this.#now = opts.now ?? Date.now;
355
365
  this.#ttlMs = opts.ttlMs ?? HERDR_UPLOAD_TTL_MS;
356
366
  this.#maxDepth = opts.maxDepth ?? SWEEP_MAX_DEPTH;
357
367
  this.#home = opts.home ?? homedir();
358
368
  this.#registry = opts.registry;
369
+ this.#disk = opts.disk ?? DIRECT_DISK;
359
370
  }
360
371
  async write(cwd, images) {
361
372
  if (images.length === 0)
362
373
  return [];
363
374
  const dir = await this.#prepareDir(cwd);
364
375
  const paths = [];
376
+ const late = [];
365
377
  try {
366
378
  for (const image of images) {
367
379
  const parsed = parseImageDataUrl(image);
368
380
  if (parsed === null) {
369
381
  throw new UploadError(say('uploads.not-image'));
370
382
  }
371
- paths.push(await this.#writeOne(dir, uploadName(this.#now(), parsed.ext), parsed.bytes));
383
+ paths.push(await this.#writeOne(dir, uploadName(this.#now(), parsed.ext), parsed.bytes, late));
372
384
  }
373
385
  }
374
386
  finally {
375
- await this.#remember(cwd, paths);
387
+ await this.#remember(cwd, [...paths, ...late]);
376
388
  }
377
389
  return paths;
378
390
  }
@@ -381,6 +393,7 @@ class Uploads {
381
393
  return [];
382
394
  const dir = await this.#prepareDir(cwd);
383
395
  const paths = [];
396
+ const late = [];
384
397
  try {
385
398
  for (const file of files) {
386
399
  const bytes = parseFileDataUrl(file.dataUrl);
@@ -388,16 +401,17 @@ class Uploads {
388
401
  const shown = sanitizeUploadName(file.name);
389
402
  throw new UploadError(say('uploads.bad-content', { name: shown }));
390
403
  }
391
- paths.push(await this.#writeOne(dir, uploadFileName(this.#now(), file.name), bytes));
404
+ paths.push(await this.#writeOne(dir, uploadFileName(this.#now(), file.name), bytes, late));
392
405
  }
393
406
  }
394
407
  finally {
395
- await this.#remember(cwd, paths);
408
+ await this.#remember(cwd, [...paths, ...late]);
396
409
  }
397
410
  return paths;
398
411
  }
399
412
  /**
400
- * Records `cwd` in the registry once a file is on disk, also when a later file of the same message failed: the
413
+ * Records `cwd` in the registry once a file is on disk or may land there late (a write the folder gate refused
414
+ * after its helper did not answer in time), also when a later file of the same message failed: the
401
415
  * start sweep must find every file Rarog left. AFTER the write, never before: a start sweep that saw the directory
402
416
  * empty drops it unless it was recorded after the sweep's mark, so a record made before the bytes land could be
403
417
  * dropped together with the file it should cover. The entry is the real path of `cwd` (no symlink in it): the
@@ -407,7 +421,7 @@ class Uploads {
407
421
  async #remember(cwd, written) {
408
422
  if (written.length === 0 || this.#registry === undefined)
409
423
  return;
410
- const real = await realpath(cwd).catch(() => null);
424
+ const real = await this.#disk.call('realpathNative', { path: cwd }).catch(() => null);
411
425
  if (real !== null)
412
426
  await this.#registry.add(real);
413
427
  }
@@ -420,29 +434,39 @@ class Uploads {
420
434
  async #prepareDir(cwd) {
421
435
  const dir = join(cwd, UPLOAD_DIR_NAME);
422
436
  // PRZED `mkdir`, bo `mkdir` na dowiązaniu nie rzuca, a `chmod` niżej idzie za dowiązaniem.
423
- await assertPlainUploadDir(dir);
437
+ await assertPlainUploadDir(this.#disk, dir);
424
438
  try {
425
- await mkdir(dir, { recursive: true, mode: UPLOAD_DIR_MODE });
439
+ await this.#disk.call('mkdir', { path: dir, recursive: true, mode: UPLOAD_DIR_MODE });
426
440
  // `mkdir` przycina tryb umaskiem, a katalog z załącznikami ma być 0700 NIEZALEŻNIE od
427
441
  // ustawień powłoki, z której wystartował Rarog.
428
- await chmod(dir, UPLOAD_DIR_MODE);
442
+ await this.#disk.call('chmod', { path: dir, mode: UPLOAD_DIR_MODE });
429
443
  }
430
444
  catch (err) {
445
+ if (err instanceof FolderGateError)
446
+ throw new UploadError(err.sentence, { cause: err });
431
447
  throw new UploadError(say('uploads.mkdir-failed', { dir, reason: foreign(describe(err)) }));
432
448
  }
433
449
  // Sprzątamy PRZED zapisem, żeby katalog nie puchł przy użytkowniku, który nigdy nie restartuje
434
450
  // Raroga. Błąd sprzątania nie ma prawa zablokować wysyłki.
435
451
  await this.sweep(cwd);
436
- await ensureGitExclude(cwd);
452
+ await ensureGitExclude(this.#disk, cwd);
437
453
  return dir;
438
454
  }
439
- async #writeOne(dir, name, bytes) {
455
+ /**
456
+ * One file. A write the folder gate refused is reported with the sentence of the folder's state, and its path goes
457
+ * to `late`: when the folder's helper did not answer in time, the bytes may land after the refusal.
458
+ */
459
+ async #writeOne(dir, name, bytes, late) {
440
460
  const path = join(dir, name);
441
461
  try {
442
462
  // `wx` — nigdy nie nadpisujemy cudzego pliku, nawet gdyby nazwa się powtórzyła.
443
- await writeFile(path, bytes, { mode: UPLOAD_FILE_MODE, flag: 'wx' });
463
+ await this.#disk.call('writeFile', { path, data: bytes, mode: UPLOAD_FILE_MODE, flag: 'wx' });
444
464
  }
445
465
  catch (err) {
466
+ if (err instanceof FolderGateError) {
467
+ late.push(path);
468
+ throw new UploadError(err.sentence, { cause: err });
469
+ }
446
470
  throw new UploadError(say('uploads.write-failed', { path, reason: foreign(describe(err)) }));
447
471
  }
448
472
  return path;
@@ -460,7 +484,7 @@ class Uploads {
460
484
  // (`lstat` widzi dowiązanie; `stat` widziałby cel). Wyścig między tym sprawdzeniem
461
485
  // a otwarciem pliku przyjęty świadomie, tak samo jak przy `write` — patrz
462
486
  // `assertPlainUploadDir`: wymaga żywego procesu atakującego na Macu.
463
- if (!(await lstat(dir)).isDirectory())
487
+ if (!(await this.#disk.call('lstat', { path: dir })).isDirectory())
464
488
  return null;
465
489
  /*
466
490
  * Sam plik czytamy przez JEDEN deskryptor: `O_NOFOLLOW` odmawia
@@ -469,7 +493,7 @@ class Uploads {
469
493
  * Przez `safe-read.ts`: `O_NONBLOCK` (FIFO pod nazwą zdjęcia nie zajmuje wątku puli libuv)
470
494
  * i sufit {@link UPLOAD_READ_MAX_BYTES} (większy plik to nie zdjęcie Raroga).
471
495
  */
472
- const read = await readRegularFile(path, { maxBytes: UPLOAD_READ_MAX_BYTES, followSymlink: false });
496
+ const read = await this.#disk.call('readHead', { path, maxBytes: UPLOAD_READ_MAX_BYTES, followSymlink: false });
473
497
  return read === null || read.truncated ? null : { bytes: read.bytes, mime };
474
498
  }
475
499
  catch {
@@ -482,7 +506,7 @@ class Uploads {
482
506
  async sweepAll(roots) {
483
507
  const registry = this.#registry;
484
508
  if (registry === undefined) {
485
- await this.#walkRoots(roots);
509
+ await this.#walkRoots(roots, null);
486
510
  return;
487
511
  }
488
512
  const state = await registry.load();
@@ -490,7 +514,47 @@ class Uploads {
490
514
  await this.#sweepRegistered(registry, state.dirs);
491
515
  return;
492
516
  }
493
- await registry.rebuild(await this.#walkRoots(roots));
517
+ // Written only when the whole walk ran, its deferred parts too: a registry written before would leave a subtree
518
+ // nobody swept out of every later start sweep.
519
+ await this.#walkRoots(roots, (found) => registry.rebuild(found));
520
+ }
521
+ /**
522
+ * The guarded folder of home `dir` lies in while the folder gate does not hold it `open` (`unknown` too), or `null`:
523
+ * the start sweep does not enter such a folder yet. Text only, against home as given and on disk.
524
+ */
525
+ #waitingFolderOf(dir, realHome) {
526
+ const gate = folderGate();
527
+ if (!gate.enabled)
528
+ return null;
529
+ const rel = relative(realHome, dir);
530
+ const asGiven = rel !== '' && !rel.startsWith('..') && !isAbsolute(rel) ? join(this.#home, rel) : dir;
531
+ const at = gate.stateOf(dir) ?? gate.stateOf(asGiven);
532
+ return at === null || at.state === 'open' ? null : at.folder;
533
+ }
534
+ /**
535
+ * Runs `job` once the folder gate holds `folder` open. One listener on the gate serves every folder that waits;
536
+ * a job never throws into the gate.
537
+ */
538
+ #afterOpen(folder, job) {
539
+ const jobs = this.#waiting.get(folder) ?? [];
540
+ jobs.push(job);
541
+ this.#waiting.set(folder, jobs);
542
+ if (this.#offGate !== null)
543
+ return;
544
+ this.#offGate = folderGate().onChange((changed, state) => {
545
+ const ready = state === 'open' ? this.#waiting.get(changed) : undefined;
546
+ if (ready === undefined)
547
+ return;
548
+ this.#waiting.delete(changed);
549
+ if (this.#waiting.size === 0) {
550
+ this.#offGate?.();
551
+ this.#offGate = null;
552
+ }
553
+ void (async () => {
554
+ for (const run of ready)
555
+ await run().catch(() => undefined);
556
+ })();
557
+ });
494
558
  }
495
559
  /**
496
560
  * Sweeps the registered directories whatever the current roots are: the server wrote there itself. A missing
@@ -500,7 +564,19 @@ class Uploads {
500
564
  async #sweepRegistered(registry, dirs) {
501
565
  const mark = registry.mark();
502
566
  const leaving = [];
567
+ const home = await this.#disk.call('realpathNative', { path: this.#home }).catch(() => this.#home);
503
568
  for (const cwd of dirs) {
569
+ const folder = this.#waitingFolderOf(cwd, home);
570
+ if (folder !== null) {
571
+ // The entry stays registered until its sweep runs.
572
+ this.#afterOpen(folder, async () => {
573
+ const later = registry.mark();
574
+ const outcome = await this.#sweepEntry(cwd);
575
+ if (outcome === 'gone' || outcome === 'empty')
576
+ await registry.drop([cwd], later);
577
+ });
578
+ continue;
579
+ }
504
580
  const outcome = await this.#sweepEntry(cwd);
505
581
  if (outcome === 'gone' || outcome === 'empty')
506
582
  leaving.push(cwd);
@@ -518,7 +594,7 @@ class Uploads {
518
594
  async #sweepEntry(cwd) {
519
595
  let real;
520
596
  try {
521
- real = await realpath(cwd);
597
+ real = await this.#disk.call('realpathNative', { path: cwd });
522
598
  }
523
599
  catch (err) {
524
600
  const code = err.code;
@@ -532,29 +608,62 @@ class Uploads {
532
608
  return this.#sweepDir(join(cwd, UPLOAD_DIR_NAME));
533
609
  }
534
610
  /**
535
- * Walk of the roots; returns the directories whose `.rarog-uploads` still holds files after the sweep, or could
536
- * not be read (`unknown`), so the next start tries those again. The walk enters no symlinked directory, so every
537
- * path it returns is already a real path.
611
+ * Whether a deferred part of the walk may sweep `dir`, a real path when the walk reached it: only while its real path
612
+ * is still `dir` itself. The `lstat` in `#sweepDir` sees only the last name, so a `dir` or a parent replaced by a
613
+ * symlink while the folder was closed would lead the sweep into another tree, where it deletes old files. Otherwise
614
+ * one log line and nothing under `dir` is touched; a `realpath` error other than a missing path keeps `dir` among
615
+ * what the walk found, so the next start tries it again.
538
616
  */
539
- async #walkRoots(roots) {
617
+ async #stillItself(dir, walk) {
618
+ let real;
619
+ try {
620
+ real = await this.#disk.call('realpathNative', { path: dir });
621
+ }
622
+ catch (err) {
623
+ const code = err.code ?? 'error';
624
+ console.warn(`rarog: skipping the deferred cleanup of ${dir} — its real path cannot be read (${code}).`);
625
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
626
+ walk.found.push(dir);
627
+ return false;
628
+ }
629
+ if (real === dir)
630
+ return true;
631
+ console.warn(`rarog: skipping the deferred cleanup of ${dir} — the path now leads through a symlink; `
632
+ + 'nothing under it is cleaned.');
633
+ return false;
634
+ }
635
+ /**
636
+ * Walk of the roots. Once every part of it ran, the first pass and each subtree deferred until its guarded folder
637
+ * opens, `complete` gets the directories whose `.rarog-uploads` still holds files after the sweep, or could not be
638
+ * read (`unknown`), so the next start tries those again. A folder that does not open in this process, or a part
639
+ * that throws, leaves the walk incomplete and `complete` uncalled. The walk enters no symlinked directory, so every
640
+ * path it gives is already a real path.
641
+ */
642
+ async #walkRoots(roots, complete) {
540
643
  // Home and roots in their on-disk form before the walk: the protected-folder check compares paths as text, so
541
644
  // a root that names home in another case (`/users/demo`) or through a symlink would otherwise reach `Desktop`.
542
645
  // `fs/promises` `realpath` has the native semantics and returns the stored case on APFS. Only the roots and home
543
646
  // are resolved, not every visited folder; a root that does not resolve is skipped, as a missing one always was.
544
- const home = await realpath(this.#home).catch(() => this.#home);
647
+ const home = await this.#disk.call('realpathNative', { path: this.#home }).catch(() => this.#home);
545
648
  const resolved = [];
546
649
  for (const root of roots) {
547
650
  if (!isAbsolute(root))
548
651
  continue;
549
- const real = await realpath(root).catch(() => null);
652
+ const real = await this.#disk.call('realpathNative', { path: root }).catch(() => null);
550
653
  if (real !== null)
551
654
  resolved.push(real);
552
655
  }
553
- const walk = { seen: new Set(), roots: resolved, home, found: [] };
656
+ const walk = { seen: new Set(), roots: resolved, home, found: [], parts: { left: 1, complete } };
554
657
  for (const root of resolved) {
555
658
  await this.#sweepTree(root, this.#maxDepth, walk);
556
659
  }
557
- return walk.found;
660
+ await this.#partRan(walk);
661
+ }
662
+ /** One part of the walk ran; after the last one, `complete` gets what the whole walk found. */
663
+ async #partRan(walk) {
664
+ walk.parts.left -= 1;
665
+ if (walk.parts.left === 0)
666
+ await walk.parts.complete?.(walk.found);
558
667
  }
559
668
  async #sweepTree(dir, depth, walk) {
560
669
  if (walk.seen.has(dir))
@@ -564,6 +673,18 @@ class Uploads {
564
673
  // and the walk would wait for an answer nobody gives. A root placed inside such a folder keeps its subtree.
565
674
  if (isProtectedPath(dir, walk.roots, walk.home))
566
675
  return;
676
+ const folder = this.#waitingFolderOf(dir, walk.home);
677
+ if (folder !== null) {
678
+ // A root inside a guarded folder the gate does not hold open yet: this subtree is a part of the walk that runs
679
+ // once the folder opens, and only while `dir` is still itself.
680
+ walk.parts.left += 1;
681
+ this.#afterOpen(folder, async () => {
682
+ if (await this.#stillItself(dir, walk))
683
+ await this.#sweepTree(dir, depth, { ...walk, seen: new Set() });
684
+ await this.#partRan(walk);
685
+ });
686
+ return;
687
+ }
567
688
  const outcome = await this.#sweepDir(join(dir, UPLOAD_DIR_NAME));
568
689
  if (outcome === 'kept' || outcome === 'unknown')
569
690
  walk.found.push(dir);
@@ -571,7 +692,7 @@ class Uploads {
571
692
  return;
572
693
  let entries;
573
694
  try {
574
- entries = await readdir(dir, { withFileTypes: true });
695
+ entries = await this.#disk.call('readdir', { path: dir, encoding: 'utf8' });
575
696
  }
576
697
  catch {
577
698
  return;
@@ -579,10 +700,11 @@ class Uploads {
579
700
  for (const entry of entries) {
580
701
  if (!entry.isDirectory())
581
702
  continue;
703
+ const name = String(entry.name);
582
704
  // Katalogi ukryte i `node_modules` odpadają: projektów tam nie ma, a skan kosztuje.
583
- if (entry.name.startsWith('.') || entry.name === 'node_modules')
705
+ if (name.startsWith('.') || name === 'node_modules')
584
706
  continue;
585
- await this.#sweepTree(join(dir, entry.name), depth - 1, walk);
707
+ await this.#sweepTree(join(dir, name), depth - 1, walk);
586
708
  }
587
709
  }
588
710
  async #sweepDir(dir) {
@@ -592,7 +714,7 @@ class Uploads {
592
714
  // (sweep startowy leci przy każdym starcie serwera). `readdir` listuje CEL dowiązania,
593
715
  // a `unlink` przez nie przechodzi — dowiązane `.rarog-uploads` oznaczałoby ciche kasowanie
594
716
  // wszystkiego starszego niż 48 h w cudzym katalogu.
595
- info = await lstat(dir);
717
+ info = await this.#disk.call('lstat', { path: dir });
596
718
  }
597
719
  catch (err) {
598
720
  const code = err.code;
@@ -608,9 +730,9 @@ class Uploads {
608
730
  let names;
609
731
  try {
610
732
  // `Dirent` z `readdir` nie podąża za dowiązaniem, więc `isFile()` odsiewa dowiązane wpisy.
611
- names = (await readdir(dir, { withFileTypes: true }))
733
+ names = (await this.#disk.call('readdir', { path: dir, encoding: 'utf8' }))
612
734
  .filter((e) => e.isFile())
613
- .map((e) => e.name);
735
+ .map((e) => String(e.name));
614
736
  }
615
737
  catch {
616
738
  return 'unknown';
@@ -621,10 +743,11 @@ class Uploads {
621
743
  const path = join(dir, name);
622
744
  try {
623
745
  // `lstat` także tutaj — wiek liczymy z tego wpisu, który za chwilę kasujemy, a nie z celu.
624
- const entry = await lstat(path);
625
- if (entry.mtimeMs >= cutoff)
746
+ const entry = await this.#disk.call('lstat', { path });
747
+ // Milliseconds with their fraction, as the number form of `lstat` gave them; bigint `mtimeMs` drops it.
748
+ if (Number(entry.mtimeNs) / 1e6 >= cutoff)
626
749
  continue;
627
- await unlink(path);
750
+ await this.#disk.call('unlink', { path });
628
751
  left -= 1;
629
752
  }
630
753
  catch {
@@ -24,10 +24,11 @@ import { gitReadEnv, probeGitSandboxAtStart } from './git-status.js';
24
24
  import { exitAfter } from './shutdown.js';
25
25
  import { consoleLogger } from './router.js';
26
26
  import { readHookHealth } from './health.js';
27
- import { consentAdminControl, consentCardAwaitedAt, consentCardLive, consentManagerPort, consentTranscriptOf, createConsentChannel, observeConsent, startConsentCycle, startConsentRegistration, watchConsentMode, } from './bootstrap/consent.js';
27
+ import { consentAdminControl, consentCardAwaitedAt, consentCardLive, consentForgottenPort, consentManagerPort, consentTranscriptOf, createConsentChannel, observeConsent, startConsentCycle, startConsentRegistration, watchConsentMode, } from './bootstrap/consent.js';
28
28
  import { createAliveSessionsSignal } from './bootstrap/alive-sessions.js';
29
29
  import { consentNoHookSources, consentSessionEntry } from './bootstrap/consent.js';
30
30
  import { createDeviceAuth, startDeviceSweep } from './bootstrap/devices.js';
31
+ import { startFolderGate } from './bootstrap/folder-gate.js';
31
32
  import { healthProbes } from './bootstrap/health.js';
32
33
  import { prepareHookFiles } from './bootstrap/hook-files.js';
33
34
  import { loadDemoHerdr } from './bootstrap/herdr.js';
@@ -190,6 +191,7 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
190
191
  const consentNoHook = cliVersionReader === null ? undefined : consentNoHookSources({
191
192
  link: consentLink, dataDir: config.dataDir, home: homedir(), roots: config.herdrRoots,
192
193
  entry: consentSessionEntry(cliVersionReader), proofGate: consentProofGate,
194
+ restartGraceMs: config.consentRestartGraceMs, startedAt: Date.now(),
193
195
  });
194
196
  const supervisor = herdr.createHerdrSupervisor({
195
197
  socketPath: config.herdrSocket,
@@ -211,7 +213,7 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
211
213
  ...(versionWatch === null ? {} : {
212
214
  onVersion: (version) => { versionWatch.observe('herdr', version); },
213
215
  }),
214
- // The first sessions after the start go to `alive.json` at once (`bootstrap/alive-sessions.ts`).
216
+ // A new session goes to `alive.json` at once (`bootstrap/alive-sessions.ts`).
215
217
  onAgentsChanged: aliveSessions.onAgentsChanged,
216
218
  /*
217
219
  * Fabryka dostaje `HerdrLaunchClient` zbudowany na TYM SAMYM gnieździe co reszta
@@ -441,6 +443,15 @@ async function main() {
441
443
  */
442
444
  const server = http.createServer();
443
445
  const iroh = await startServerIroh(config, server, log);
446
+ /*
447
+ * The folder gate before the first disk call of the work area: calls in a guarded folder of home go to a helper.
448
+ * It stays routed until the process ends: a call in such a folder during shutdown must not fall back to the server
449
+ * process, and the exit hook of the client kills the helpers when the process exits.
450
+ */
451
+ startFolderGate({
452
+ enabled: config.folderGate, home: homedir(), roots: [...config.projectRoots, ...config.herdrRoots],
453
+ log: (line) => { log.info(line); },
454
+ });
444
455
  // Hook files in the data directory, before anything reads them: roots, start cleanup, log rotation.
445
456
  prepareHookFiles(config, log);
446
457
  // Git under `sandbox-exec` on macOS (layer 2): one probe before the first read, one log line without it.
@@ -593,6 +604,7 @@ async function main() {
593
604
  }),
594
605
  // Karty kanału zgód: decyzje i zwolnienie tylko przy otwartym kanale (`main`, `all`), inaczej 410.
595
606
  ...(consentCycle === null ? {} : { consent: consentManagerPort(consentCycle, consentMode, log) }),
607
+ ...(consentCycle === null ? {} : { consentForgotten: consentForgottenPort(consentCycle, log) }),
596
608
  ...(prStatus === null ? {} : { prStatus: prStatus.port }),
597
609
  });
598
610
  managerRef = manager;
@@ -687,7 +699,14 @@ async function main() {
687
699
  socket.destroy();
688
700
  return;
689
701
  }
690
- term.handleUpgrade(req, socket, head);
702
+ // An exception in an `upgrade` listener is uncaught and would end the process before any credential.
703
+ try {
704
+ term.handleUpgrade(req, socket, head);
705
+ }
706
+ catch (err) {
707
+ log.error(`term: upgrade failed (${err instanceof Error ? err.name : 'non-error'}), socket closed`);
708
+ socket.destroy();
709
+ }
691
710
  });
692
711
  // Timeouty dla strumieni SSE i obsługa błędu `listen` (EADDRINUSE = kod 1), `bootstrap/http.ts`.
693
712
  configureHttpServer(server, config, log);
@@ -205,6 +205,9 @@ export async function startIroh(config, server, log, deps = {}) {
205
205
  const duplex = new IrohDuplex(stream, { slot, clock });
206
206
  entry.sockets.add(duplex);
207
207
  duplex.once('close', () => { entry.sockets.delete(duplex); });
208
+ // A throw in an `http.Server` listener comes back through the read loop as the socket's `'error'`. Node removes
209
+ // its own `'error'` listener before `'upgrade'`, and an unheard `'error'` would end the process.
210
+ duplex.on('error', ignore);
208
211
  entry.handle.attach(duplex);
209
212
  duplex.setTimeout(idleMs());
210
213
  try {
@@ -26,6 +26,7 @@ export const IROH_REFUSALS = [
26
26
  'origin', // mutation with an `Origin` other than `IROH_ORIGIN`
27
27
  'upgrade-refused', // WebSocket upgrade refused
28
28
  'login', // `/api/login` over iroh
29
+ 'bad-url', // request target that `URL` cannot parse
29
30
  ];
30
31
  /** Budget window. */
31
32
  export const LOG_BUDGET_WINDOW_MS = 60_000;
@@ -8,7 +8,8 @@
8
8
  * authenticated (higher stream limit, no deadline, protection from eviction), and revoking a device
9
9
  * (`revokeDevice`) removes it from all connections at once. The listener gets the state change through `onAuthChange`.
10
10
  *
11
- * HTTP layer refusals on an iroh socket (bad `Origin`, upgrade refusal, `/api/login`) go through
11
+ * HTTP layer refusals on an iroh socket (bad `Origin`, upgrade refusal, `/api/login`, a request target `URL` cannot
12
+ * parse) go through
12
13
  * {@link noteIrohRefusal} to the listener's log budget instead of an ordinary line: before authentication anyone who
13
14
  * knows the server's EndpointId can trigger them as often as they like.
14
15
  *
@@ -33,10 +33,11 @@
33
33
  * zapis atomowy. Retencji NIE MA — treść kasuje wyłącznie człowiek.
34
34
  */
35
35
  import { createHash } from 'node:crypto';
36
- import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
36
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
37
37
  import { join } from 'node:path';
38
38
  import { notesEmpty } from '@rarog/shared';
39
39
  import { say, textOf } from '@rarog/shared/sentences';
40
+ import { DIRECT_DISK } from '../folder-gate/disk.js';
40
41
  /**
41
42
  * Katalog plików notatek w `<dataDir>`. Cytują go `docs/security-model.md` (runbook)
42
43
  * i `docs/server-config.md`.
@@ -74,7 +75,7 @@ export class NotesFailure extends Error {
74
75
  export function notesPath(dataDir, cwd) {
75
76
  let real;
76
77
  try {
77
- real = realpathSync(cwd);
78
+ real = DIRECT_DISK.sync('realpath', { path: cwd });
78
79
  }
79
80
  catch {
80
81
  throw new NotesFailure('cwd-not-allowed', say('rest.notes-cwd-not-allowed'));
@@ -493,7 +493,19 @@ export function createRouter(deps) {
493
493
  async function handle(req, res) {
494
494
  const method = req.method ?? 'GET';
495
495
  // `req.url` jest ścieżką względną; base jest sztuczny, bierzemy z niego tylko pathname.
496
- const url = new URL(req.url ?? '/', 'http://127.0.0.1');
496
+ // The HTTP parser lets through targets `URL` rejects (`//:/`): a 400 before the Origin check, and on an iroh
497
+ // socket through the log budget, because anyone can send it before any credential.
498
+ let url;
499
+ try {
500
+ url = new URL(req.url ?? '/', 'http://127.0.0.1');
501
+ }
502
+ catch {
503
+ if (!noteIrohRefusal(req.socket, 'bad-url', `${method} ${req.url ?? ''}`)) {
504
+ log.info(`refused ${method}: request target does not parse as a URL`);
505
+ }
506
+ sendError(res, 400, 'bad-request', say('rest.bad-request'));
507
+ return;
508
+ }
497
509
  const pathname = url.pathname.replace(/\/+$/, '') || '/';
498
510
  const segments = pathname.split('/').filter((s) => s !== '');
499
511
  /*
@@ -9,6 +9,7 @@ import { MAX_RECENT_PROJECTS, MAX_RECENT_SESSIONS, makeDirBodySchema } from '@ra
9
9
  import { say } from '@rarog/shared/sentences';
10
10
  import { redact } from '../auth/index.js';
11
11
  import { validateProjectCwd } from '../config.js';
12
+ import { closedFolderOf } from '../folder-gate/disk.js';
12
13
  import { browseDirectory, demoListing } from '../fs-browse.js';
13
14
  import { makeDirectory, mkdirRefusal } from '../fs-mkdir.js';
14
15
  import { managerErrorStatus, methodNotAllowed, readValidatedBody, recheckDevice, sendError, sendFailure, sendJson, } from '../router.js';
@@ -20,6 +21,8 @@ import { managerErrorStatus, methodNotAllowed, readValidatedBody, recheckDevice,
20
21
  * seedów (`/Users/demo/Projects/...`) NIE istnieją na dysku,
21
22
  * - poza demo dowolna inna ścieżka („inna ścieżka…") musi przejść walidację korzeni:
22
23
  * istniejący katalog wewnątrz `RAROG_PROJECT_ROOTS`, bez segmentów ukrytych.
24
+ * Outside the demo a listed directory in a guarded folder the folder gate holds closed is refused with the sentence
25
+ * of the folder's state, judged by its text and without the disk, as `validateProjectCwd` refuses any other path.
23
26
  *
24
27
  * @returns znormalizowany katalog albo zdanie do odesłania w 400.
25
28
  */
@@ -45,7 +48,8 @@ export function checkCwd(cwd, config, manager) {
45
48
  }
46
49
  const target = path.resolve(raw);
47
50
  if (manager.projects().some((p) => path.resolve(p.path) === target)) {
48
- return { ok: true, cwd: target };
51
+ const closed = config.demo ? null : closedFolderOf(target);
52
+ return closed === null ? { ok: true, cwd: target } : { ok: false, sentence: closed.sentence };
49
53
  }
50
54
  if (config.demo) {
51
55
  return { ok: false, sentence: say('rest.cwd-not-in-projects') };