@rarog/server 1.1.0-beta.1 → 1.1.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 (95) 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/cli/update-registry.js +31 -1
  21. package/server/src/cli/update.js +128 -6
  22. package/server/src/config/protected-dirs.js +2 -0
  23. package/server/src/config/roots.js +13 -8
  24. package/server/src/config/work-area.js +36 -12
  25. package/server/src/config-env.js +9 -0
  26. package/server/src/config.js +17 -1
  27. package/server/src/demo/control.js +9 -1
  28. package/server/src/drivers/herdr/consent-no-hook.js +103 -8
  29. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  30. package/server/src/drivers/herdr-driver.js +78 -9
  31. package/server/src/files/file-index.js +5 -3
  32. package/server/src/files/listing.js +8 -2
  33. package/server/src/files/path-rule.js +95 -41
  34. package/server/src/files/refusals.js +14 -0
  35. package/server/src/files/session-gate.js +11 -6
  36. package/server/src/folder-gate/client.js +314 -0
  37. package/server/src/folder-gate/disk.js +455 -0
  38. package/server/src/folder-gate/folders.js +23 -0
  39. package/server/src/folder-gate/gate.js +220 -0
  40. package/server/src/folder-gate/helper.js +118 -0
  41. package/server/src/folder-gate/install.js +27 -0
  42. package/server/src/folder-gate/relay-worker.js +147 -0
  43. package/server/src/folder-gate/types.js +115 -0
  44. package/server/src/folder-gate/wire.js +170 -0
  45. package/server/src/fs-browse.js +55 -23
  46. package/server/src/fs-mkdir.js +3 -1
  47. package/server/src/git-status.js +13 -5
  48. package/server/src/git-watch.js +130 -19
  49. package/server/src/git-work-tree.js +3 -3
  50. package/server/src/herdr/client.js +2 -2
  51. package/server/src/herdr/commands/discover.js +21 -9
  52. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  53. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  54. package/server/src/herdr/dialogs/hook/contract.js +1 -1
  55. package/server/src/herdr/dialogs/index.js +7 -2
  56. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  57. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
  58. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  59. package/server/src/herdr/dialogs/router.js +21 -6
  60. package/server/src/herdr/dialogs/screen/parse.js +23 -2
  61. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  62. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  63. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  64. package/server/src/herdr/jsonl-follow.js +55 -14
  65. package/server/src/herdr/provenance.js +3 -3
  66. package/server/src/herdr/socket.js +25 -28
  67. package/server/src/herdr/supervisor.js +13 -10
  68. package/server/src/herdr/transcript-path.js +36 -0
  69. package/server/src/herdr/trust.js +11 -8
  70. package/server/src/herdr/uploads-registry.js +3 -2
  71. package/server/src/herdr/uploads.js +170 -47
  72. package/server/src/index.js +22 -3
  73. package/server/src/iroh/listener.js +3 -0
  74. package/server/src/iroh/log-budget.js +1 -0
  75. package/server/src/iroh/socket.js +2 -1
  76. package/server/src/notes/store.js +3 -2
  77. package/server/src/router.js +13 -1
  78. package/server/src/routes/projects.js +5 -1
  79. package/server/src/routes/sessions.js +10 -4
  80. package/server/src/routes/system.js +4 -0
  81. package/server/src/safe-read.js +12 -12
  82. package/server/src/sessions/companion-scope.js +10 -5
  83. package/server/src/sessions/done-retention.js +57 -0
  84. package/server/src/sessions/launch-gate.js +2 -2
  85. package/server/src/sessions/manager.js +35 -59
  86. package/server/src/sessions/project-scan.js +9 -3
  87. package/server/src/sessions/ring-buffer.js +8 -21
  88. package/server/src/sessions/session-git.js +31 -2
  89. package/server/src/sessions/session.js +1 -1
  90. package/server/src/sessions/state-sentences.js +1 -1
  91. package/server/src/sse.js +121 -22
  92. package/server/src/term/herdr-backend.js +2 -2
  93. package/server/src/term/index.js +2 -15
  94. package/server/src/term/registry.js +4 -3
  95. package/server/src/term/ws.js +9 -1
package/README.md CHANGED
@@ -40,8 +40,9 @@ Threat model, killswitches (flags that switch capabilities off) and how to repor
40
40
  - npm 11 or newer, or pnpm, for the npm package; pnpm 11.4.0 for a clone (`packageManager` in `package.json`).
41
41
  - Claude Code (`claude`), signed in with `/login`. Do not export `CLAUDE_CODE_OAUTH_TOKEN` or Anthropic API keys in
42
42
  interactive shells (for example in `~/.zshrc`): a session would use them instead of that login.
43
- - herdr (`herdr` in `PATH` or `~/.local/bin/herdr`) with API protocol 22 (herdr 0.9.0 to 0.9.5). With an older
44
- protocol Rarog does not work, with a newer one it only reads.
43
+ - herdr (`herdr` in `PATH` or `~/.local/bin/herdr`) with API protocol 22 or newer (tested on 22, herdr 0.9.0 to
44
+ 0.9.5). With an older protocol Rarog does not work. A newer one is untested, and Rarog works on it fully;
45
+ `RAROG_HERDR_SEND=0` keeps Rarog read-only on such a herdr.
45
46
  - A way for the app to reach the server: the iroh listener, where the native iroh module installs (Apple silicon,
46
47
  Linux x64 and arm64), or an HTTPS address in a private network: Tailscale (`rarog setup` maps it with
47
48
  `tailscale serve`) or your own reverse proxy with TLS. An Intel Mac has no iroh module, so it needs the HTTPS
