rvlib-shipkit 2.31.0 → 2.33.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 (408) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/package.json +1 -1
  3. package/src/advisors/acts.ts +16 -15
  4. package/src/advisors/advice.ts +56 -102
  5. package/src/advisors/advisor-view.ts +122 -76
  6. package/src/advisors/app-graph.ts +1 -1
  7. package/src/advisors/app.ts +3 -11
  8. package/src/advisors/cf-api.ts +1 -1
  9. package/src/advisors/dir-bucket.ts +4 -3
  10. package/src/advisors/edge/api.ts +20 -221
  11. package/src/advisors/edge/bucket.ts +2 -2
  12. package/src/advisors/edge/handler.ts +13 -155
  13. package/src/advisors/edge/here.ts +5 -5
  14. package/src/advisors/edge/pages.ts +12 -9
  15. package/src/advisors/edge/shell.ts +6 -5
  16. package/src/advisors/edge/sign-in.ts +101 -36
  17. package/src/advisors/edge/status.ts +19 -6
  18. package/src/advisors/edge/types.ts +36 -60
  19. package/src/advisors/expose.ts +29 -29
  20. package/src/advisors/here.ts +12 -12
  21. package/src/advisors/invite-send.ts +79 -35
  22. package/src/advisors/invite.ts +31 -8
  23. package/src/advisors/job.ts +24 -16
  24. package/src/advisors/login.ts +40 -15
  25. package/src/advisors/owner-store.ts +46 -22
  26. package/src/advisors/photos.ts +3 -3
  27. package/src/advisors/project.ts +27 -25
  28. package/src/advisors/reach.ts +89 -0
  29. package/src/advisors/rights.ts +1 -1
  30. package/src/advisors/routes.ts +55 -74
  31. package/src/advisors/scan.ts +0 -4
  32. package/src/advisors/setup-run.ts +14 -14
  33. package/src/advisors/share-trace.ts +3 -3
  34. package/src/advisors/{door-probe.ts → sign-in-probe.ts} +7 -6
  35. package/src/advisors/speaks.ts +29 -0
  36. package/src/advisors/sync.ts +97 -183
  37. package/src/advisors/tunnel.ts +6 -5
  38. package/src/advisors/users-listen.ts +92 -0
  39. package/src/advisors/users-router.ts +261 -87
  40. package/src/advisors/users-store.ts +81 -0
  41. package/src/agent-time/blocked-scan.ts +181 -0
  42. package/src/agent-time/registry.ts +12 -5
  43. package/src/agent-time/store.ts +9 -109
  44. package/src/asks/ask-bar-fold.ts +2 -1
  45. package/src/asks/ask-close.ts +2 -1
  46. package/src/asks/ask-doc.ts +2 -1
  47. package/src/asks/ask-migrate.ts +3 -2
  48. package/src/asks/ask-steps-fold.ts +2 -1
  49. package/src/asks/ask-store.ts +4 -3
  50. package/src/check.ts +3 -43
  51. package/src/checks/SK001-package-json-shape.check.ts +4 -55
  52. package/src/checks/SK004-gitignore-policy.check.ts +24 -69
  53. package/src/checks/SK013-one-way-in-policy.check.ts +3 -7
  54. package/src/checks/SK017-vscode-hub-task.check.ts +4 -4
  55. package/src/checks/SK019-tests-run-in-units.check.ts +3 -14
  56. package/src/checks/SK020-self-spawning-check.check.ts +5 -7
  57. package/src/checks/SK035-public-clean.check.ts +1 -1
  58. package/src/checks/SK039-vscode-watch-generated.check.ts +1 -1
  59. package/src/checks/SK042-post-kinds.check.ts +5 -14
  60. package/src/checks/SK054-agent-allow-list.check.ts +5 -74
  61. package/src/checks/SK055-retired-config-keys.check.ts +45 -0
  62. package/src/cli/cmd_Advisors.ts +11 -45
  63. package/src/cli/cmd_Asks.ts +3 -10
  64. package/src/cli/cmd_Backup.ts +25 -127
  65. package/src/cli/cmd_BackupTargets.ts +1 -1
  66. package/src/cli/cmd_Capacity.ts +6 -2
  67. package/src/cli/cmd_Checks.ts +0 -14
  68. package/src/cli/cmd_Ci.ts +2 -1
  69. package/src/cli/cmd_Db.ts +3 -82
  70. package/src/cli/cmd_Home.ts +4 -32
  71. package/src/cli/cmd_Hq.ts +0 -17
  72. package/src/cli/cmd_Releases.ts +57 -4
  73. package/src/cli/cmd_Review.ts +333 -354
  74. package/src/cli/cmd_Shot.ts +26 -4
  75. package/src/cli/cmd_SocialDrafts.ts +6 -13
  76. package/src/cli/cmd_ThreadSyncNeeds.ts +6 -2
  77. package/src/cli/cmd_Time.ts +1 -1
  78. package/src/cli/cmd_Trailer.ts +1 -1
  79. package/src/cli/inbox-hook-run.ts +5 -23
  80. package/src/cli/registry-heads.ts +5 -55
  81. package/src/cli/registry.ts +1 -5
  82. package/src/cli/review-here.ts +1 -1
  83. package/src/cli.ts +15 -4
  84. package/src/collections/collection-types.ts +1 -1
  85. package/src/collections/review.ts +5 -4
  86. package/src/core/admission.ts +268 -0
  87. package/src/core/agent-allow-policy.ts +32 -2
  88. package/src/core/agent-env.ts +8 -0
  89. package/src/core/allow-rows.ts +74 -0
  90. package/src/core/check-file-names.ts +19 -106
  91. package/src/core/code-lines.ts +36 -21
  92. package/src/core/footprint.ts +17 -13
  93. package/src/core/identities-root.ts +1 -4
  94. package/src/core/layout.ts +1 -2
  95. package/src/core/machine-db.ts +33 -208
  96. package/src/core/machine-layout.ts +14 -127
  97. package/src/core/machine-read.ts +5 -2
  98. package/src/core/mask-source.ts +60 -0
  99. package/src/core/memory-watch.ts +17 -14
  100. package/src/core/motherhome.ts +8 -35
  101. package/src/core/one-way-in-policy.ts +0 -3
  102. package/src/core/peer-sk.ts +8 -0
  103. package/src/core/repo-walk.ts +0 -9
  104. package/src/core/retention.ts +1 -9
  105. package/src/core/retired-checks.ts +2 -0
  106. package/src/core/tmux-policy.ts +1 -1
  107. package/src/core/tree-watch.ts +2 -2
  108. package/src/core/when.ts +7 -45
  109. package/src/gate/admit-heavy.ts +150 -0
  110. package/src/gate/check-runner.ts +6 -0
  111. package/src/gate/discover-checks.ts +42 -32
  112. package/src/gate/gate-checks.ts +21 -131
  113. package/src/gate/head-gate.ts +1 -1
  114. package/src/gate/job-run.ts +2 -1
  115. package/src/gate/pre-commit-discovery.ts +22 -28
  116. package/src/gate/run-check.ts +3 -4
  117. package/src/gate/run-ci.ts +4 -0
  118. package/src/gate/run-fix.ts +5 -17
  119. package/src/gate/run-fixers.ts +6 -42
  120. package/src/home/app-sign.ts +2 -2
  121. package/src/home/backup-status.ts +52 -92
  122. package/src/home/backup-verdict.ts +2 -2
  123. package/src/home/daemon-jobs.ts +51 -95
  124. package/src/home/database-words.ts +1 -2
  125. package/src/home/databases.ts +9 -25
  126. package/src/home/home-launchd.ts +0 -6
  127. package/src/home/home-paths.ts +8 -4
  128. package/src/home/home-routes.ts +3 -10
  129. package/src/home/home-state.ts +2 -14
  130. package/src/home/inbox-shape.ts +14 -15
  131. package/src/home/inbox.ts +1 -1
  132. package/src/home/machine-repair.ts +102 -103
  133. package/src/home/resume.ts +1 -15
  134. package/src/home/run-daemon.ts +7 -12
  135. package/src/home/space-page.ts +3 -2
  136. package/src/home/supervise.ts +3 -7
  137. package/src/hooks/commit-msg-run.ts +61 -0
  138. package/src/hooks/commit-run.ts +16 -166
  139. package/src/hooks/gate-outcome.ts +108 -0
  140. package/src/hooks/git-hook.ts +9 -9
  141. package/src/hooks/hook-config.ts +8 -8
  142. package/src/hooks/leak-guard.ts +1 -1
  143. package/src/hooks/pre-commit-checks.ts +1 -1
  144. package/src/hooks/run-hooks.ts +2 -6
  145. package/src/hooks/shared-file.ts +3 -2
  146. package/src/hq/daemon-db.ts +8 -8
  147. package/src/hq/door.ts +3 -16
  148. package/src/hq/hq-db.ts +4 -3
  149. package/src/hq/hq-local.ts +1 -2
  150. package/src/hq/hq-store.ts +0 -15
  151. package/src/hq/item-direct.ts +8 -10
  152. package/src/hq/item-fill.ts +37 -0
  153. package/src/hq/kinds/item-gone.ts +7 -10
  154. package/src/hq/kinds/item-msg.ts +12 -18
  155. package/src/hq/kinds/item.ts +13 -19
  156. package/src/hq/kinds/report.ts +3 -4
  157. package/src/hq/owner-switch.ts +3 -3
  158. package/src/hq/report.ts +5 -9
  159. package/src/hq/switch.ts +2 -11
  160. package/src/hq/thread-sync.ts +5 -17
  161. package/src/hq/{shapes-words.ts → threads-words.ts} +2 -12
  162. package/src/http/owner-word.ts +1 -1
  163. package/src/identities/machine.ts +16 -0
  164. package/src/init-repo.ts +0 -1
  165. package/src/ledger/check-stats.ts +6 -5
  166. package/src/ledger/db.ts +2 -4
  167. package/src/ledger/record-kept.ts +117 -48
  168. package/src/ledger/run-log.ts +21 -2
  169. package/src/ledger/slow-tests.ts +96 -0
  170. package/src/ledger/store.ts +3 -86
  171. package/src/ledger/suite-log.ts +8 -2
  172. package/src/media-store/backup/facts.ts +3 -37
  173. package/src/media-store/backup/keys.ts +1 -8
  174. package/src/media-store/backup/manifest.ts +6 -67
  175. package/src/media-store/backup/restore.ts +4 -13
  176. package/src/media-store/backup/retention.ts +13 -1
  177. package/src/media-store/backup/run.ts +6 -267
  178. package/src/media-store/backup/snapshot.ts +2 -38
  179. package/src/media-store/backup/sources.ts +3 -113
  180. package/src/media-store/backup/target-send.ts +5 -29
  181. package/src/media-store/db.ts +8 -7
  182. package/src/media-store/forget-one.ts +1 -1
  183. package/src/media-store/forget.ts +1 -80
  184. package/src/orchestrator/guards.ts +0 -1
  185. package/src/orchestrator/presence.ts +2 -2
  186. package/src/orchestrator/routes.ts +1 -1
  187. package/src/orchestrator/started.ts +0 -9
  188. package/src/orchestrator/talk-key.ts +3 -4
  189. package/src/orchestrator/unheard.ts +1 -1
  190. package/src/plan/planner.ts +3 -2
  191. package/src/recordings/edit.ts +3 -3
  192. package/src/recordings/marks-draw.ts +17 -6
  193. package/src/recordings/marks.ts +120 -9
  194. package/src/reflections/reflections-queue.ts +3 -10
  195. package/src/release/notes.ts +1 -1
  196. package/src/release/public-clean.ts +66 -6
  197. package/src/release/run-bump.ts +11 -0
  198. package/src/release/run-release.ts +4 -0
  199. package/src/releases/from-thread.ts +3 -3
  200. package/src/releases/model.ts +186 -36
  201. package/src/releases/store.ts +13 -3
  202. package/src/releases/validate.ts +83 -0
  203. package/src/repo-config.ts +36 -64
  204. package/src/review/answer-kinds.ts +63 -4
  205. package/src/review/blocked-guard.ts +11 -0
  206. package/src/review/blocked-object.ts +298 -0
  207. package/src/review/cells.ts +144 -230
  208. package/src/review/close.ts +39 -1
  209. package/src/review/doc-save.ts +3 -2
  210. package/src/review/draft-item.ts +1 -1
  211. package/src/review/events.ts +3 -7
  212. package/src/review/expect.ts +23 -39
  213. package/src/review/format.ts +79 -46
  214. package/src/review/glyphs.ts +1 -0
  215. package/src/review/hand-over.ts +3 -3
  216. package/src/review/heard.ts +1 -1
  217. package/src/review/holds-sync.ts +2 -1
  218. package/src/review/inbox-hook.ts +2 -2
  219. package/src/review/inbox-read.ts +39 -33
  220. package/src/review/instruction-guards.ts +12 -0
  221. package/src/review/instructions.ts +0 -1
  222. package/src/review/item-db.ts +13 -43
  223. package/src/review/item-hq.ts +2 -2
  224. package/src/review/item-rows.ts +3 -14
  225. package/src/review/kind-catalog.ts +3 -1
  226. package/src/review/kinds.ts +18 -8
  227. package/src/review/live-view.ts +3 -0
  228. package/src/review/media-kind.ts +1 -1
  229. package/src/review/mentions.ts +1 -2
  230. package/src/review/model.ts +158 -114
  231. package/src/review/move.ts +149 -0
  232. package/src/review/need-threads.ts +3 -2
  233. package/src/review/object-card.ts +11 -0
  234. package/src/review/object-read.ts +6 -1
  235. package/src/review/one-block.ts +1 -1
  236. package/src/review/owner-read.ts +1 -1
  237. package/src/review/phone-push.ts +10 -9
  238. package/src/review/previews.ts +32 -4
  239. package/src/review/push.ts +2 -2
  240. package/src/review/recap.ts +129 -0
  241. package/src/review/referring.ts +6 -3
  242. package/src/review/reflection-object.ts +4 -3
  243. package/src/review/routes.ts +51 -47
  244. package/src/review/secret-route.ts +3 -2
  245. package/src/review/settle.ts +0 -6
  246. package/src/review/snooze.ts +5 -3
  247. package/src/review/speaker.ts +68 -0
  248. package/src/review/start-title.ts +19 -0
  249. package/src/review/store-parties.ts +28 -0
  250. package/src/review/store.ts +94 -59
  251. package/src/review/{wakes.ts → thread-events.ts} +92 -7
  252. package/src/review/thread-md.ts +35 -14
  253. package/src/review/thread-state.ts +804 -0
  254. package/src/review/threads.ts +29 -347
  255. package/src/review/traces.ts +104 -7
  256. package/src/review/trailer-item.ts +1 -1
  257. package/src/review/unit.ts +7 -9
  258. package/src/review/verdict-items.ts +12 -10
  259. package/src/review/view-layout.ts +25 -1
  260. package/src/review/watch-feed.ts +1 -2
  261. package/src/review/working-guards.ts +2 -3
  262. package/src/rules/untrack-generated.ts +1 -15
  263. package/src/secrets/copy.ts +4 -4
  264. package/src/secrets/lapse.ts +2 -1
  265. package/src/serve/hub-app/advisor-app.tsx +4 -4
  266. package/src/serve/hub-app/advisor-face.tsx +9 -3
  267. package/src/serve/hub-app/advisor-host.ts +27 -27
  268. package/src/serve/hub-app/advisors-model.ts +17 -8
  269. package/src/serve/hub-app/advisors-rights.tsx +1 -1
  270. package/src/serve/hub-app/advisors-st.ts +15 -14
  271. package/src/serve/hub-app/advisors-view.tsx +13 -11
  272. package/src/serve/hub-app/app-bridge.ts +23 -3
  273. package/src/serve/hub-app/asks-page.tsx +1 -1
  274. package/src/serve/hub-app/auto-text.tsx +71 -16
  275. package/src/serve/hub-app/check-view.tsx +0 -8
  276. package/src/serve/hub-app/controls.css +14 -3
  277. package/src/serve/hub-app/database-view.tsx +1 -2
  278. package/src/serve/hub-app/dock-st.ts +1 -1
  279. package/src/serve/hub-app/git-view.tsx +3 -1
  280. package/src/serve/hub-app/hub.css +12 -5
  281. package/src/serve/hub-app/icons.tsx +1 -1
  282. package/src/serve/hub-app/inbox-view.tsx +1 -2
  283. package/src/serve/hub-app/live-sources.ts +2 -2
  284. package/src/serve/hub-app/main-panel.tsx +2 -1
  285. package/src/serve/hub-app/panel-repo.ts +0 -9
  286. package/src/serve/hub-app/pic.tsx +29 -12
  287. package/src/serve/hub-app/polled.ts +16 -2
  288. package/src/serve/hub-app/recordings-st.ts +23 -2
  289. package/src/serve/hub-app/recordings-view.tsx +68 -10
  290. package/src/serve/hub-app/ref-pill.ts +1 -1
  291. package/src/serve/hub-app/repo-st.ts +1 -2
  292. package/src/serve/hub-app/review/advisor-add.tsx +1 -1
  293. package/src/serve/hub-app/review/advisor-invite.tsx +1 -1
  294. package/src/serve/hub-app/review/draft-body.tsx +2 -2
  295. package/src/serve/hub-app/review/heard-line.tsx +1 -1
  296. package/src/serve/hub-app/review/instructions-view.tsx +1 -8
  297. package/src/serve/hub-app/review/kind-states.tsx +14 -9
  298. package/src/serve/hub-app/review/kit.tsx +4 -11
  299. package/src/serve/hub-app/review/lane-bar.tsx +3 -3
  300. package/src/serve/hub-app/review/lightbox.tsx +15 -11
  301. package/src/serve/hub-app/review/line-window.ts +4 -1
  302. package/src/serve/hub-app/review/live-bar-st.ts +2 -2
  303. package/src/serve/hub-app/review/live-view.tsx +57 -1
  304. package/src/serve/hub-app/review/object-panel.tsx +20 -8
  305. package/src/serve/hub-app/review/question-views.tsx +191 -53
  306. package/src/serve/hub-app/review/recap-bar.tsx +40 -0
  307. package/src/serve/hub-app/review/request-cell.tsx +48 -0
  308. package/src/serve/hub-app/review/review-cells.tsx +154 -96
  309. package/src/serve/hub-app/review/review-host.ts +8 -4
  310. package/src/serve/hub-app/review/review-kit.ts +17 -11
  311. package/src/serve/hub-app/review/review-list.tsx +30 -35
  312. package/src/serve/hub-app/review/review-st.ts +32 -42
  313. package/src/serve/hub-app/review/review-thread.tsx +139 -85
  314. package/src/serve/hub-app/review/review-views.tsx +127 -68
  315. package/src/serve/hub-app/review/share-lines.tsx +4 -4
  316. package/src/serve/hub-app/review/start-st.ts +2 -5
  317. package/src/serve/hub-app/review/superseded-runs.ts +4 -3
  318. package/src/serve/hub-app/review/thread-close.tsx +10 -7
  319. package/src/serve/hub-app/review/thread-st.ts +381 -202
  320. package/src/serve/hub-app/review/tone-bar.tsx +129 -0
  321. package/src/serve/hub-app/review/tones.ts +53 -0
  322. package/src/serve/hub-app/review/trailer-body.tsx +2 -2
  323. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  324. package/src/serve/hub-app/review/trailer-voices-st.ts +3 -2
  325. package/src/serve/hub-app/review.css +189 -106
  326. package/src/serve/hub-app/search-view.tsx +1 -1
  327. package/src/serve/hub-app/social/social-model.ts +0 -4
  328. package/src/serve/hub-app/source-acts.ts +2 -1
  329. package/src/serve/hub-app/stores/stores-page.tsx +2 -2
  330. package/src/serve/hub-app/terminal-sources.tsx +2 -1
  331. package/src/serve/hub-app/thread-row.tsx +3 -4
  332. package/src/serve/hub-app/tree-build.ts +0 -4
  333. package/src/serve/hub-app/urls-view.tsx +2 -1
  334. package/src/serve/hub-app/view-layout.css +13 -3
  335. package/src/serve/hub-app/wikis-view.tsx +5 -2
  336. package/src/serve/hub-runtime.ts +7 -37
  337. package/src/serve/project-gutter-route.ts +6 -2
  338. package/src/serve/read-thread.ts +20 -2
  339. package/src/serve/read-worker.ts +9 -1
  340. package/src/serve/record-pages.ts +46 -0
  341. package/src/serve/serve-hub.ts +2 -2
  342. package/src/serve/terminal-host.ts +1 -1
  343. package/src/serve/terminal-route.ts +1 -3
  344. package/src/serve/tracked-watch.ts +1 -3
  345. package/src/setup-house.ts +2 -2
  346. package/src/shipkit-files.ts +1 -1
  347. package/src/shipkit.ts +1 -6
  348. package/src/shot/client.ts +2 -1
  349. package/src/shot/film-box.ts +0 -20
  350. package/src/shot/on-place.ts +141 -0
  351. package/src/social/drafts.ts +1 -1
  352. package/src/social/kinds.ts +6 -29
  353. package/src/social/load.ts +2 -2
  354. package/src/social/post-object.ts +3 -2
  355. package/src/social/release-stage.ts +1 -1
  356. package/src/social/stage.ts +2 -2
  357. package/src/stores/model.ts +4 -0
  358. package/src/stores/routes.ts +11 -3
  359. package/src/suite/judge-suites.ts +58 -0
  360. package/src/suite/red-alone.ts +54 -18
  361. package/src/suite/runner-shapes.ts +2 -2
  362. package/src/suite/suite-cli.ts +67 -14
  363. package/src/suite/test-units.ts +2 -1
  364. package/src/urls/fill.ts +1 -1
  365. package/src/urls/places.ts +1 -2
  366. package/src/vault/vault-config.ts +2 -2
  367. package/src/vault/vault-init.ts +1 -5
  368. package/src/wiki/graph-page.ts +14 -2
  369. package/src/advisors/copy-truth.ts +0 -49
  370. package/src/advisors/door-child.ts +0 -112
  371. package/src/advisors/door-serve.ts +0 -52
  372. package/src/advisors/door.ts +0 -118
  373. package/src/checks/SK016-legacy-check-shapes.check.ts +0 -189
  374. package/src/checks/SK029-explicit-check-files.check.ts +0 -112
  375. package/src/checks/SK048-one-local-file.check.ts +0 -36
  376. package/src/core/config-rewrite.ts +0 -111
  377. package/src/core/daemon-port.ts +0 -10
  378. package/src/core/legacy-shapes.ts +0 -263
  379. package/src/core/migrate-layout.ts +0 -638
  380. package/src/core/port-check-cli.ts +0 -52
  381. package/src/core/port-check-file.ts +0 -295
  382. package/src/core/port-check-files.ts +0 -31
  383. package/src/gate/discover-legacy-checks.ts +0 -26
  384. package/src/home/home-move.ts +0 -527
  385. package/src/home/machine-fold.ts +0 -810
  386. package/src/hq/item-shapes.ts +0 -54
  387. package/src/hq/kinds/items-read.ts +0 -4
  388. package/src/media-store/backup/daemon.ts +0 -220
  389. package/src/media-store/backup/kept.ts +0 -241
  390. package/src/media-store/backup/prune.ts +0 -359
  391. package/src/media-store/backup/secret.ts +0 -88
  392. package/src/media-store/backup/ssh-space.ts +0 -202
  393. package/src/media-store/backup/watch.ts +0 -117
  394. package/src/review/band.ts +0 -182
  395. package/src/review/folders.ts +0 -216
  396. package/src/review/hook-ask.ts +0 -58
  397. package/src/review/role.ts +0 -48
  398. package/src/review/thread-fold.ts +0 -64
  399. package/src/review/wait.ts +0 -91
  400. package/src/rules/rule.ts +0 -43
  401. package/src/serve/hook-thread.ts +0 -37
  402. package/src/serve/hook-work.ts +0 -92
  403. package/src/serve/hook-worker.ts +0 -57
  404. package/src/serve/hub-app/review/dock.tsx +0 -147
  405. package/src/serve/hub-app/review/faces.tsx +0 -18
  406. package/src/serve/hub-app/review/item-verdict.tsx +0 -112
  407. package/src/serve/hub-app/review/review-board.tsx +0 -48
  408. /package/src/{scaffold → core}/jsonc-spans.ts +0 -0
