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