@@ -131,6 +132,17 @@ checks the installation, and `rarog help` lists every command. Dictation needs `
131
132
  `~/.config/rarog/secret/private.env` (directory 0700, file 0600). By default the server keeps its state and its log
132
133
  `server.log` in `~/.local/share/rarog`.
133
134
 
135
+ ## Updating
136
+
137
+ ```bash
138
+ rarog update # the newest release; rarog update --beta also takes a newer beta
139
+ ```
140
+
141
+ `rarog update` installs the newest release from the npm registry with npm, in a terminal, and finishes it: the
142
+ Claude SDK, the service, the hook copy and a restart. A rollback is `npm i -g @rarog/server@<version>`, then
143
+ `rarog update --finish`. An installation made with pnpm updates by other steps; they and the details are in
144
+ [docs/distribution.md](docs/distribution.md), section "Install from the npm registry".
145
+
134
146
  ## Where next
135
147
 
136
148
  Documentation index: [docs/README.md](docs/README.md). Good starting points:
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rarog/shared",
3
- "version": "1.1.0-beta.1",
3
+ "version": "1.1.1",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,7 +22,7 @@
22
22
  * złotych ramek (`shared/test/sse-fixtures.test.ts` sprawdza nim `degrades`, które czyta Swift).
23
23
  */
24
24
  import { z } from 'zod';
25
- import { activityEventSchema, activitySchema, backgroundTaskSchema, blockSchema, contextLimitStateSchema, deltaEventSchema, gitFileDetailSchema, gitStatusEventSchema, helloEventSchema, herdrStatusEventSchema, inboxCardKindSchema, inboxDialogKindSchema, inboxEventSchemas, inboxHeadSchemaOf, messageAttachmentSchema, messageEventSchema, notesEventSchema, parseServerEvent, permissionPendingEventSchema, permissionRequestObjectSchema, permissionRequestSchema, permissionResolvedEventSchema, permissionSettledEventSchema, questionOptionSchema, questionPendingEventSchema, questionRequestSchema, questionSchema, questionResolvedEventSchema, sessionChangedEventSchema, sessionPullRequestSchema, sessionStateSchema, sessionsSnapshotEventSchema, sessionSummarySchema, stateEventSchema, transcriptMessageSchema, transcriptNoticeSchema, transcriptSnapshotEventSchema, usageEventSchema, toolCallBlockObjectSchema, waitingForSchema, withDetailTruncation, withDisplayTextTruncation, } from './protocol.js';
25
+ import { activityEventSchema, activitySchema, backgroundTaskSchema, blockSchema, contextLimitStateSchema, deltaEventSchema, folderAccessEventSchema, gitFileDetailSchema, gitStatusEventSchema, helloEventSchema, herdrStatusEventSchema, inboxCardKindSchema, inboxDialogKindSchema, inboxEventSchemas, inboxHeadSchemaOf, macFolderBlockSchema, macFolderStateSchema, messageAttachmentSchema, messageEventSchema, notesEventSchema, parseServerEvent, permissionPendingEventSchema, permissionRequestObjectSchema, permissionRequestSchema, permissionResolvedEventSchema, permissionSettledEventSchema, questionOptionSchema, questionPendingEventSchema, questionRequestSchema, questionSchema, questionResolvedEventSchema, sessionChangedEventSchema, sessionPullRequestSchema, sessionStateSchema, sessionsSnapshotEventSchema, sessionSummarySchema, stateEventSchema, transcriptMessageSchema, transcriptNoticeSchema, transcriptSnapshotEventSchema, usageEventSchema, toolCallBlockObjectSchema, waitingForSchema, withDetailTruncation, withDisplayTextTruncation, } from './protocol.js';
26
26
  /**
27
27
  * Wartownik „ta wersja klienta tego nie zna". Zarezerwowany w KLIENCIE: serwer go nie nadaje
28
28
  * i nie zna (schematy ścisłe), więc w polu stanu nie pomyli się z żadną prawdziwą wartością.
@@ -117,6 +117,11 @@ export const DEGRADATIONS = {
117
117
  * value is one item with nothing left to show and is ignored whole.
118
118
  */
119
119
  'inbox.head': undefined,
120
+ /**
121
+ * A `folder-access` block with an unknown `state`: that folder drops out of the list and the other blocks stay, so a
122
+ * state added later does not hide the folders an older app can name.
123
+ */
124
+ 'folder-access.block': undefined,
120
125
  };
121
126
  /**
122
127
  * Znacznik widoku surowego: ta wartość przeszła GAŁĄŹ ZAPASOWĄ. Zgłaszany zawsze, bez porównania
@@ -264,6 +269,15 @@ function buildSchemas(raw) {
264
269
  }).transform((head) => new Dropped(head));
265
270
  const inboxHeads = z.array(z.union([inboxHead, unreadableHead]))
266
271
  .transform((heads) => (raw ? heads : heads.filter((head) => !(head instanceof Dropped))));
272
+ /*
273
+ * `folder-access`: a block with an unknown string in `state` drops out and the rest of the list stays. Any other
274
+ * broken block (`null`, a missing field, an empty `path`) still rejects the frame, also next to an unknown state.
275
+ */
276
+ const unreadableBlock = macFolderBlockSchema.extend({
277
+ state: lenient(macFolderStateSchema, undefined),
278
+ }).transform((block) => new Dropped(block));
279
+ const folderBlocks = z.array(z.union([macFolderBlockSchema, unreadableBlock]))
280
+ .transform((blocks) => (raw ? blocks : blocks.filter((block) => !(block instanceof Dropped))));
267
281
  return z.discriminatedUnion('type', [
268
282
  helloEventSchema,
269
283
  sessionsSnapshotEventSchema.extend({ sessions: z.array(summary) }),
@@ -300,6 +314,7 @@ function buildSchemas(raw) {
300
314
  usageEventSchema,
301
315
  herdrStatusEventSchema,
302
316
  notesEventSchema,
317
+ folderAccessEventSchema.extend({ blocked: folderBlocks }),
303
318
  inboxHeadsEvent.extend({ heads: inboxHeads }),
304
319
  // One head is one item: an unknown value ignores the frame, and the next head or `GET /api/inbox` mends it.
305
320
  inboxHeadEvent,
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Protocol contract, macOS folders area: the `folder-access` SSE frame (`FolderAccessEvent`), the guarded folders of
3
+ * the home directory the server keeps closed until macOS lets it in.
4
+ *
5
+ * The full list goes in every frame, sorted by `name`. A server with the folder gate on sends it on every global
6
+ * stream right after `sessions-snapshot`, also empty, and again on every change of the list. The frame is fleeting:
7
+ * `seq: null`, outside every ring buffer. A server without the gate never sends it.
8
+ *
9
+ * Re-exported unchanged by `shared/src/protocol.ts`; code imports the names from there.
10
+ */
11
+ import { z } from 'zod';
12
+ /**
13
+ * Why a folder is closed: `waiting` (no answer from the disk, macOS probably shows a window on the Mac), `denied`
14
+ * (macOS refused; System Settings decide) or `unchecked` (the server could not tell; details in the server log).
15
+ */
16
+ export const MAC_FOLDER_STATES = ['waiting', 'denied', 'unchecked'];
17
+ export const macFolderStateSchema = z.enum(MAC_FOLDER_STATES);
18
+ export const macFolderBlockSchema = z.object({
19
+ name: z.string().min(1),
20
+ path: z.string().min(1),
21
+ state: macFolderStateSchema,
22
+ since: z.string(),
23
+ });
24
+ export const folderAccessEventSchema = z.object({
25
+ type: z.literal('folder-access'),
26
+ blocked: z.array(macFolderBlockSchema),
27
+ });
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Protocol contract, herdr area: the pane's permission mode read from the screen and the availability of the herdr
3
3
  * integration (`HerdrStatus`, the source of the "herdr unavailable" banner and of the launch permission).
4
+ * The live availability change, the `herdr-status` SSE frame, lives here too (`HerdrStatusEvent`).
4
5
  *
5
6
  * Re-exported unchanged by `shared/src/protocol.ts`; code imports the names from there.
6
7
  */
@@ -21,3 +22,25 @@ const _herdrStatusSchemaMatchesType = true;
21
22
  const _herdrStatusTypeMatchesSchema = true;
22
23
  void _herdrStatusSchemaMatchesType;
23
24
  void _herdrStatusTypeMatchesSchema;
25
+ /**
26
+ * Świadomie WĘŻSZY niż `herdrStatusSchema`: `version`/`protocol` interesują tylko ramkę
27
+ * startową (baner „protokół nowszy niż testowany"), a nie każdą zmianę dostępności.
28
+ *
29
+ * `canLaunch` is not cosmetic: with the answer to "may I start a session" only in the
30
+ * `sessions-snapshot` frame, the phone would keep the last known value until the next reconnect,
31
+ * so a panel closed by hand at the Mac would free a slot while the app still showed a dimmed "+"
32
+ * and the limit sentence.
33
+ *
34
+ * OPCJONALNE, bo event jest współdzielony ze starszymi wydaniami frontu i backendu: brak pola
35
+ * znaczy „nie wiem", a nie „nie wolno" — klient zostawia wtedy poprzednią wartość zamiast gasić
36
+ * przycisk na podstawie ciszy.
37
+ */
38
+ export const herdrStatusEventSchema = z.object({
39
+ type: z.literal('herdr-status'),
40
+ available: z.boolean(),
41
+ agentCount: z.number(),
42
+ readOnly: z.boolean(),
43
+ canLaunch: z.boolean().optional(),
44
+ detail: z.string().optional(),
45
+ detailRef: sentenceRefSchema.optional(),
46
+ });
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Protocol contract, project notes area: `/api/notes`.
2
+ * Protocol contract, project notes area: `/api/notes` and the `notes` SSE frame (`NotesEvent`).
3
3
  *
4
4
  * Re-exported unchanged by `shared/src/protocol.ts`; code imports the names from there.
5
5
  */
@@ -89,3 +89,9 @@ export const notesConflictBodySchema = z.object({
89
89
  messageRef: sentenceRefSchema.optional(),
90
90
  current: notesDocSchema,
91
91
  });
92
+ /** Project notes changed: the directory and the "empty after the write" bit, no content ({@link NotesEvent}). */
93
+ export const notesEventSchema = z.object({
94
+ type: z.literal('notes'),
95
+ cwd: z.string().min(1),
96
+ empty: z.boolean(),
97
+ });
@@ -15,9 +15,11 @@ import { imageDataUrlSchema, messageAttachmentSchema } from './protocol/attachme
15
15
  import { backgroundTaskSchema, sessionArtifactSchema, sessionPullRequestSchema, sessionScheduledTaskSchema, } from './protocol/background.js';
16
16
  import { consentAlwaysEntrySchema, SCREEN_UNAVAILABLE_REASONS, } from './protocol/consent.js';
17
17
  import { gitCommitSchema, gitFileDetailSchema, gitFileKindsSchema, } from './protocol/git.js';
18
- import { herdrModeSchema, herdrStatusSchema } from './protocol/herdr.js';
18
+ import { herdrModeSchema, herdrStatusEventSchema, herdrStatusSchema, } from './protocol/herdr.js';
19
19
  import { inboxEventSchemas } from './protocol/inbox.js';
20
20
  import { effortLevelSchema, modelIdSchema } from './protocol/model.js';
21
+ import { notesEventSchema } from './protocol/notes.js';
22
+ import { folderAccessEventSchema } from './protocol/folders.js';
21
23
  export * from './protocol/activity.js';
22
24
  export * from './protocol/attachments.js';
23
25
  export * from './protocol/background.js';
@@ -27,6 +29,7 @@ export * from './protocol/dictation.js';
27
29
  export * from './protocol/diff.js';
28
30
  export * from './protocol/directories.js';
29
31
  export * from './protocol/files.js';
32
+ export * from './protocol/folders.js';
30
33
  export * from './protocol/git.js';
31
34
  export * from './protocol/herdr.js';
32
35
  export * from './protocol/inbox.js';
@@ -547,34 +550,6 @@ export const usageEventSchema = z.object({
547
550
  contextTokens: z.number(),
548
551
  contextLimit: z.number(),
549
552
  });
550
- /**
551
- * Świadomie WĘŻSZY niż `herdrStatusSchema`: `version`/`protocol` interesują tylko ramkę
552
- * startową (baner „protokół nowszy niż testowany"), a nie każdą zmianę dostępności.
553
- *
554
- * `canLaunch` is not cosmetic: with the answer to "may I start a session" only in the
555
- * `sessions-snapshot` frame, the phone would keep the last known value until the next reconnect,
556
- * so a panel closed by hand at the Mac would free a slot while the app still showed a dimmed "+"
557
- * and the limit sentence.
558
- *
559
- * OPCJONALNE, bo event jest współdzielony ze starszymi wydaniami frontu i backendu: brak pola
560
- * znaczy „nie wiem", a nie „nie wolno" — klient zostawia wtedy poprzednią wartość zamiast gasić
561
- * przycisk na podstawie ciszy.
562
- */
563
- export const herdrStatusEventSchema = z.object({
564
- type: z.literal('herdr-status'),
565
- available: z.boolean(),
566
- agentCount: z.number(),
567
- readOnly: z.boolean(),
568
- canLaunch: z.boolean().optional(),
569
- detail: z.string().optional(),
570
- detailRef: sentenceRefSchema.optional(),
571
- });
572
- /** Project notes changed: the directory and the "empty after the write" bit, no content ({@link ServerEvent}). */
573
- export const notesEventSchema = z.object({
574
- type: z.literal('notes'),
575
- cwd: z.string().min(1),
576
- empty: z.boolean(),
577
- });
578
553
  export const serverEventSchema = z.discriminatedUnion('type', [
579
554
  helloEventSchema,
580
555
  sessionsSnapshotEventSchema,
@@ -591,8 +566,7 @@ export const serverEventSchema = z.discriminatedUnion('type', [
591
566
  stateEventSchema,
592
567
  gitStatusEventSchema,
593
568
  usageEventSchema,
594
- herdrStatusEventSchema,
595
- notesEventSchema,
569
+ herdrStatusEventSchema, notesEventSchema, folderAccessEventSchema,
596
570
  ...inboxEventSchemas(sessionStateSchema),
597
571
  ]);
598
572
  const _schemaMatchesType = true;
@@ -69,10 +69,6 @@ export const HERDR_SENTENCES = {
69
69
  en: 'herdr protocol {protocol} is older than the tested {oldest}. Integration is turned off.',
70
70
  args: ['protocol:text', 'oldest:text'],
71
71
  },
72
- 'herdr.protocol-unknown': {
73
- en: 'herdr protocol {protocol} is unknown (tested: {tested}), read-only',
74
- args: ['protocol:text', 'tested:text'],
75
- },
76
72
  'herdr.response-bad-shape': { en: 'The `{method}` response has an unknown shape.', args: ['method:text'] },
77
73
  'herdr.response-foreign-id': {
78
74
  en: 'A herdr response with an unexpected ID (expected {expected}). Protocol error.',
@@ -91,7 +91,13 @@ export const SENTENCES = Object.freeze({
91
91
  /**
92
92
  * Kody wycofane. Wpis przenosi się tu z pliku obszaru bez zmiany szablonu i argumentów, z `since`; nie znika nigdy.
93
93
  */
94
- export const RETIRED = Object.freeze({});
94
+ export const RETIRED = Object.freeze({
95
+ 'herdr.protocol-unknown': {
96
+ en: 'herdr protocol {protocol} is unknown (tested: {tested}), read-only',
97
+ args: ['protocol:text', 'tested:text'],
98
+ since: '1.1.0',
99
+ },
100
+ });
95
101
  /** Kształt `ref` na drucie; uszkodzony `ref` (`null`, pusty kod, ponad 8 argumentów, nie-łańcuch) odrzuca ramkę. */
96
102
  export const sentenceRefSchema = z.object({
97
103
  code: z.string().min(1),
@@ -56,6 +56,14 @@ export const REST_SENTENCES = {
56
56
  'rest.companion-throttled': { en: 'Too soon. Wait a moment and start the conversation again.' },
57
57
  'rest.companion-timeout': { en: 'Checking the session took too long. Try again.' },
58
58
  'rest.cwd-empty': { en: 'Enter the path to a project directory.' },
59
+ 'rest.cwd-folder-denied': {
60
+ en: "macOS doesn't let Rarog into this folder. Change it in System Settings on the Mac "
61
+ + '(Privacy & Security → Files & Folders).',
62
+ },
63
+ 'rest.cwd-folder-unchecked': { en: "Rarog can't check access to this folder. The server log has the details." },
64
+ 'rest.cwd-folder-waiting': {
65
+ en: "Rarog can't open this folder: macOS is probably waiting for someone to click Allow on the Mac.",
66
+ },
59
67
  'rest.cwd-hidden': { en: "Hidden directories (those starting with a dot) aren't allowed." },
60
68
  'rest.cwd-not-absolute': { en: 'Enter the full directory path, starting with “/” or “~/”.' },
61
69
  'rest.cwd-not-found': { en: "That directory doesn't exist." },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rarog/server",
3
- "version": "1.1.0-beta.1",
3
+ "version": "1.1.1",
4
4
  "description": "Rarog is a free, open-source (MIT) iPhone and iPad app, plus a server on your Mac or Linux machine, that shows the Claude Code sessions running in Herdr TUI and lets you drive them.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@number0/iroh": "1.2.0",
37
- "@rarog/shared": "1.1.0-beta.1",
37
+ "@rarog/shared": "1.1.1",
38
38
  "qrcode": "1.5.4",
39
39
  "ws": "8.21.3",
40
40
  "zod": "4.4.3"
@@ -68,9 +68,11 @@ function deviceRow(record) {
68
68
  creator: record.creator, build: sanitizeBuild(record.build),
69
69
  };
70
70
  }
71
+ /** Tombstone on the list and in the revoke replies; the label goes through the pairing rules like {@link deviceRow}. */
71
72
  function tombRow(tomb) {
72
73
  return {
73
- id: tomb.id, label: tomb.label, createdAt: tomb.createdAt, revokedAt: tomb.revokedAt, revokedBy: tomb.revokedBy,
74
+ id: tomb.id, label: sanitizeLabel(tomb.label), createdAt: tomb.createdAt, revokedAt: tomb.revokedAt,
75
+ revokedBy: tomb.revokedBy,
74
76
  };
75
77
  }
76
78
  /** HTTP handler of the admin socket. Port 8930 does NOT have these routes (the router returns 404). */
@@ -156,6 +156,8 @@ export function consentNoHookSources(options) {
156
156
  outsideWorkArea: (cwd) => !inWorkAreaOnDisk(cwd, options.roots, options.home),
157
157
  statusline: (sessionId) => statuslineFreshness(statuslineRoot, sessionId, Date.now()),
158
158
  proofRules: (sessionId) => options.proofGate.current(sessionId),
159
+ restarting: () => Date.now() < options.startedAt + options.restartGraceMs,
160
+ screenKey: (sessionId, key) => { options.link.cycle?.screenKey(sessionId, key); },
159
161
  };
160
162
  }
161
163
  /**
@@ -423,6 +425,15 @@ export function consentManagerCards(consentCycle, engineSessionId) {
423
425
  return { ...card, decision: record.decision, ...(record.retired === undefined ? {} : { retired: true }) };
424
426
  });
425
427
  }
428
+ /**
429
+ * Receiver of a forgotten conversation for the manager: the cycle drops the session's entries
430
+ * (`ConsentCycle.forgetSession`). A failure leaves one log line instead of an unhandled rejection.
431
+ */
432
+ export function consentForgottenPort(consentCycle, log) {
433
+ return (engineSessionId) => {
434
+ void consentStep('forget session', (line) => { log.error(line); }, () => consentCycle.forgetSession(engineSessionId));
435
+ };
436
+ }
426
437
  /** The consent port of the manager over the channel cycle. */
427
438
  export function consentManagerPort(consentCycle, consentMode, log) {
428
439
  return {
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Server start: the folder gate. With the gate on, it makes the relay client and the gate of the process, routes the
3
+ * work-area disk port through them and starts the helper of each guarded folder that holds a root, so the first real
4
+ * call there does not pay for the start. With the gate off (the kill switch, Linux, the demo) it makes nothing and
5
+ * every disk call stays in the server process. It touches no guarded folder: a helper starts on a call on `/`.
6
+ */
7
+ import path from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { FOLDER_SYNC_BOUND_MS, RelayFolderClient } from '../folder-gate/client.js';
10
+ import { routeWorkAreaDisk } from '../folder-gate/disk.js';
11
+ import { MacFolderGate } from '../folder-gate/gate.js';
12
+ import { folderHelperCommand } from '../folder-gate/helper.js';
13
+ import { installFolderGate } from '../folder-gate/install.js';
14
+ import { INSTALL_MODE, INSTALL_ROOT } from '../install/mode.js';
15
+ /** The module of the relay thread for the install at `root`: TypeScript in a clone, JavaScript in the package. */
16
+ export function folderRelayUrl(root = INSTALL_ROOT, mode = INSTALL_MODE) {
17
+ const file = mode === 'package' ? 'relay-worker.js' : 'relay-worker.ts';
18
+ return pathToFileURL(path.join(root, 'server', 'src', 'folder-gate', file));
19
+ }
20
+ /** Installs the gate when `enabled`; `null` when off, and then nothing was made. */
21
+ export function startFolderGate(options) {
22
+ if (!options.enabled) {
23
+ options.log('folder gate: off, disk calls in guarded folders run in the server process');
24
+ return null;
25
+ }
26
+ const client = new RelayFolderClient({ relay: folderRelayUrl(), helper: folderHelperCommand() });
27
+ const gate = new MacFolderGate({ home: options.home, client, boundMs: FOLDER_SYNC_BOUND_MS, log: options.log });
28
+ const uninstall = installFolderGate(gate);
29
+ const unroute = routeWorkAreaDisk({ gate, client, home: options.home });
30
+ options.log('folder gate: on, disk calls in guarded folders run in a helper process per folder');
31
+ const folders = new Set();
32
+ for (const root of options.roots) {
33
+ const folder = gate.stateOf(root)?.folder;
34
+ if (folder !== undefined)
35
+ folders.add(folder);
36
+ }
37
+ for (const folder of [...folders].sort()) {
38
+ // A call on `/`, not in the folder: the helper starts, and macOS has nothing to ask about.
39
+ void client.call(folder, 'lstat', { path: '/' });
40
+ options.log(`folder gate: started the helper of ${path.basename(folder)}, a root lies in it`);
41
+ }
42
+ let disposed = false;
43
+ return {
44
+ gate,
45
+ dispose: () => {
46
+ if (disposed)
47
+ return;
48
+ disposed = true;
49
+ unroute();
50
+ uninstall();
51
+ gate.dispose();
52
+ client.dispose();
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The server log of the service (`<dataDir>/server.log`) before launchd or systemd opens it: `rarog service install`
3
+ * creates the file with mode 0600 and sets an existing one to 0600. Both supervisors open the log for appending and
4
+ * keep its mode, so the server process umask stays as it is (directories the server creates keep their modes).
5
+ * A path that is not a regular file (a symlink, a FIFO) is left alone, and an error is one line, not a failure: the
6
+ * install has already stopped the server, and the service starts with the log as it was.
7
+ */
8
+ import { chmodSync, lstatSync, writeFileSync } from 'node:fs';
9
+ import { out } from './io.js';
10
+ const LOG_MODE = 0o600;
11
+ /** Creates the log with mode 0600 or sets a regular file to 0600, and prints one line about it. */
12
+ export function prepareServiceLog(io, file) {
13
+ try {
14
+ const found = lstatSync(file, { throwIfNoEntry: false });
15
+ if (found !== undefined && !found.isFile()) {
16
+ out(io, ` server log ${file}: not a regular file, mode left as it is`);
17
+ return;
18
+ }
19
+ writeFileSync(file, '', { flag: 'a', mode: LOG_MODE });
20
+ chmodSync(file, LOG_MODE);
21
+ out(io, ` server log ${file} (mode 0600)`);
22
+ }
23
+ catch (failure) {
24
+ const code = failure.code ?? String(failure);
25
+ out(io, ` server log ${file}: mode 0600 not set (${code}), the service appends to it as it is`);
26
+ }
27
+ }
@@ -20,7 +20,7 @@
20
20
  * (`loadState` z `restart.ts`), a „nie wiem” (`launchctl print` z kodem innym niż 0 i 113) to odmowa przed
21
21
  * `bootout`.
22
22
  * - **faza 1:** `bootout` `ai.rarog.server`, jeśli jest załadowana, z czekaniem (do 30 s), aż launchd zdejmie
23
- * etykietę ({@link waitUntilAbsent}); katalog danych 0700 (launchd zakłada plik logu, ale nie katalog); zapis
23
+ * etykietę ({@link waitUntilAbsent}); katalog danych 0700, przed `bootstrap` plik logu 0600 (`service-log.ts`); zapis
24
24
  * plistu; `bootstrap`; `scripts/restart.sh` z etykietą, portem i logiem (ubija resztki na porcie, `kickstart`,
25
25
  * health), wołany wprost, bo blokadę trzyma już `install`; na końcu dowiązanie `~/.local/bin/rarog` (tylko klon
26
26
  * repo; w paczce polecenie `rarog` daje menedżer paczek).
@@ -48,7 +48,7 @@
48
48
  * `~/.config/systemd/user`; jednostka bez drop-inów; węzeł; `curl`, `ps`, `pgrep`; `serve --check` na środowisku
49
49
  * menedżera; gniazdo ≤ 103 B i żaden serwer tych danych na innym porcie; wrapper; jednostka z szablonu w pliku
50
50
  * tymczasowym i `systemd-analyze verify` (tryb systemowy, działa bez menedżera; brak narzędzia = linia „nie
51
- * sprawdzone”); pełne `--check` przez wrapper (ten sam katalog danych i port co bez niego); stan jednostki. Faza 1: zapis atomowy, `daemon-reload`, `enable`, katalog danych 0700, `restart.sh`
51
+ * sprawdzone”); pełne `--check` przez wrapper (ten sam katalog danych i port co bez niego); stan jednostki. Faza 1: zapis atomowy, `daemon-reload`, `enable`, katalog danych 0700, plik logu 0600, `restart.sh`
52
52
  * z `RAROG_RESTART_UNIT`, linia o lingerze, dowiązanie; porażka wypisuje komendy powrotu. `uninstall` = `disable