@@ -0,0 +1,92 @@
1
+ // the users' port, opened by the daemon itself (wiki tools/shipkit/advisors.md, Who calls): on 127.0.0.1 alone, which
2
+ // the tunnel reaches, while this machine carries the hq and the advisors page is set up; looked at every 30 s, opened
3
+ // again with a new name. The one server besides the house's loopback one (RV040 allows this file). The one constraint
4
+ // a reader breaks first: its router is users-router.ts, which reaches no route of the hub, no owner word, no vault
5
+ import { DirBucket } from './dir-bucket.ts'
6
+ import { factsOf, type PageFacts } from './edge/pages.ts'
7
+ import { limits, type PasswordHasher } from './edge/sign-in.ts'
8
+ import { FILE_MAX } from './edge/types.ts'
9
+ import { housePageFacts } from './speaks.ts'
10
+ import { ownerNameOf } from './owner-name.ts'
11
+ import { advisorsDir, readState } from './owner-store.ts'
12
+ import { privateWords } from './sync.ts'
13
+ import { usersRouter } from './users-router.ts'
14
+ import { usersDir, usersPort } from './users-store.ts'
15
+
16
+ /** a password as the port keeps it: argon2id */
17
+ export const ARGON: PasswordHasher = { hash: (p) => Bun.password.hash(p, { algorithm: 'argon2id' }), verify: (p, h) => Bun.password.verify(p, h) }
18
+
19
+ const EVERY_MS = 30_000
20
+
21
+ /** the users' port on 127.0.0.1 with its router. No shared port: another program of this Mac may not bind beside it
22
+ * and take its requests */
23
+ export function usersServe(o: { port: number; fetch: (req: Request) => Promise<Response>; tls?: { cert: string; key: string } }): Bun.Server<undefined> {
24
+ // no body past the largest file a person may send, whatever the route: a stranger's 100 MB is refused by the server
25
+ return Bun.serve({ hostname: '127.0.0.1', port: o.port, maxRequestBodySize: FILE_MAX + 64 * 1024, ...(o.tls ? { tls: o.tls } : {}), fetch: o.fetch, error: () => new Response('error', { status: 500 }) })
26
+ }
27
+
28
+ export interface ListenerDeps {
29
+ carries?: () => boolean
30
+ host?: () => string | null
31
+ /** the name the public pages print: the owner's default (owner-name.ts) */
32
+ owner?: () => string
33
+ /** the port opened over the owner's advisors folder; tests pass their own */
34
+ listen?: (host: string, pages: PageFacts) => Promise<{ stop: () => void }>
35
+ }
36
+
37
+ /** the port over the owner's advisors folder, the owner's private words read again each minute */
38
+ async function listenHere(house: string, host: string, pages: PageFacts): Promise<{ stop: () => void }> {
39
+ const users = new DirBucket(usersDir())
40
+ let words: { at: number; list: string[] } = { at: 0, list: [] }
41
+ const wordsNow = (): string[] => (Date.now() - words.at < 60_000 ? words.list : (words = { at: Date.now(), list: privateWords(house) }).list)
42
+ const s = usersServe({ port: usersPort(), fetch: usersRouter({ bucket: users, host, pages, limits: limits(), password: ARGON, dir: advisorsDir(), words: wordsNow }) })
43
+ return { stop: () => void s.stop(true) }
44
+ }
45
+
46
+ /** the port kept open while this machine carries the hq and the page is set up, opened again on a new name */
47
+ export function usersListener(o: { house: string; print: (l: string) => void; printErr: (l: string) => void; everyMs?: number } & ListenerDeps): { stop: () => void; tick: () => Promise<void> } {
48
+ const host = o.host ?? (() => readState(advisorsDir()).host)
49
+ const owner = o.owner ?? (() => ownerNameOf(readState(advisorsDir())))
50
+ const listen = o.listen ?? ((h: string, pages: PageFacts) => listenHere(o.house, h, pages))
51
+ let here: { host: string; owner: string; stop: () => void } | null = null
52
+ let stopped = false
53
+ const look = async (): Promise<void> => {
54
+ let want: string | null = null
55
+ let name = 'the owner'
56
+ try {
57
+ const carries = o.carries ?? (await import('../hq/hq-role.ts')).carriesHq
58
+ want = carries() ? host() : null
59
+ name = owner()
60
+ } catch (e) {
61
+ o.printErr(`WARN advisors page: ${(e as Error).message}`)
62
+ }
63
+ // a new name for the public pages: the port opens again
64
+ if (here !== null && (here.host !== want || here.owner !== name)) {
65
+ here.stop()
66
+ here = null
67
+ }
68
+ if (want === null || here !== null) return
69
+ const pages = (await housePageFacts(o.house).catch(() => null))?.facts ?? factsOf(undefined, undefined)
70
+ if (stopped) return
71
+ try {
72
+ here = { host: want, owner: name, ...(await listen(want, pages)) }
73
+ o.print(`advisors page: serving ${want} from this daemon`)
74
+ } catch (e) {
75
+ o.printErr(`WARN advisors page: the users' port did not open here: ${(e as Error).message}`)
76
+ }
77
+ }
78
+ // one look at a time: a tick while one runs waits for that one
79
+ let running: Promise<void> | null = null
80
+ const tick = (): Promise<void> => (running ??= look().finally(() => (running = null)))
81
+ void tick()
82
+ const timer = setInterval(() => void tick(), o.everyMs ?? EVERY_MS)
83
+ return {
84
+ tick,
85
+ stop: () => {
86
+ stopped = true
87
+ clearInterval(timer)
88
+ here?.stop()
89
+ here = null
90
+ },
91
+ }
92
+ }
@@ -1,74 +1,88 @@
1
1
  // the users' port of the hq server (wiki tools/shipkit/advisors.md, Who calls): an advisor is a user of the one hq
2
2
  // server with a few rights. The tunnel lands on this port alone, so a request here is NOBODY until its session and a
3
- // live grant in his store make it a user; the owner is no caller of this port, whatever the request carries. An exact
4
- // allow list of paths, the rest the one 404 before any session is read. With the switch `advisors-live` on, the list
5
- // of threads, a thread, its pictures, a reply and a read cursor answer from the live thread store (sync.ts prepare:
6
- // the hub's own builders, the output whitelist, the mask); the other paths are the edge handler's, over its folder.
3
+ // live grant in the owner's store make it a user; the owner is no caller of this port, whatever the request carries.
4
+ // An exact allow list of paths, the rest the one 404 before any session is read. Every path answers live: who may sign
5
+ // in from the owner's store, the list, a thread and its pictures from the live thread store (sync.ts prepare: the hub's
6
+ // own builders, the output whitelist, the mask), every write taken at the request (advice.ts landAdvice, landProposal:
7
+ // pending in the owner's store, or direct by the person's rights). A reset asked at `/reset` is parked in the owner's
8
+ // store after the answer left (users-store.ts askedReset), and the daemon's job mails it: the answer is one for every email.
7
9
  // The one constraint a reader breaks first: nothing here imports a route of the hub, an owner gate, the vault or a
8
10
  // terminal (tests/advisors-users-caller.test.ts walks the graph)