53
53
  * --now`, unit file removal, `daemon-reload`, this clone's symlink as on macOS. Inna platforma = odmowa.
54
54
  */
@@ -69,6 +69,7 @@ import { SETTINGS_BACKUP_DIRNAME, copyRemovalCheck, entriesDiff, entriesQuestion
69
69
  import { EXIT_OK, EXIT_REFUSED, Refusal, Usage, err, homeOf, isYes, out, platformOf, terminalOf } from './io.js';
70
70
  import { childExitText } from './child-output.js';
71
71
  import { acquireLock } from './lock.js';
72
+ import { prepareServiceLog } from './service-log.js';
72
73
  import { LAUNCHD_PATH, LINUX_RESTART_TOOLS, NOTHING_STOPPED, SERVICE_LABEL, accepts, decidedLoadState, installedServiceDataDir, launchdDomain, launchdEnv, launchdTarget, loadState, nodeRequirement, onPath, refuseLaunchdDataDirEnv, runRestartScript, scriptEnv, serviceNodeVersionOk, servicePackageFromClone, servicePackageText, servicePlistArgv, servicePlistPath, unitArgv, } from './restart.js';
73
74
  import { confirm as confirmForm } from './screen/ask.js';
74
75
  import { layoutOf } from './screen/style.js';
@@ -605,6 +606,7 @@ async function switchOver(io, prepared, fail, wait, output) {
605
606
  const plistFile = servicePlistPath(home);
606
607
  try {
607
608
  mkdirSync(dataDir, { recursive: true, mode: 0o700 });
609
+ prepareServiceLog(io, path.join(dataDir, 'server.log'));
608
610
  mkdirSync(path.dirname(plistFile), { recursive: true });
609
611
  writeAtomic(plistFile, plist);
610
612
  out(io, ` plist ${plistFile}`);
@@ -971,6 +973,7 @@ async function applyUnit(io, prepared, output) {
971
973
  out(io, ` systemctl --user ${args.join(' ')}`);
972
974
  }
973
975
  mkdirSync(dataDir, { recursive: true, mode: 0o700 });
976
+ prepareServiceLog(io, path.join(dataDir, 'server.log'));
974
977
  out(io, ` restart.sh with unit ${UNIT_NAME}, port ${String(port)}:`);
975
978
  const result = await runRestartScript(scriptEnv(io, {
976
979
  RAROG_RESTART_UNIT: UNIT_NAME,
@@ -26,7 +26,7 @@
26
26
  <!-- `Interactive`, not `Background`: the server serves a person in real time. -->
27
27
  <key>ProcessType</key>
28
28
  <string>Interactive</string>
29
- <!-- Server log in the data directory; launchd APPENDS to it (it creates the file, the installation the directory). -->
29
+ <!-- Server log in the data directory, mode 0600: the installation creates it, launchd APPENDS to it. -->
30
30
  <key>StandardOutPath</key>
31
31
  <string>{{LOG}}</string>
32
32
  <key>StandardErrorPath</key>
@@ -17,7 +17,7 @@ WorkingDirectory={{WORKING_DIRECTORY}}
17
17
  ExecStart={{EXEC_START}}
18
18
  Restart=always
19
19
  RestartSec=2
20
- # Server log in the data directory, appended; the installation creates the directory.
20
+ # Server log in the data directory, mode 0600: the installation creates the directory and the file, systemd appends.
21
21
  StandardOutput=append:{{LOG}}
22
22
  StandardError=append:{{LOG}}
23
23
 
@@ -24,6 +24,19 @@ export const RELEASE_SOURCE = {
24
24
  };
25
25
  /** Where to report a version that fails the check (the repository's security policy). */
26
26
  export const REPORT_FIX = `do not install it by hand; report it at ${RELEASE_SOURCE.repository}/security`;
27
+ /**
28
+ * The clause of {@link attestationSigner} for a certificate the pinned authority did not issue. From here a new
29
+ * Sigstore certificate and a forged attestation look the same, so the clause names both.
30
+ */
31
+ export const OTHER_AUTHORITY = 'has a certificate from another authority than the pinned one: Sigstore changed its'
32
+ + ' certificate, or the attestation is forged';
33
+ /**
34
+ * The fix of {@link OTHER_AUTHORITY}: a version that pins Sigstore's new certificate is announced on the releases
35
+ * page of the repository. No install command: one typed from here would install without this check.
36
+ */
37
+ export const OTHER_AUTHORITY_FIX = `check ${RELEASE_SOURCE.repository}/releases for a release with Sigstore's new`
38
+ + ` certificate before you install a version by hand; if there is none, report it at ${RELEASE_SOURCE.repository}`
39
+ + '/security';
27
40
  /** The predicate type of the SLSA provenance npm keeps next to a version published from a CI run. */