9
- import { landAdvice } from './advice.ts'
10
- import { dropStaged, etag, ID_RE, NAME_RE, pageOfRows, readCursor, takeStaged, TOKEN, tokensOf, wordsIn, type CopyRow, type ReadCursor } from './edge/api.ts'
11
- import { getJson, type Bytes } from './edge/bucket.ts'
12
- import { BASE, bytesB64url, csrfOf, CSRF_HEADER, handle, NOT_FOUND, status, type EdgeEnv } from './edge/handler.ts'
13
- import { sameText, sessionOf } from './edge/sign-in.ts'
14
- import { ADVICE_TEXT_MAX, FILES_MAX, KEYS, type SharesFile } from './edge/types.ts'
15
- import { isLive, readState, servedShares, type Share } from './owner-store.ts'
16
- import { prepare, sharpWebp, type Encode, type Prepared } from './sync.ts'
17
-
18
- /** the machine switch: on, the hq daemon serves the users' port itself, its reads and replies live */
19
- export const ADVISORS_LIVE = 'advisors-live'
11
+ import { landAdvice, landProposal } from './advice.ts'
12
+ import { advisorBundle, type AppBundle } from './app.ts'
13
+ import { dropEntry, dropStaged, etag, ID_RE, MSG_RE, NAME_RE, PARTIES, readCursor, SPEC, stageFile, takeStaged, TOKEN, tokensOf, wordsIn, type ReadCursor } from './edge/api.ts'
14
+ import { personPage, personSince, type PersonEntry } from './advisor-view.ts'
15
+ import type { Bytes } from './edge/bucket.ts'
16
+ import { APP_HEADER, BASE, bytesB64url, csrfOf, CSRF_HEADER, NOT_FOUND, status, type EdgeEnv } from './edge/handler.ts'
17
+ import { bytesOf } from './edge/form.ts'
18
+ import { hereBeat } from './edge/here.ts'
19
+ import { pageHtml, PUBLIC_PAGES, factsOf, type PublicPage } from './edge/pages.ts'
20
+ import { APP_CSP, appShell } from './edge/shell.ts'
21
+ import { askReset, limits as newLimits, RESET_PATH, resetPage, sameText, SESSION_COOKIE, sessionOf, sha256, SIGN_IN_CSP, signIn, signInPage, type Said } from './edge/sign-in.ts'
22
+ import { pageResponse, STATUS_CSP } from './edge/status.ts'
23
+ import { ADVICE_TEXT_MAX, FILES_MAX, KEYS, PROPOSAL_TITLE_MAX, SHARE_ID_RE, type AdviceWire, type ProposalWire, type SignInList } from './edge/types.ts'
24
+ import { ownerNameOf } from './owner-name.ts'
25
+ import { isLive, readState, servedShares, startPlacesOf, type OwnerState, type Share } from './owner-store.ts'
26
+ import { photoBytes } from './photos.ts'
27
+ import { maskHits } from './scan.ts'
28
+ import { prepare, projectsOf, sharpWebp, type Encode, type Prepared } from './sync.ts'
29
+ import { askedReset, liveLogins, markSpent, tokenKey } from './users-store.ts'
20
30
 
21
31
  /** who calls the users' port: nobody, or a signed in user with a live grant. There is no owner here */
22
- export type Caller = { kind: 'nobody' } | { kind: 'user'; email: string; login: string; shares: readonly Share[] }
32
+ export type Caller = { kind: 'nobody' } | { kind: 'user'; email: string; login: string; shares: readonly Share[]; places: readonly string[] }
23
33
  export const NOBODY: Caller = { kind: 'nobody' }
24
34
 
25
35
  export interface UsersEnv extends EdgeEnv {
26
- /** his advisors folder: the people, their shares and rights, read on every request */
36
+ /** the owner's advisors folder: the people, their shares and rights, read on every request */
27
37
  dir: string
28
- /** his private words, masked on the way out */
38
+ /** the owner's private words, masked on the way out */
29
39
  words: () => string[]
30
40
  /** a picture as a user gets it: re-encoded, no metadata */
31
41
  encode?: Encode
42
+ /** the page's two files; absent, the bundle built from this source (app.ts) */
43
+ app?: () => Promise<AppBundle>
32
44
  }
33
45
 
34
46
  const ID = '[A-Za-z0-9_-]{22}\\.[0-9a-f]{12}'
35
47
  const NAME = '[0-9a-f]{64}\\.webp'
36
- /** the paths answered live, by method */
37
- const LIVE_GET = [new RegExp(`^/api/review/threads$`), new RegExp(`^/api/review/threads/(${ID})$`), new RegExp(`^/api/review/(${ID})/(?:(?:preview/(?:fit|thumb|tile)|thread)/)?(${NAME})$`)]
38
- const LIVE_POST = new RegExp(`^/api/review/(${ID})/(reply|read)$`)
39
- /** the paths the edge handler answers (sign in, the page, its other writes), exact */
40
- const EDGE_GET = [/^\/health$/, /^\/about$/, /^\/privacy$/, /^\/in$/, /^\/$/, /^\/app\/[0-9a-f]{64}\.(?:js|css)$/, /^\/api\/advisor\/(?:projects|photo)$/, /^\/api\/review\/(?:spec|parties|board)$/]
41
- const EDGE_POST = [/^\/in$/, /^\/api\/advisor\/(?:here|out)$/, /^\/api\/advisor\/(?:start|upload)\/[A-Za-z0-9_-]{22}$/, new RegExp(`^/api/review/(${ID})/(?:feedback|answer|upload)$`)]
48
+ const PLACE = '[A-Za-z0-9_-]{22}'
49
+ /** every path of the port, by method: the rest is the one 404 */
50
+ const GETS = [/^\/health$/, /^\/about$/, /^\/privacy$/, /^\/in$/, /^\/reset$/, /^\/$/, /^\/app\/[0-9a-f]{64}\.(?:js|css)$/, /^\/api\/advisor\/(?:projects|photo)$/, /^\/api\/review\/(?:spec|parties|threads)$/, new RegExp(`^/api/review/threads/(${ID})$`), new RegExp(`^/api/review/(${ID})/(?:(?:preview/(?:fit|thumb|tile)|thread)/)?(${NAME})$`)]
51
+ const POSTS = [/^\/in$/, /^\/reset$/, /^\/api\/advisor\/(?:here|out)$/, new RegExp(`^/api/advisor/(?:start|upload)/${PLACE}$`), new RegExp(`^/api/review/(${ID})/(?:reply|read|feedback|answer|upload)$`)]
42
52
 