28
41
  const PROVENANCE = 'https://slsa.dev/provenance/v1';
29
42
  /** The payload type of an in-toto statement in a DSSE envelope. */
@@ -31,7 +44,8 @@ const STATEMENT_TYPE = 'application/vnd.in-toto+json';
31
44
  /**
32
45
  * The certificate authority that issues the signing certificate of a GitHub Actions run: the intermediate of
33
46
  * Sigstore's public Fulcio (`O=sigstore.dev, CN=sigstore-intermediate`, valid until October 2031), DER in base64 as
34
- * Sigstore's trust root (`trusted_root.json`) carries it. A provenance signed under another authority is refused.
47
+ * Sigstore's trust root (`trusted_root.json`) carries it. A provenance signed under another authority is refused
48
+ * ({@link OTHER_AUTHORITY}); `scripts/sigstore-pin.ts` tells whether Sigstore still issues under this one.
35
49
  */
36
50
  const FULCIO_INTERMEDIATE = [
37
51
  'MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREw',
@@ -168,9 +182,8 @@ export function attestationSigner(signed, authority) {
168
182
  ]);
169
183
  try {
170
184
  const issuer = new X509Certificate(authority);
171
- if (!certificate.checkIssued(issuer) || !certificate.verify(issuer.publicKey)) {
172
- return 'has a certificate Sigstore did not issue';
173
- }
185
+ if (!certificate.checkIssued(issuer) || !certificate.verify(issuer.publicKey))
186
+ return OTHER_AUTHORITY;
174
187
  if (!verify('sha256', signedBytes, certificate.publicKey, Buffer.from(signature.sig, 'base64'))) {
175
188
  return 'has a signature its certificate did not make';
176
189
  }
@@ -192,17 +205,20 @@ export function attestationSigner(signed, authority) {
192
205
  * provenance of this version passes {@link attestationSigner} under `authority`, its certificate's only subject
193
206
  * alternative name is {@link releaseIdentity}, and the signed statement is a provenance that names this package
194
207
  * version, this file's sha512 and the same repository, workflow and tag. The certificate decides, because the
195
- * statement is text the signing run wrote.
208
+ * statement is text the signing run wrote. Every refusal has {@link REPORT_FIX}, except a certificate of another
209
+ * authority ({@link OTHER_AUTHORITY_FIX}): that one can be a new Sigstore certificate.
196
210
  */
197
211
  export function provenanceProblem(audit, expected, authority = fulcioAuthority()) {
212
+ const problem = (summary) => ({ summary, fix: REPORT_FIX });
198
213
  const id = `${RAROG_PACKAGE_NAME} ${expected.version}`;
199
214
  if (!isRecord(audit))
200
- return `npm gave no signature check result for ${id}`;
215
+ return problem(`npm gave no signature check result for ${id}`);
201
216
  const { invalid, missing, verified } = audit;
202
- if (Array.isArray(invalid) && invalid.length > 0)
203
- return `npm found an invalid signature or attestation of ${id}`;
217
+ if (Array.isArray(invalid) && invalid.length > 0) {
218
+ return problem(`npm found an invalid signature or attestation of ${id}`);
219
+ }
204
220
  if (Array.isArray(missing) && missing.length > 0)
205
- return `npm found no registry signature of ${id}`;
221
+ return problem(`npm found no registry signature of ${id}`);
206
222
  const thisVersion = (one) => isRecord(one) && one.name === RAROG_PACKAGE_NAME
207
223
  && one.version === expected.version;
208
224
  const entry = Array.isArray(verified) ? verified.find(thisVersion) : undefined;
@@ -212,27 +228,29 @@ export function provenanceProblem(audit, expected, authority = fulcioAuthority()
212
228
  : [];
213
229
  const [provenance] = provenances;
214
230
  if (!isRecord(provenance))
215
- return `${id} has no verified provenance`;
231
+ return problem(`${id} has no verified provenance`);
216
232
  if (provenances.length !== 1)
217
- return `${id} has more than one provenance`;
233
+ return problem(`${id} has more than one provenance`);
218
234
  const signer = attestationSigner(provenance.bundle, authority);
235
+ if (signer === OTHER_AUTHORITY)
236
+ return { summary: `the provenance of ${id} ${signer}`, fix: OTHER_AUTHORITY_FIX };
219
237
  if (typeof signer === 'string')
220
- return `the provenance of ${id} ${signer}`;
238
+ return problem(`the provenance of ${id} ${signer}`);
221
239
  const identity = releaseIdentity(expected.version);
222
240
  if (signer.names !== `URI:${identity}`) {
223
241
  const single = /^URI:([^,\s]+)$/u.exec(signer.names)?.[1];
224
242
  const shown = single === undefined ? 'a certificate with other names' : printable(single);
225
- return `${id} was signed by ${shown}, not by ${identity}`;
243
+ return problem(`${id} was signed by ${shown}, not by ${identity}`);
226
244
  }
227
245
  const { statement } = signer;
228
246
  if (statement.predicateType !== PROVENANCE)
229
- return `the provenance of ${id} is another kind of statement`;
247
+ return problem(`the provenance of ${id} is another kind of statement`);
230
248
  const subjects = statement.subject;
231
249
  const purl = `pkg:npm/${RAROG_PACKAGE_NAME.replace(/^@/u, '%40')}@${expected.version}`;
232
250
  const subject = Array.isArray(subjects) && subjects.length === 1 ? subjects[0] : undefined;
233
251
  if (!isRecord(subject) || subject.name !== purl || !isRecord(subject.digest)
234
252
  || subject.digest.sha512 !== expected.sha512) {
235
- return `the provenance of ${id} names another tarball`;
253
+ return problem(`the provenance of ${id} names another tarball`);
236
254
  }
237
255
  const { predicate } = statement;
238
256
  const definition = isRecord(predicate) ? predicate.buildDefinition : undefined;
@@ -240,7 +258,7 @@ export function provenanceProblem(audit, expected, authority = fulcioAuthority()
240
258
  const workflow = isRecord(parameters) ? parameters.workflow : undefined;
241
259
  if (!isRecord(workflow) || workflow.repository !== RELEASE_SOURCE.repository
242
260
  || workflow.path !== RELEASE_SOURCE.workflow || workflow.ref !== `refs/tags/v${expected.version}`) {
243
- return `the provenance of ${id} names another workflow than ${identity}`;
261
+ return problem(`the provenance of ${id} names another workflow than ${identity}`);
244
262
  }
245
263
  return null;
246
264
  }
@@ -295,9 +313,9 @@ export async function verifyTarball(input) {
295
313
  // which says nothing about the package.
296
314
  if (isRecord(report) && !found && !Array.isArray(report.verified))
297
315
  return { kind: 'old-npm' };
298
- const problem = provenanceProblem(report, { version, sha512 }, input.authority);
299
- if (problem !== null)
300
- return { kind: 'refused', summary: problem, fix: REPORT_FIX };
316
+ const refusal = provenanceProblem(report, { version, sha512 }, input.authority);
317
+ if (refusal !== null)
318
+ return { kind: 'refused', ...refusal };
301
319
  input.log(` npm: ${id} provenance verified: ${releaseIdentity(version)}`);
302
320
  return { kind: 'verified' };
303
321
  }