43
- /** where a path goes: live, the edge handler, or nowhere (the 404) */
44
- export function allowed(method: string, path: string): 'live' | 'edge' | null {
53
+ /** whether a path is one of the port's, by method */
54
+ export function allowed(method: string, path: string): boolean {
45
55
  const m = method.toUpperCase()
46
- if (m === 'GET' || m === 'HEAD') return LIVE_GET.some((r) => r.test(path)) ? 'live' : EDGE_GET.some((r) => r.test(path)) ? 'edge' : null
47
- if (m === 'POST') return LIVE_POST.test(path) ? 'live' : EDGE_POST.some((r) => r.test(path)) ? 'edge' : null
48
- return null
56
+ if (m === 'GET' || m === 'HEAD') return GETS.some((r) => r.test(path))
57
+ if (m === 'POST') return POSTS.some((r) => r.test(path))
58
+ return false
49
59
  }
50
60
 
51
- /** the caller of a request: its session, then a live grant of that email in his store now; anything else is nobody */
61
+ /** the list who may sign in reads, from the owner's store now (users-store.ts) */
62
+ const loginsFile = (s: OwnerState, now: Date): SignInList => liveLogins(s, now)
63
+
64
+ /** the caller of a request: its session, then a live grant of that email in the owner's store now; anything else is nobody */
52
65
  export async function callerOf(req: Request, env: UsersEnv): Promise<Caller> {
53
- const now = (env.now ?? Date.now)()
54
- const file = await getJson<SharesFile>(env.bucket, KEYS.shares)
55
- const who = await sessionOf(req, { bucket: env.bucket, file, now })
56
- if (who === null) return NOBODY
66
+ const ms = (env.now ?? Date.now)()
67
+ const now = new Date(ms)
57
68
  const s = readState(env.dir)
69
+ const who = await sessionOf(req, { bucket: env.bucket, logins: loginsFile(s, now), now: ms })
70
+ if (who === null) return NOBODY
58
71
  const ids = new Set(s.advisors.filter((a) => a.email === who.email).map((a) => a.id))
59
- const shares = servedShares(s, new Date(now)).filter((x) => ids.has(x.advisor))
60
- const access = s.access.some((x) => ids.has(x.advisor) && isLive(x, new Date(now)))
61
- return shares.length === 0 && !access ? NOBODY : { kind: 'user', email: who.email, login: who.login, shares }
72
+ const shares = servedShares(s, now).filter((x) => ids.has(x.advisor))
73
+ const places = startPlacesOf(s, now).filter((x) => ids.has(x.advisor)).map((x) => x.id)
74
+ const access = s.access.some((x) => ids.has(x.advisor) && isLive(x, now))
75
+ return shares.length === 0 && !access && places.length === 0 ? NOBODY : { kind: 'user', email: who.email, login: who.login, shares, places }
62
76
  }
63
77
 
64
78
  /** the users' port: its own name, the allow list, then the caller */
65
79
  export function usersRouter(env: UsersEnv): (req: Request) => Promise<Response> {
80
+ const e = { ...env, limits: env.limits ?? newLimits() }
66
81
  return async (req) => {
67
- if (env.host === null || (req.headers.get('host') ?? new URL(req.url).host).toLowerCase() !== env.host) return NOT_FOUND()
68
- const where = allowed(req.method, new URL(req.url).pathname)
69
- if (where === null) return NOT_FOUND()
70
- if (where === 'edge') return handle(req, env)
71
- return liveAnswer(req, await callerOf(req, env), env)
82
+ if (e.host === null || (req.headers.get('host') ?? new URL(req.url).host).toLowerCase() !== e.host) return NOT_FOUND()
83
+ const path = new URL(req.url).pathname
84
+ if (!allowed(req.method, path)) return NOT_FOUND()
85
+ return answer(req, path, e)
72
86
  }
73
87
  }
74
88
 
@@ -78,36 +92,173 @@ const PICTURES_MAX = 200
78
92
 
79
93
  /** one share as its user reads it now, null when it shows nothing */
80
94
  async function liveOf(x: Share, env: UsersEnv, now: Date): Promise<Prepared | null> {
81
- const p = await prepare(readState(env.dir), x, { words: env.words(), encode: env.encode ?? sharpWebp, now, names: 'raw' })
82
- if (p?.copy != null && p.copy.faults.length > 0) {
83
- console.error(`WARN users' port: share ${x.id} refused ${p.copy.faults.length} values: ${p.copy.faults.slice(0, 3).join('; ')}`)
95
+ const p = await prepare(readState(env.dir), x, { words: env.words(), now })
96
+ if (p?.theirs != null && p.theirs.faults.length > 0) {
97
+ console.error(`WARN users' port: share ${x.id} refused ${p.theirs.faults.length} values: ${p.theirs.faults.slice(0, 3).join('; ')}`)
84
98
  return null
85
99
  }
86
- return p?.copy == null || p.manifest === null ? null : p
100
+ return p?.theirs == null || p.manifest === null ? null : p
101
+ }
102
+
103
+ /** the sign in form's cap (edge/sign-in.ts reads the same) */
104
+ const SIGN_IN_MAX = 4096
105
+
106
+ /** a JSON object body of at most 16 KB, read under that cap, null for anything else */
107
+ async function bodyOf(req: Request): Promise<Record<string, unknown> | null> {
108
+ const bytes = await bytesOf(req, 16 * 1024)
109
+ const raw = bytes === null ? '' : new TextDecoder().decode(bytes)
110
+ try {
111
+ const v = bytes !== null ? (JSON.parse(raw) as unknown) : null
112
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null
113
+ } catch {
114
+ return null
115
+ }
116
+ }
117
+
118
+ /** the owner's name as the person reads it: the names their own grants give, the one they agree on, else the owner's
119
+ * default; masked */
120
+ function ownerFor(s: OwnerState, words: string[], names: readonly string[]): string {
121
+ const fallback = ownerNameOf(s)
122
+ const one = new Set(names).size === 1 ? names[0]! : fallback
123
+ return maskHits(one, { advisorEmail: '', words }).length === 0 ? one : 'the owner'
124
+ }
125
+
126
+ /** the paths before any session: health, the public pages, the sign in; the rest is liveAnswer's */
127
+ async function answer(req: Request, path: string, env: UsersEnv & { limits: NonNullable<EdgeEnv['limits']> }): Promise<Response> {
128
+ const ms = (env.now ?? Date.now)()
129
+ const now = new Date(ms)
130
+ const read = req.method.toUpperCase() === 'GET' || req.method.toUpperCase() === 'HEAD'
131
+ if (path === '/health') return new Response('ok', { headers: { ...BASE, 'content-type': 'text/plain' } })
132
+ // fixed words, before any session and before any read of the owner's store
133
+ const page = PUBLIC_PAGES.find((x) => x === path)
134
+ if (page !== undefined) return pageResponse(pageHtml(page as PublicPage, env.pages ?? factsOf(undefined, undefined)), { csp: STATUS_CSP, headers: BASE })
135
+ if (path === RESET_PATH) {
136
+ const page = (code: number, p: Parameters<typeof resetPage>[0]): Response => pageResponse(resetPage(p), { status: code, csp: SIGN_IN_CSP, headers: BASE })
137
+ if (read) return page(200, { sent: false })
138
+ if (req.headers.get('origin') !== `https://${env.host}`) return status(403, 'Forbidden', 'This was not sent from the reset page.')
139
+ const asked = await askReset(req, { limits: env.limits, now: ms })
140
+ if (asked === null) return page(429, { sent: false, said: `Too many tries: a code may already be in your inbox. Else wait an hour, or ask ${ownerFor(readState(env.dir), env.words(), [])} for a new code.` })
141
+ // the owner's store is read and written after the answer left, whatever the email: the answer and its time are
142
+ // the same for all. The daemon's advisors job mails the code (invite-send.ts sendResets)
143
+ if (asked.email !== '')
144
+ setTimeout(() => {
145
+ try {
146
+ askedReset(env.dir, asked.email, now)
147
+ } catch (e) {
148
+ console.error(`WARN users' port: a reset was not kept: ${(e as Error).message}`)
149
+ }
150
+ }, 0)
151
+ return page(200, { sent: true })
152
+ }
153
+ if (path === '/in') {
154
+ const s = readState(env.dir)
155
+ const words = env.words()
156
+ const owner = ownerFor(s, words, [])
157
+ // its referrer policy is the page's own (sign-in.ts): the origin check below meets what its form really sends
158
+ const form = (code: number, said?: Said): Response => pageResponse(signInPage(owner, said), { status: code, csp: SIGN_IN_CSP, headers: BASE })
159
+ if (read) return form(200)
160
+ if (req.headers.get('origin') !== `https://${env.host}`) return status(403, 'Forbidden', 'This was not sent from the sign in page.')
161
+ // the form read once, under the sign in's own cap: a body past it signs nobody in
162
+ const body = await bytesOf(req, SIGN_IN_MAX)
163
+ const sent = new Request(req.url, { method: 'POST', headers: req.headers, body: body ?? new Uint8Array(0) })
164
+ const r = await signIn(sent, { bucket: env.bucket, logins: loginsFile(s, now), now: ms, limits: env.limits, password: env.password })
165
+ if (!r.ok) return form(r.status, r.said)
166
+ // a code that set a password is spent, a reset's the login now: the owner's store says so
167
+ const f = new URLSearchParams(new TextDecoder().decode(body ?? new Uint8Array(0)))
168
+ if ((f.get('code') ?? '').trim() !== '') await markSpent(env.dir, env.bucket, (f.get('email') ?? '').trim().toLowerCase(), now)
169
+ return new Response(null, { status: 303, headers: { ...BASE, location: '/', 'set-cookie': r.cookie } })
170
+ }
171
+ return liveAnswer(req, await callerOf(req, env), env)
87
172
  }
88
173
 
89
- /** a live route for a caller: nobody is the 401; a user reaches their own live shares alone */
174
+ /** a path past the sign in, for a caller: nobody is the 303 to `/in` for the page, else the 401; a user reaches their
175
+ * own live shares and start places alone */
90
176
  export async function liveAnswer(req: Request, caller: Caller, env: UsersEnv): Promise<Response> {
91
177
  const ms = (env.now ?? Date.now)()
92
178
  const now = new Date(ms)
93
- const json = async (x: unknown, code = 200): Promise<Response> => {
179
+ const path = new URL(req.url).pathname
180
+ const method = req.method.toUpperCase()
181
+ const read = method === 'GET' || method === 'HEAD'
182
+ const json = async (x: unknown, code = 200, headers: Record<string, string> = BASE): Promise<Response> => {
94
183
  const body = JSON.stringify(x)
95
184
  const tag = await etag(body)
96
- if (code === 200 && req.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers: { ...BASE, etag: tag } })
97
- return new Response(body, { status: code, headers: { ...BASE, 'content-type': 'application/json', ...(code === 200 ? { etag: tag } : {}) } })
185
+ if (code === 200 && req.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers: { ...headers, etag: tag } })
186
+ return new Response(body, { status: code, headers: { ...headers, 'content-type': 'application/json', ...(code === 200 ? { etag: tag } : {}) } })
98
187
  }
99
188
  const no = (code: number, error: string): Response => new Response(JSON.stringify({ error }), { status: code, headers: { ...BASE, 'content-type': 'application/json' } })
100
- if (caller.kind !== 'user') return status(401, 'Not signed in', 'Sign in again at /in, or ask for a new code.')
101
- const url = new URL(req.url)
102
- const path = url.pathname
103
- const read = req.method.toUpperCase() === 'GET' || req.method.toUpperCase() === 'HEAD'
189
+ if (caller.kind !== 'user') return path === '/' ? new Response(null, { status: 303, headers: { ...BASE, location: '/in' } }) : status(401, 'Not signed in', 'Sign in again at /in, or ask for a new code.')
190
+ const s = readState(env.dir)
191
+ const words = env.words()
192
+ const key = await tokenKey(env.bucket)
104
193
  if (!read) {
105
194
  // a write comes from the page itself: its own origin, and the token its shell carries for this session
106
195
  if (req.headers.get('origin') !== `https://${env.host}`) return status(403, 'Forbidden', 'This was not sent from the advisors page.')
107
- const key = await env.bucket.get(KEYS.csrf)
108
- if (key === null) return status(503, 'Not open', 'Nothing is taken right now.')
109
196
  if (!sameText(req.headers.get(CSRF_HEADER) ?? '', await csrfOf(key, 'app', caller))) return status(403, 'Forbidden', 'This page is out of date: open it again.')
110
197
  }
198
+ const me = s.advisors.find((a) => a.email === caller.email)
199
+ const app = await (env.app ?? advisorBundle)()
200
+ if (path === '/') {
201
+ const owners: string[] = []
202
+ for (const x of caller.shares) {
203
+ const p = await liveOf(x, env, now)
204
+ if (p !== null) owners.push(p.owner)
205
+ }
206
+ const photo = me?.photo?.seen === true ? me.photo.sha : undefined
207
+ return pageResponse(appShell({ app: '/app', js: app.js.sha, css: app.css.sha, base: '', csrf: await csrfOf(key, 'app', caller), name: 'shared with you', owner: ownerFor(s, words, owners), ...(me !== undefined ? { me: me.name } : {}), ...(photo !== undefined ? { photo: photo.slice(0, 12) } : {}) }), { csp: APP_CSP, headers: BASE })
208
+ }
209
+ const file = /^\/app\/([0-9a-f]{64})\.(js|css)$/.exec(path)
210
+ if (file !== null) {
211
+ const f = file[2] === 'js' ? app.js : app.css
212
+ if (f.sha !== file[1]) return NOT_FOUND()
213
+ return new Response(f.bytes, { headers: { ...BASE, 'cache-control': 'private, max-age=31536000, immutable', 'content-type': file[2] === 'js' ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8' } })
214
+ }
215
+ // the bundle the shell names now: a page still open on an older one says « reload » (advisor-host.ts advisorFetch)
216
+ const api = { ...BASE, [APP_HEADER]: app.js.sha }
217
+ if (path === '/api/advisor/photo') {
218
+ const bytes = me?.photo?.seen === true ? photoBytes(env.dir, 'advisors', me.id, 64) : null
219
+ return bytes === null ? no(404, 'no photo') : new Response(bytes, { headers: { ...BASE, 'cache-control': 'private, max-age=86400', 'content-type': 'image/webp' } })
220
+ }
221
+ if (path === '/api/advisor/projects') {
222
+ const projects = await projectsOf(s, words, now)
223
+ return json(caller.places.flatMap((id) => (projects[id] ? [{ id, project: projects[id]!.project }] : [])), 200, api)
224
+ }
225
+ if (path === '/api/advisor/here') {
226
+ // the thread their page has open: one of their own live shares or none; the answer says nothing of anyone
227
+ const r = await hereBeat(await req.text(), { bucket: env.bucket, email: caller.email, mine: caller.shares.map((x) => x.id), now: ms })
228
+ return 'ok' in r ? json({ ok: true }) : no(r.status, r.error)
229
+ }
230
+ if (path === '/api/advisor/out') {
231
+ // this session ends here and now: its file gone, the cookie cleared; their other sessions stay
232
+ await env.bucket.delete(KEYS.session(await sha256(caller.email), caller.login))
233
+ return new Response(JSON.stringify({ ok: true }), { headers: { ...BASE, 'content-type': 'application/json', 'set-cookie': `${SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax` } })
234
+ }
235
+ const rand = (): string => (env.rand ?? (() => bytesB64url(crypto.getRandomValues(new Uint8Array(9)))))()
236
+ const start = /^\/api\/advisor\/(start|upload)\/([^/]+)$/.exec(path)
237
+ if (start !== null) {
238
+ const place = start[2]!
239
+ if (!SHARE_ID_RE.test(place) || !caller.places.includes(place)) return no(404, 'no such project')
240
+ if (start[1] === 'upload') {
241
+ const r = await stageFile(req, 'p', place, { bucket: env.bucket, now: ms, rand })
242
+ return 'token' in r ? json(r) : no(r.status, r.error)
243
+ }
244
+ const b = (await bodyOf(req)) ?? {}
245
+ const title = typeof b['title'] === 'string' ? b['title'].trim() : ''
246
+ const text = typeof b['text'] === 'string' ? b['text'].trim() : ''
247
+ if (title === '' || title.length > PROPOSAL_TITLE_MAX) return no(400, `a title of 1 to ${PROPOSAL_TITLE_MAX} characters`)
248
+ if (text.length > ADVICE_TEXT_MAX) return no(400, `at most ${ADVICE_TEXT_MAX} characters`)
249
+ const given = tokensOf(b['files'])
250
+ if (given.length > FILES_MAX || !given.every((x): x is string => typeof x === 'string' && TOKEN.test(x))) return no(400, `at most ${FILES_MAX} files the page staged`)
251
+ const entry = `${ms}-${rand()}`
252
+ const files = await takeStaged(env.bucket, 'p', place, given, entry)
253
+ if (typeof files === 'string') return no(400, files)
254
+ const wire: ProposalWire = { v: 1, at: now.toISOString(), email: caller.email, title, ...(text !== '' ? { text } : {}), ...(files.length > 0 ? { files } : {}) }
255
+ const r = await landProposal(env.dir, env.bucket, place, wire, entry, now)
256
+ await dropStaged(env.bucket, 'p', place, given)
257
+ if (!('waits' in r)) await dropEntry(env.bucket, 'p', place, entry)
258
+ return 'waits' in r ? json({ ok: true, waits: r.waits }) : no(r.status, r.error)
259
+ }
260
+ if (read && path === '/api/review/spec') return json(SPEC, 200, api)
261
+ if (read && path === '/api/review/parties') return json(PARTIES, 200, api)
111
262
  /** the share an id is in, while it is one of the caller's, and that share as it reads now with the id in it */
112
263
  const shareOf = async (id: string): Promise<{ x: Share; p: Prepared } | null> => {
113
264
  const x = caller.shares.find((y) => y.id === ID_RE.exec(id)?.[1])
@@ -115,72 +266,95 @@ export async function liveAnswer(req: Request, caller: Caller, env: UsersEnv): P
115
266
  return x === undefined || p === null || !p.manifest!.ids.includes(id) ? null : { x, p }
116
267
  }
117
268
  if (read && path === '/api/review/threads') {
118
- const words = (url.searchParams.get('q') ?? '').toLowerCase().split(/\s+/).filter(Boolean)
119
- const rows: CopyRow[] = []
269
+ // the hub's own page over the rows the person may see: its order, search (words, `#code`), filters and counts
270
+ const rows: PersonEntry[] = []
271
+ const read: Parameters<typeof personSince>[0][number][] = []
120
272
  for (const x of caller.shares) {
121
273
  const p = await liveOf(x, env, now)
122
274
  if (p === null) continue
123
- const row = p.copy!.row as unknown as CopyRow
124
- if (words.length > 0) {
125
- const text = wordsIn([row, p.copy!.view]).join('\n')
126
- if (!words.every((w) => text.includes(w))) continue
127
- }
275
+ const row = p.theirs!.row
128
276
  const cursor = await readCursor(env.bucket, x.id)
129
- rows.push({ ...row, unread: cursor === null || row.updated > cursor.upTo })
277
+ rows.push({ row: { ...row, unread: cursor === null || row.updated > cursor.upTo }, text: wordsIn([row, p.theirs!.view]).join('\n') })
278
+ read.push({ row, view: p.theirs!.view })
130
279
  }
131
- return json(pageOfRows(rows, url.searchParams))
280
+ // their last act: a word, a pick, a verdict, a thread they started, as his own line counts his
281
+ const s = readState(env.dir)
282
+ const ids = new Set(caller.shares.map((x) => x.advisor))
283
+ const left = [...s.advice.filter((a) => ids.has(a.advisor)), ...s.proposals.filter((p) => ids.has(p.advisor))].map((a) => a.at).sort().at(-1) ?? null
284
+ return json(personPage(rows, new URL(req.url).searchParams, personSince(read, left)), 200, api)
132
285
  }
133
286
  const one = new RegExp(`^/api/review/threads/(${ID})$`).exec(path)
134
287
  if (read && one !== null) {
135
288
  const at = await shareOf(one[1]!)
136
- return at === null ? no(404, 'no such thread') : json({ ...at.p.copy!.view, asked: one[1]! })
289
+ return at === null ? no(404, 'no such thread') : json({ ...at.p.theirs!.view, asked: one[1]! }, 200, api)
137
290
  }
138
291
  const pic = new RegExp(`^/api/review/(${ID})/(?:(?:preview/(?:fit|thumb|tile)|thread)/)?(${NAME})$`).exec(path)
139
292
  if (read && pic !== null) {
140
293
  const at = await shareOf(pic[1]!)
141
294
  const sha = NAME_RE.exec(pic[2]!)![1]!
142
- const file = at === null || !at.p.manifest!.images.includes(sha) ? undefined : at.p.all.find((y) => y.sha === sha)
143
- if (file === undefined) return no(404, 'no such picture')
295
+ const f = at === null || !at.p.manifest!.images.includes(sha) ? undefined : at.p.all.find((y) => y.sha === sha)
296
+ if (f === undefined) return no(404, 'no such picture')
144
297
  let bytes = pictures.get(sha)
145
298
  if (bytes === undefined) {
146
- bytes = await (env.encode ?? sharpWebp)(file.path)
299
+ bytes = await (env.encode ?? sharpWebp)(f.path)
147
300
  if (pictures.size >= PICTURES_MAX) pictures.delete(pictures.keys().next().value!)
148
301
  pictures.set(sha, bytes)
149
302
  }
150
303
  return new Response(bytes, { headers: { ...BASE, 'cache-control': 'private, max-age=86400', 'content-type': 'image/webp' } })
151
304
  }
152
- const w = LIVE_POST.exec(path)
305
+ const w = new RegExp(`^/api/review/(${ID})/(reply|read|feedback|answer|upload)$`).exec(path)
153
306
  if (read || w === null) return no(404, 'no such route')
154
307
  const at = await shareOf(w[1]!)
155
308
  if (at === null) return no(404, 'no such thread')
156
- const raw = await req.text()
157
- let b: Record<string, unknown> | null = null
158
- try {
159
- const v = raw.length <= 16 * 1024 ? (JSON.parse(raw) as unknown) : null
160
- if (v !== null && typeof v === 'object' && !Array.isArray(v)) b = v as Record<string, unknown>
161
- } catch {
162
- // refused below
309
+ const id = w[1]!
310
+ if (w[2] === 'upload') {
311
+ const r = await stageFile(req, 's', at.x.id, { bucket: env.bucket, now: ms, rand })
312
+ return 'token' in r ? json(r) : no(r.status, r.error)
163
313
  }
314
+ const b = await bodyOf(req)
164
315
  if (b === null) return no(400, 'a body of at most 16 KB, a JSON object')
165
316
  if (w[2] === 'read') {
166
317
  // forward only, a time one of that share's cells holds now, this server's clock beside it
167
318
  const upTo = typeof b['upTo'] === 'string' ? b['upTo'] : ''
168
- if (!at.p.copy!.view.cells.some((c) => c.at === upTo)) return no(400, 'no such moment in this thread')
319
+ if (!at.p.theirs!.view.cells.some((c) => c.at === upTo)) return no(400, 'no such moment in this thread')
169
320
  const was = await readCursor(env.bucket, at.x.id)
170
321
  if (was === null || upTo > was.upTo) await env.bucket.put(KEYS.reads(at.x.id), JSON.stringify({ v: 1, at: now.toISOString(), upTo } satisfies ReadCursor), 'application/json')
171
322
  return json({ ok: true })
172
323
  }
173
- const text = typeof b['text'] === 'string' ? b['text'].trim() : ''
324
+ const text = typeof b['text'] === 'string' ? b['text'].trim() : typeof b['comment'] === 'string' ? b['comment'].trim() : ''
174
325
  if (text.length > ADVICE_TEXT_MAX) return no(400, `at most ${ADVICE_TEXT_MAX} characters`)
175
- const files = tokensOf(b['files'])
176
- if (!files.every((x): x is string => typeof x === 'string' && TOKEN.test(x))) return no(400, 'a file of yours is not one the page staged: add it again')
177
- if (files.length > FILES_MAX) return no(400, `at most ${FILES_MAX} files`)
178
- if (text === '' && files.length === 0) return no(400, 'your words are empty')
179
- const entry = `${ms}-${(env.rand ?? (() => bytesB64url(crypto.getRandomValues(new Uint8Array(9)))))()}`
326
+ let advice: Omit<AdviceWire, 'v' | 'at' | 'email'>
327
+ let given: string[] = []
328
+ const m = at.p.manifest!
329
+ if (w[2] === 'feedback') {
330
+ const judge = m.judge.find((j) => j.item === id)
331
+ if (judge === undefined) return no(409, 'this version does not wait for a verdict, or a newer one does: open it again')
332
+ if (b['status'] === 'approved') advice = { kind: 'approve', item: id, version: judge.version, ...(text !== '' ? { text } : {}) }
333
+ else if (b['status'] === 'approved-with-fix') {
334
+ if (text === '') return no(400, 'say what you would change')
335
+ advice = { kind: 'change', item: id, version: judge.version, text }
336
+ } else return no(403, 'an advisor approves or says what they would change')
337
+ } else if (w[2] === 'answer') {
338
+ const re = typeof b['re'] === 'string' && MSG_RE.test(b['re']) ? b['re'] : ''
339
+ const q = m.questions.find((x) => x.cell === `${id}/${re}`)
340
+ const option = b['option']
341
+ if (q === undefined) return no(409, 'this question is answered or changed: open it again')
342
+ if (typeof option !== 'number' || !Number.isInteger(option) || option < 0 || option >= q.options) return no(400, 'no such option')
343
+ advice = { kind: 'pick', item: id, message: re, option, qhash: q.qhash, ...(text !== '' ? { text } : {}) }
344
+ } else {
345
+ const files = tokensOf(b['files'])
346
+ if (!files.every((x): x is string => typeof x === 'string' && TOKEN.test(x))) return no(400, 'a file of yours is not one the page staged: add it again')
347
+ given = files
348
+ if (given.length > FILES_MAX) return no(400, `at most ${FILES_MAX} files`)
349
+ if (text === '' && given.length === 0) return no(400, 'your words are empty')
350
+ advice = { kind: 'words', ...(text !== '' ? { text } : {}) }
351
+ }
352
+ const entry = `${ms}-${rand()}`
180
353
  // the files first, moved under the entry from where the page staged them; the advice names only files that are there
181
- const metas = await takeStaged(env.bucket, 's', at.x.id, files, entry)
354
+ const metas = await takeStaged(env.bucket, 's', at.x.id, given, entry)
182
355
  if (typeof metas === 'string') return no(400, metas)
183
- const r = await landAdvice(env.dir, env.bucket, at.x.id, { v: 1, at: now.toISOString(), email: caller.email, kind: 'words', ...(text !== '' ? { text } : {}), ...(metas.length > 0 ? { files: metas } : {}) }, entry, now)
184
- await dropStaged(env.bucket, 's', at.x.id, files)
356
+ const r = await landAdvice(env.dir, env.bucket, at.x.id, { v: 1, at: now.toISOString(), email: caller.email, ...advice, ...(metas.length > 0 ? { files: metas } : {}) }, entry, now)
357
+ await dropStaged(env.bucket, 's', at.x.id, given)
358
+ if (!('waits' in r)) await dropEntry(env.bucket, 's', at.x.id, entry)
185
359
  return 'waits' in r ? json({ ok: true, waits: r.waits }) : no(r.status, r.error)
186
360
  }