@open-pencil/cloud 0.17.0-beta.4 → 0.17.0-beta.6

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 (280) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/services.mjs +1 -1
  5. package/dist/bin/services.mjs.map +1 -1
  6. package/dist/client.d.ts +783 -47
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +1651 -382
  9. package/dist/client.js.map +1 -1
  10. package/dist/contract.d.ts +2 -2
  11. package/dist/contract.js +2 -2
  12. package/dist/contract2.js +701 -45
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +2138 -34
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +4343 -306
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +61 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +1338 -44
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +45 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +958 -340
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +93 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +18032 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +12615 -5249
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +17367 -8567
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +13587 -7333
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +11601 -5401
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +84 -62
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +31 -5
  42. package/src/admin/api/routes.ts +263 -190
  43. package/src/admin/audit/service.ts +11 -3
  44. package/src/admin/bootstrap.ts +86 -0
  45. package/src/admin/documents/service.ts +195 -10
  46. package/src/admin/email/service.ts +2 -1
  47. package/src/admin/enrollment/email.ts +17 -3
  48. package/src/admin/enrollment/service.ts +71 -10
  49. package/src/admin/errors.ts +5 -0
  50. package/src/admin/index.ts +1 -0
  51. package/src/admin/reports/service.ts +15 -3
  52. package/src/admin/schema.ts +6 -5
  53. package/src/admin/users/service.ts +173 -16
  54. package/src/client/api.ts +52 -473
  55. package/src/client/auth/client.ts +22 -3
  56. package/src/client/comments.ts +205 -0
  57. package/src/client/community.ts +40 -0
  58. package/src/client/device-authorization.ts +4 -20
  59. package/src/client/discovery.ts +39 -11
  60. package/src/client/documents.ts +160 -0
  61. package/src/client/files/archive.ts +60 -0
  62. package/src/client/files/checksum.ts +7 -0
  63. package/src/client/files/download.ts +122 -0
  64. package/src/client/files/images.ts +89 -0
  65. package/src/client/files/index.ts +15 -0
  66. package/src/client/files/objects.ts +173 -0
  67. package/src/client/files/save.ts +79 -0
  68. package/src/client/index.ts +4 -0
  69. package/src/client/portal/account.ts +73 -3
  70. package/src/client/portal/administration.ts +52 -5
  71. package/src/client/portal/request.ts +6 -2
  72. package/src/client/response.ts +21 -0
  73. package/src/client/schema.ts +8 -0
  74. package/src/client/services.ts +23 -18
  75. package/src/client/sharing.ts +262 -0
  76. package/src/client/tour.ts +44 -0
  77. package/src/client/versions.ts +110 -0
  78. package/src/contract/account.ts +111 -11
  79. package/src/contract/admin/index.ts +48 -3
  80. package/src/contract/billing.ts +235 -0
  81. package/src/contract/collaboration.ts +5 -0
  82. package/src/contract/comments.ts +223 -0
  83. package/src/contract/community.ts +60 -0
  84. package/src/contract/discovery.ts +94 -5
  85. package/src/contract/entitlements.ts +10 -0
  86. package/src/contract/index.ts +64 -5
  87. package/src/contract/links.ts +62 -4
  88. package/src/contract/locale.ts +27 -0
  89. package/src/contract/portal.ts +12 -1
  90. package/src/contract/relay.ts +3 -1
  91. package/src/contract/routes.ts +10 -0
  92. package/src/contract/services.ts +62 -20
  93. package/src/contract/workspaces.ts +5 -0
  94. package/src/email/i18n.ts +174 -0
  95. package/src/email/index.ts +13 -2
  96. package/src/email/locales/ar.json +169 -0
  97. package/src/email/locales/de.json +169 -0
  98. package/src/email/locales/es.json +169 -0
  99. package/src/email/locales/fr.json +169 -0
  100. package/src/email/locales/it.json +169 -0
  101. package/src/email/locales/ja.json +169 -0
  102. package/src/email/locales/pl.json +169 -0
  103. package/src/email/locales/pt-br.json +169 -0
  104. package/src/email/locales/ru.json +169 -0
  105. package/src/email/locales/zh-cn.json +169 -0
  106. package/src/email/messages.ts +235 -0
  107. package/src/email/render.ts +160 -276
  108. package/src/email/samples.ts +142 -0
  109. package/src/email/schema.ts +98 -8
  110. package/src/email/templates/BrandEmail.vue +56 -0
  111. package/src/email/templates/CommentNotification.vue +39 -0
  112. package/src/email/templates/DocumentBlocked.vue +45 -0
  113. package/src/email/templates/DocumentInvitation.vue +24 -0
  114. package/src/email/templates/DocumentReport.vue +32 -0
  115. package/src/email/templates/DocumentReportDecided.vue +36 -0
  116. package/src/email/templates/DocumentReportReceived.vue +18 -0
  117. package/src/email/templates/DocumentRestored.vue +24 -0
  118. package/src/email/templates/EmailChangeRequested.vue +24 -0
  119. package/src/email/templates/EmailRoot.vue +19 -0
  120. package/src/email/templates/EmailText.vue +9 -0
  121. package/src/email/templates/EmailVerification.vue +38 -0
  122. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  123. package/src/email/templates/EnrollmentNotification.vue +24 -0
  124. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  125. package/src/email/templates/NewSignIn.vue +37 -0
  126. package/src/email/templates/PasswordChanged.vue +22 -0
  127. package/src/email/templates/PasswordReset.vue +23 -0
  128. package/src/email/templates/StorageLimitReached.vue +28 -0
  129. package/src/email/templates/TwoStepChanged.vue +47 -0
  130. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  131. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  132. package/src/email/templates/brand.ts +15 -61
  133. package/src/email/templates/localization.ts +17 -0
  134. package/src/errors/index.ts +6 -0
  135. package/src/{server/errors → errors}/posthog.ts +28 -4
  136. package/src/global.d.ts +7 -0
  137. package/src/runtime/cloudflare/email.ts +2 -0
  138. package/src/runtime/cloudflare/relay/index.ts +28 -7
  139. package/src/runtime/cloudflare/tsconfig.json +2 -1
  140. package/src/runtime/cloudflare/worker.ts +14 -1
  141. package/src/runtime/cloudflare/xml.ts +12 -0
  142. package/src/runtime/node/admin.ts +51 -47
  143. package/src/runtime/node/cleanup.ts +5 -1
  144. package/src/runtime/node/email/runtime.ts +1 -0
  145. package/src/runtime/node/email/transport.ts +14 -10
  146. package/src/runtime/node/main.ts +1 -1
  147. package/src/runtime/node/server.ts +20 -4
  148. package/src/runtime/node/services/main.ts +1 -1
  149. package/src/runtime/posthog/errors.ts +5 -2
  150. package/src/runtime/s3/objects.ts +17 -0
  151. package/src/runtime/site/community.ts +101 -0
  152. package/src/runtime/site/server.ts +17 -1
  153. package/src/server/account/actions.ts +3 -1
  154. package/src/server/account/deletion.ts +40 -4
  155. package/src/server/account/routes.ts +305 -253
  156. package/src/server/account/tokens.ts +57 -0
  157. package/src/server/api/router.ts +44 -6
  158. package/src/server/app/checks.ts +89 -0
  159. package/src/server/app/cors.ts +44 -0
  160. package/src/server/app/editors.ts +20 -0
  161. package/src/server/app/index.ts +128 -0
  162. package/src/server/app/indexing.ts +40 -0
  163. package/src/server/app/limiters.ts +53 -0
  164. package/src/server/app/routes.ts +123 -0
  165. package/src/server/app/services.ts +219 -0
  166. package/src/server/auth/access-control.ts +13 -8
  167. package/src/server/auth/access-tokens.ts +62 -0
  168. package/src/server/auth/account.ts +13 -12
  169. package/src/server/auth/activity.ts +7 -2
  170. package/src/server/auth/adapter.ts +36 -3
  171. package/src/server/auth/email.ts +33 -18
  172. package/src/server/auth/endpoints.ts +4 -0
  173. package/src/server/auth/enrollment.ts +116 -0
  174. package/src/server/auth/factory.ts +165 -189
  175. package/src/server/auth/index.ts +1 -1
  176. package/src/server/auth/logger.ts +23 -0
  177. package/src/server/auth/methods.ts +162 -0
  178. package/src/server/auth/mfa-assurance.ts +190 -2
  179. package/src/server/auth/passwords.ts +43 -0
  180. package/src/server/auth/rate-limit.ts +31 -0
  181. package/src/server/auth/runtime.ts +19 -5
  182. package/src/server/auth/session.ts +2 -0
  183. package/src/server/auth/social-providers.ts +70 -24
  184. package/src/server/billing/index.ts +8 -0
  185. package/src/server/billing/notify.ts +55 -0
  186. package/src/server/billing/routes.ts +27 -0
  187. package/src/server/billing/seats.ts +17 -0
  188. package/src/server/billing/tokens.ts +37 -0
  189. package/src/server/cleanup/configured.ts +16 -3
  190. package/src/server/cleanup/documents.ts +5 -2
  191. package/src/server/cleanup/revisions.ts +6 -3
  192. package/src/server/cleanup/uploads.ts +2 -1
  193. package/src/server/cleanup/worker.ts +10 -1
  194. package/src/server/collaboration/relay/connection.ts +7 -2
  195. package/src/server/collaboration/relay/hub.ts +80 -166
  196. package/src/server/collaboration/relay/room.ts +154 -0
  197. package/src/server/collaboration/routes.ts +8 -5
  198. package/src/server/collaboration/service.ts +21 -2
  199. package/src/server/comments/index.ts +9 -0
  200. package/src/server/comments/notify.ts +277 -0
  201. package/src/server/comments/routes.ts +352 -0
  202. package/src/server/comments/rows.ts +249 -0
  203. package/src/server/comments/service.ts +570 -0
  204. package/src/server/community/index.ts +2 -0
  205. package/src/server/community/routes.ts +93 -0
  206. package/src/server/community/service.ts +134 -0
  207. package/src/server/config/deployment.ts +35 -10
  208. package/src/server/config/index.ts +2 -2
  209. package/src/server/config/public.ts +25 -6
  210. package/src/server/config/schema.ts +53 -293
  211. package/src/server/config/toml/schema.ts +330 -0
  212. package/src/server/db/index.ts +3 -1
  213. package/src/server/db/migrate.ts +33 -1
  214. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  215. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  216. package/src/server/db/migrations/011_account_ids.ts +30 -0
  217. package/src/server/db/migrations/012_email_locales.ts +34 -0
  218. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  219. package/src/server/db/migrations/014_report_replies.ts +28 -0
  220. package/src/server/db/migrations/015_comments.ts +57 -0
  221. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  222. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  223. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  224. package/src/server/db/migrations/schema.ts +26 -1
  225. package/src/server/db/tables.ts +122 -3
  226. package/src/server/db/users.ts +22 -0
  227. package/src/server/documents/access.ts +17 -0
  228. package/src/server/documents/images.ts +6 -1
  229. package/src/server/documents/index.ts +1 -1
  230. package/src/server/documents/limits.ts +7 -1
  231. package/src/server/documents/routes.ts +12 -12
  232. package/src/server/documents/service.ts +31 -407
  233. package/src/server/documents/summary.ts +15 -0
  234. package/src/server/documents/uploads.ts +450 -0
  235. package/src/server/documents/versions/routes.ts +7 -8
  236. package/src/server/documents/versions/service.ts +86 -26
  237. package/src/server/email/invitations.ts +1 -0
  238. package/src/server/email/service.ts +39 -6
  239. package/src/server/email/types.ts +13 -0
  240. package/src/server/errors/index.ts +49 -12
  241. package/src/server/index.ts +27 -6
  242. package/src/server/internal/routes.ts +8 -2
  243. package/src/server/internal/service.ts +10 -0
  244. package/src/server/invitations/budget.ts +3 -1
  245. package/src/server/invitations/index.ts +1 -0
  246. package/src/server/invitations/links.ts +6 -0
  247. package/src/server/invitations/types.ts +5 -1
  248. package/src/server/objects/types.ts +5 -0
  249. package/src/server/pictures/service.ts +3 -1
  250. package/src/server/policy/configured.ts +9 -3
  251. package/src/server/policy/database.ts +13 -2
  252. package/src/server/policy/policy.ts +39 -12
  253. package/src/server/policy/service.ts +71 -52
  254. package/src/server/policy/storage.ts +33 -0
  255. package/src/server/policy/workspace.ts +5 -2
  256. package/src/server/quota/index.ts +6 -0
  257. package/src/server/quota/notices.ts +121 -0
  258. package/src/server/quota/storage.ts +5 -0
  259. package/src/server/rate-limit/middleware.ts +4 -0
  260. package/src/server/reports/index.ts +1 -0
  261. package/src/server/reports/replies.ts +55 -0
  262. package/src/server/reports/routes.ts +5 -3
  263. package/src/server/reports/service.ts +27 -3
  264. package/src/server/services/routes.ts +2 -2
  265. package/src/server/sharing/capabilities/service.ts +3 -4
  266. package/src/server/sharing/document-routes.ts +3 -3
  267. package/src/server/sharing/invitations/service.ts +17 -8
  268. package/src/server/sharing/routes.ts +15 -15
  269. package/src/server/validation.ts +35 -24
  270. package/src/server/workspaces/members.ts +57 -31
  271. package/src/server/workspaces/repository.ts +23 -12
  272. package/src/server/workspaces/routes.ts +8 -8
  273. package/src/services/app.ts +31 -22
  274. package/src/services/config.ts +48 -8
  275. package/src/services/metering.ts +15 -27
  276. package/src/services/usage.ts +6 -14
  277. package/src/email/templates/document-invitation.ts +0 -35
  278. package/src/email/templates/enrollment.ts +0 -27
  279. package/src/email/templates/layout.ts +0 -18
  280. package/src/server/app.ts +0 -453
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-cloudflare.js","names":["ptBR","zhCN","isBase64","urlSchema","creditsSchema","urlSchema","countSchema","enrollmentStatusSchema","DocumentInvitation","WorkspaceInvitation","EnrollmentUpdate","EnrollmentInvitation","EnrollmentNotification","EmailVerification","PasswordReset","PasswordChanged","EmailChangeRequested","NewSignIn","TwoStepChanged","DocumentReport","StorageLimitReached","DocumentBlocked","DocumentRestored","DocumentReportReceived","DocumentReportDecided","CommentNotification","EmailRoot","uuidSchema","accountIdSchema","FILTERS","dateString","enrollmentStatusSchema","FILTERS","searchCondition","FILTERS","logOnly","invitationContract","toISOString","providerPicture","searchCondition","FILTERS","toISOString","uuidSchema","FILTERS","searchCondition","positiveIntegerSchema","accountIdSchema","parseTOML","invitationContract","notFound","answer","getSignedURL","transformHTMLTemplate","#sockets"],"sources":["../src/email/locales/ar.json","../src/email/locales/de.json","../src/email/locales/es.json","../src/email/locales/fr.json","../src/email/locales/it.json","../src/email/locales/ja.json","../src/email/locales/pl.json","../src/email/locales/pt-br.json","../src/email/locales/ru.json","../src/email/locales/zh-cn.json","../src/email/messages.ts","../src/email/i18n.ts","../src/email/templates/brand.ts","../src/email/templates/localization.ts","../src/email/templates/BrandEmail.vue","../src/email/templates/EmailText.vue","../src/email/templates/CommentNotification.vue","../src/email/templates/DocumentBlocked.vue","../src/email/templates/DocumentInvitation.vue","../src/email/templates/DocumentReport.vue","../src/email/templates/DocumentReportDecided.vue","../src/email/templates/DocumentReportReceived.vue","../src/email/templates/DocumentRestored.vue","../src/email/templates/EmailChangeRequested.vue","../src/email/templates/EmailRoot.vue","../src/email/templates/EmailVerification.vue","../src/email/templates/EnrollmentInvitation.vue","../src/email/templates/EnrollmentNotification.vue","../src/email/templates/EnrollmentUpdate.vue","../src/email/templates/NewSignIn.vue","../src/email/templates/PasswordChanged.vue","../src/email/templates/PasswordReset.vue","../src/email/templates/StorageLimitReached.vue","../src/contract/account.ts","../src/contract/locale.ts","../src/contract/services.ts","../src/contract/billing.ts","../src/contract/documents.ts","../src/contract/collaboration.ts","../src/contract/workspaces.ts","../src/contract/sharing.ts","../src/contract/reports.ts","../src/contract/admin/index.ts","../src/contract/relay.ts","../src/contract/discovery.ts","../src/contract/links.ts","../src/contract/portal.ts","../src/contract/versions.ts","../src/contract/comments.ts","../src/contract/community.ts","../src/email/templates/TwoStepChanged.vue","../src/email/templates/WorkspaceInvitation.vue","../src/email/render.ts","../src/email/schema.ts","../src/server/email/crypto.ts","../src/server/email/service.ts","../src/server/email/invitations.ts","../src/runtime/cloudflare/email.ts","../src/admin/errors.ts","../src/admin/api/security.ts","../src/admin/schema.ts","../src/server/documents/errors.ts","../src/server/db/expressions.ts","../src/server/invitations/budget.ts","../src/server/invitations/links.ts","../src/server/rate-limit/cleanup.ts","../src/server/rate-limit/keys.ts","../src/server/rate-limit/postgres.ts","../src/server/rate-limit/middleware.ts","../src/server/validation.ts","../src/admin/api/routes.ts","../src/admin/list.ts","../src/admin/enrollment/email.ts","../src/admin/enrollment/service.ts","../src/server/db/database.ts","../src/server/db/users.ts","../src/admin/audit/service.ts","../src/admin/email/service.ts","../src/admin/operations/service.ts","../src/server/logging.ts","../src/server/errors/index.ts","../src/server/cleanup/objects.ts","../src/server/cleanup/documents.ts","../src/server/documents/purge.ts","../src/server/auth/access-control.ts","../src/server/quota/storage.ts","../src/server/sharing/errors.ts","../src/server/sharing/crypto.ts","../src/server/sharing/continuation.ts","../src/server/sharing/contracts.ts","../src/server/workspaces/repository.ts","../src/server/workspaces/members.ts","../src/server/workspaces/service.ts","../src/server/workspaces/routes.ts","../src/server/account/deletion.ts","../src/server/auth/social-providers.ts","../src/server/auth/methods.ts","../src/server/auth/account.ts","../src/server/auth/endpoints.ts","../src/server/auth/user-agent.ts","../src/server/auth/activity.ts","../src/server/auth/email.ts","../src/server/auth/mfa-assurance.ts","../src/server/account/terms.ts","../src/server/pictures/provider.ts","../src/server/pictures/service.ts","../src/server/pictures/routes.ts","../src/server/auth/access-tokens.ts","../src/server/auth/enrollment.ts","../src/server/auth/logger.ts","../src/server/auth/passwords.ts","../src/server/auth/rate-limit.ts","../src/server/auth/factory.ts","../src/server/auth/runtime.ts","../src/server/auth/session.ts","../src/admin/users/service.ts","../src/server/reports/replies.ts","../src/server/sharing/actor.ts","../src/server/documents/access.ts","../src/server/policy/keys.ts","../src/server/quota/notices.ts","../src/server/documents/routes.ts","../src/server/documents/images.ts","../src/server/policy/workspace.ts","../src/server/documents/versions/history.ts","../src/server/cleanup/revisions.ts","../src/server/cleanup/uploads.ts","../src/server/cleanup/configured.ts","../src/server/cleanup/worker.ts","../src/server/documents/summary.ts","../src/server/documents/repository.ts","../src/server/documents/trash.ts","../src/server/policy/storage.ts","../src/server/documents/limits.ts","../src/server/documents/versions/checkpoint.ts","../src/server/documents/uploads.ts","../src/server/documents/service.ts","../src/server/sharing/http.ts","../src/server/reports/service.ts","../src/server/reports/routes.ts","../src/admin/documents/service.ts","../src/admin/reports/service.ts","../src/server/billing/routes.ts","../src/server/billing/notify.ts","../src/server/billing/seats.ts","../src/server/policy/schema.ts","../src/server/config/limits.ts","../src/server/config/schema.ts","../src/server/services/keys.ts","../src/server/billing/tokens.ts","../src/server/services/errors.ts","../src/server/services/routes.ts","../src/server/services/tokens.ts","../src/server/sharing/access.ts","../src/server/policy/static.ts","../src/server/policy/database.ts","../src/server/policy/entitlements.ts","../src/server/policy/provider.ts","../src/server/config/toml/schema.ts","../src/server/config/deployment.ts","../src/server/config/public.ts","../src/server/policy/policy.ts","../src/server/policy/configured.ts","../src/server/policy/service.ts","../src/server/sharing/policy.ts","../src/server/sharing/capabilities/service.ts","../src/server/sharing/grants/service.ts","../src/server/sharing/document-routes.ts","../src/server/sharing/invitations/service.ts","../src/server/sharing/routes.ts","../src/server/sharing/service.ts","../src/server/collaboration/routes.ts","../src/server/collaboration/service.ts","../src/server/collaboration/relay/authorize.ts","../src/server/collaboration/relay/awareness.ts","../src/server/collaboration/relay/documents.ts","../src/server/collaboration/relay/connection.ts","../src/server/collaboration/relay/log.ts","../src/server/collaboration/relay/room.ts","../src/server/collaboration/relay/hub.ts","../src/server/collaboration/relay/persistence.ts","../src/server/collaboration/relay/resume.ts","../src/server/comments/notify.ts","../src/server/comments/rows.ts","../src/server/comments/service.ts","../src/server/comments/routes.ts","../src/server/community/routes.ts","../src/server/community/service.ts","../src/server/documents/versions/routes.ts","../src/server/documents/versions/service.ts","../src/server/api/router.ts","../src/server/app/checks.ts","../src/server/app/cors.ts","../src/server/app/editors.ts","../src/server/app/indexing.ts","../src/server/app/limiters.ts","../src/server/account/actions.ts","../src/server/account/routes.ts","../src/server/account/tokens.ts","../src/server/internal/schema.ts","../src/server/internal/routes.ts","../src/server/internal/service.ts","../src/server/app/routes.ts","../src/server/app/services.ts","../src/server/app/index.ts","../src/runtime/postgres/database.ts","../src/runtime/s3/objects.ts","../src/runtime/site/community.ts","../src/runtime/site/server.ts","../src/errors/posthog.ts","../src/runtime/posthog/errors.ts","../src/runtime/cloudflare/logging.ts","../src/runtime/cloudflare/environment.ts","../src/runtime/cloudflare/maintenance.ts","../src/runtime/cloudflare/relay/sockets.ts","../src/runtime/cloudflare/relay/index.ts","../src/runtime/cloudflare/site.ts","../src/runtime/cloudflare/xml.ts","../src/runtime/cloudflare/worker.ts"],"sourcesContent":["","","","","","","","","","","import { params } from '@nanostores/i18n'\n\n/**\n * Every email's words in English, translated under `locales/`. A name, address, or document in a\n * placeholder is someone's own text and stays as they wrote it.\n */\nexport const emailMessageDefaults = {\n greeting: params('Hi {name},'),\n greetingWithoutName: 'Hi,',\n someone: 'Someone',\n openCloud: 'Open OpenPencil Cloud',\n footer: 'OpenPencil, the open-source design editor',\n invitationExpires: params('This invitation expires on {date}.'),\n\n documentInvitationHeading: 'You’re invited to a document',\n documentInvitationViewSubject: params('{inviter} invited you to view “{document}”'),\n documentInvitationEditSubject: params('{inviter} invited you to edit “{document}”'),\n documentInvitationView: params('{inviter} invited you to view “{document}” on OpenPencil Cloud.'),\n documentInvitationEdit: params('{inviter} invited you to edit “{document}” on OpenPencil Cloud.'),\n documentInvitationAction: 'Open document',\n\n workspaceInvitationSubject: params('{inviter} invited you to {workspace}'),\n workspaceInvitationHeading: params('Join {workspace}'),\n workspaceInvitationAdmin: params(\n '{inviter} invited you to manage the workspace “{workspace}” on OpenPencil Cloud.'\n ),\n workspaceInvitationEditor: params(\n '{inviter} invited you to edit in the workspace “{workspace}” on OpenPencil Cloud.'\n ),\n workspaceInvitationViewer: params(\n '{inviter} invited you to view the workspace “{workspace}” on OpenPencil Cloud.'\n ),\n workspaceInvitationHome: 'You’ll see its documents on Home once you join.',\n workspaceInvitationAction: 'Join workspace',\n\n enrollmentRequestedSubject: 'We received your OpenPencil Cloud request',\n enrollmentRequestedHeading: 'Request received',\n enrollmentRequestedPreview: 'Your OpenPencil Cloud access request is awaiting review.',\n enrollmentRequested: 'Your request is awaiting review. We’ll write again once it’s decided.',\n enrollmentApprovedSubject: 'Your OpenPencil Cloud access is ready',\n enrollmentApprovedHeading: 'Access approved',\n enrollmentApprovedPreview: 'You can now sign in to OpenPencil Cloud.',\n enrollmentApproved: 'Your access request was approved, so you can sign in now.',\n enrollmentApprovedAction: 'Sign in',\n enrollmentRejectedSubject: 'Your OpenPencil Cloud request was reviewed',\n enrollmentRejectedHeading: 'Request reviewed',\n enrollmentRejectedPreview: 'Your access request was not approved.',\n enrollmentRejected: 'Your access request was not approved this time.',\n enrollmentRejectedAction: 'Request access again',\n enrollmentRevokedSubject: 'Your OpenPencil Cloud access has changed',\n enrollmentRevokedHeading: 'Access changed',\n enrollmentRevokedPreview: 'Your OpenPencil Cloud access is no longer active.',\n enrollmentRevoked: 'Your OpenPencil Cloud access is no longer active.',\n enrollmentRevokedAction: 'Open OpenPencil',\n invitationSubject: 'You can try OpenPencil Cloud now',\n invitationHeading: 'Cloud is open',\n invitationPreview: 'OpenPencil Cloud is open, and you can sign in now.',\n invitationWaitlistSubject: 'OpenPencil Cloud is ready',\n invitationWaitlistPreview: 'You joined the waitlist; Cloud is open now.',\n invitationWaitlistBeta:\n 'It’s still a beta: some features are switched off, and some things will break. When they do, reply to this email and tell me, or {link} if you’re comfortable with that. I read both.',\n invitationWaitlistThanks:\n 'Thank you for joining the OpenPencil Cloud waitlist. Here’s the one email we promised: Cloud is open, and you can sign in now.',\n invitationThanks:\n 'A while ago you asked to try OpenPencil Cloud. Thanks for being curious enough to ask, and for waiting. We were still testing it then and weren’t ready to let anyone in.',\n invitationBeta:\n 'It’s open now, and you can sign in. It’s still a beta: some features are switched off, and some things will break. When they do, reply to this email and tell me, or {link} if you’re comfortable with that. I read both.',\n invitationIssueLink: 'open an issue on GitHub',\n invitationDesktop: 'To use Cloud in the desktop app, you need the beta release from the {link}.',\n invitationDownloadLink: 'download page',\n invitationAction: 'Open Cloud',\n invitationSignatureName: 'Danila',\n invitationSignatureRole: 'Founder of OpenPencil',\n\n enrollmentNotificationSubject: 'New OpenPencil Cloud access request',\n enrollmentNotificationHeading: 'New access request',\n enrollmentNotificationPreview: params('{email} requested OpenPencil Cloud access.'),\n enrollmentNotification: params('{name} ({email}) requested access and wrote:'),\n enrollmentNotificationAction: 'Review request',\n\n documentReportSubject: 'A shared OpenPencil Cloud document was reported',\n documentReportHeading: 'A shared document was reported',\n documentReportPreview: params('“{document}” was reported for {reason}.'),\n documentReport: params(\n 'Someone who opened “{document}” from a share link reported it for {reason} and wrote:'\n ),\n documentReportAction: 'Review report',\n reportReasonSpamPhishing: 'spam or phishing',\n reportReasonIllegal: 'illegal content',\n reportReasonCopyright: 'copyright',\n reportReasonHarassment: 'harassment',\n reportReasonOther: 'something else',\n\n verifyAccountSubject: 'Confirm your OpenPencil Cloud email',\n verifyAccountHeading: 'Confirm your email',\n verifyAccountPreview: 'One click to finish creating your OpenPencil Cloud account.',\n verifyAccount:\n 'Confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.',\n verifyAccountNote: 'Didn’t create an account? Ignore this email and nothing happens.',\n verifyChangeSubject: 'Confirm your new OpenPencil Cloud email',\n verifyChangeHeading: 'Confirm your new email',\n verifyChangePreview: 'One click to move your OpenPencil Cloud account to this address.',\n verifyChange:\n 'Confirm this address to make it your OpenPencil Cloud account’s email. Your old address stays until you do.',\n verifyChangeNote: 'Didn’t ask for this? Ignore this email and nothing changes.',\n verifyAction: 'Confirm email',\n\n passwordResetSubject: 'Reset your OpenPencil Cloud password',\n passwordResetHeading: 'Reset your password',\n passwordResetPreview: 'Use this secure link to choose a new password.',\n passwordReset: 'Use the link below to choose a new password.',\n passwordResetNote: 'Didn’t ask for this? Ignore this email and your password stays the same.',\n passwordResetAction: 'Reset password',\n\n passwordChangedSubject: 'Your OpenPencil Cloud password changed',\n passwordChangedHeading: 'Password changed',\n passwordChangedPreview: 'Your OpenPencil Cloud password was changed.',\n passwordChanged: 'Your password was changed. If this wasn’t you, contact your administrator.',\n\n emailChangeSubject: 'Your OpenPencil Cloud email is changing',\n emailChangeHeading: 'Your email is changing',\n emailChangePreview: params('Your OpenPencil Cloud email is changing to {email}.'),\n emailChange: params(\n 'Someone signed in to your account asked to change its email to {email}. It changes once that address confirms it.'\n ),\n emailChangeNotYou:\n 'If this wasn’t you, change your password and sign out of your other sessions.',\n reviewAccount: 'Review your account',\n\n newSignInSubject: 'New sign-in to your OpenPencil Cloud account',\n newSignInHeading: 'New sign-in to your account',\n newSignInPreview: params('Your OpenPencil Cloud account was signed in to with {device}.'),\n newSignIn: params('Your account was signed in to with {device} on {date}.'),\n newSignInFrom: params('Your account was signed in to with {device} from {address} on {date}.'),\n newSignInNotYou:\n 'If this was you, there’s nothing to do. If it wasn’t, sign that session out and change your password.',\n newSignInApp: 'the OpenPencil app',\n newSignInBrowser: params('{browser} on {system}'),\n newSignInUnknownBrowser: 'an unknown browser',\n reviewSessions: 'Review sessions',\n\n twoStepSubject: 'How you sign in to OpenPencil Cloud changed',\n authenticatorOnHeading: 'Authenticator app turned on',\n authenticatorOn: 'An authenticator app now confirms your sign-ins.',\n authenticatorOffHeading: 'Authenticator app turned off',\n authenticatorOff: 'Your sign-ins no longer ask for a code from an authenticator app.',\n passkeyAddedHeading: 'Passkey added',\n passkeyAdded: 'A passkey was added to your account.',\n passkeyRemovedHeading: 'Passkey removed',\n passkeyRemoved: 'A passkey was removed from your account.',\n twoStepResetHeading: 'Two-step sign-in was reset',\n twoStepReset:\n 'An administrator removed your authenticator app, recovery codes, and passkeys, so you can set them up again.',\n signInMethodRemovedHeading: 'Sign-in method removed',\n signInMethodRemoved: params(\n 'An administrator removed {method} from the ways you sign in to your account.'\n ),\n signInMethodPassword: 'your password',\n twoStepNotYou: 'If this wasn’t you, change your password and contact your administrator.',\n reviewSecurity: 'Review security',\n\n storageFullSubject: 'Your OpenPencil Cloud files are read-only',\n storageFullHeading: 'Your storage is full',\n storageFullPreview: params(\n 'Your OpenPencil Cloud files use {used} of {limit}, so they’re read-only.'\n ),\n storageFull: params(\n 'Your workspaces hold {used}, and your plan includes {limit}. Until they hold less, your documents open and download but take no edits or new files.'\n ),\n storageFullUpgrade: 'Get more storage, or delete documents and empty the trash, to edit again.',\n storageFullFreeSpace: 'Delete documents and empty the trash to edit again.',\n storageFullAction: 'Get more storage',\n\n documentBlockedSubject: params('Your document “{document}” was blocked'),\n documentBlockedHeading: 'A document of yours was blocked',\n documentBlocked: params(\n 'An administrator of OpenPencil Cloud blocked your document “{document}”. Nobody can open it, you included, until it’s restored. Nothing in it was deleted.'\n ),\n documentBlockedReason: params('The reason they gave: {reason}'),\n documentBlockedContest: params(\n 'If you think this is a mistake, write to {email} to have it looked at again.'\n ),\n documentBlockedContestAdministrators:\n 'If you think this is a mistake, ask the server’s administrators to look at it again.',\n documentRestoredSubject: params('Your document “{document}” is back'),\n documentRestoredHeading: 'Your document is back',\n documentRestored: params(\n 'An administrator restored your document “{document}”. It opens again for you and everyone you shared it with.'\n ),\n openHome: 'Open Home',\n reportReceivedSubject: params('We received your report about “{document}”'),\n reportReceivedHeading: 'Report received',\n reportReceived: params(\n 'Thanks for reporting “{document}”. The server’s administrators review every report and decide whether it breaks the rules. We’ll write again when they have.'\n ),\n reportDecidedSubject: params('Your report about “{document}”'),\n reportBlockedHeading: 'The document was blocked',\n reportBlocked: params(\n 'The administrators reviewed your report and blocked “{document}”, so nobody can open it until it’s restored.'\n ),\n reportActionedHeading: 'Your report was acted on',\n reportActioned: params(\n 'The administrators reviewed your report about “{document}” and took action on it.'\n ),\n reportDismissedHeading: 'The document stays',\n reportDismissed: params(\n 'The administrators reviewed your report about “{document}” and found it doesn’t break the rules, so it stays as it is.'\n ),\n reportDisagree: params('If you disagree, write to {email}.'),\n reportDisagreeAdministrators:\n 'If you disagree, ask the server’s administrators to look at it again.',\n\n commentMentionSubject: params('{author} mentioned you in “{document}”'),\n commentReplySubject: params('{author} replied in “{document}”'),\n commentMentionHeading: 'You were mentioned',\n commentReplyHeading: 'New reply',\n commentMention: params('{author} mentioned you in a comment on “{document}”:'),\n commentReply: params('{author} replied in a thread you’re part of on “{document}”:'),\n commentSomeone: 'Someone',\n openComment: 'Open the comment',\n commentSettings: 'You get these emails as your notification settings say. Change them in {link}.',\n commentSettingsLink: 'your account settings',\n\n waitlistSubject: 'Confirm your place on the OpenPencil Cloud waitlist',\n waitlistHeading: 'Confirm your email',\n waitlistPreview: 'One click to join the OpenPencil Cloud waitlist.',\n waitlist:\n 'Thanks for your interest in OpenPencil Cloud. Confirm this address to join the waitlist, and we’ll write once, when Cloud is ready for you.',\n waitlistAction: 'Join the waitlist',\n waitlistNote:\n 'Didn’t sign up? Ignore this email and the address is deleted in seven days, or {link}.',\n waitlistLeave: 'remove it now'\n}\n\nexport type EmailMessageDefaults = typeof emailMessageDefaults\n","import { createI18n, type Components, type Messages } from '@nanostores/i18n'\nimport { mapValues } from 'es-toolkit'\nimport { parseAccept } from 'hono/utils/accept'\nimport { atom, type StoreValue } from 'nanostores'\n\nimport ar from './locales/ar.json'\nimport de from './locales/de.json'\nimport es from './locales/es.json'\nimport fr from './locales/fr.json'\nimport it from './locales/it.json'\nimport ja from './locales/ja.json'\nimport pl from './locales/pl.json'\nimport ptBR from './locales/pt-br.json'\nimport ru from './locales/ru.json'\nimport zhCN from './locales/zh-cn.json'\nimport { emailMessageDefaults } from './messages'\n\n/**\n * Each language's translations of `emailMessageDefaults`, bundled so a Worker reads no files. They\n * are what Cloud writes in: a language is supported once its file is here.\n */\nconst TRANSLATIONS = {\n ar,\n de,\n es,\n fr,\n it,\n ja,\n pl,\n 'pt-BR': ptBR,\n ru,\n 'zh-CN': zhCN\n} satisfies Record<string, Record<string, string>>\n\n/** A language Cloud writes email in: English, or one it has translations for. */\nexport type EmailLocale = 'en' | keyof typeof TRANSLATIONS\n\n/** Every language Cloud writes email in, English first. */\nexport const EMAIL_LOCALES: readonly EmailLocale[] = ['en', ...typedKeys(TRANSLATIONS)]\n\nfunction typedKeys<Value extends object>(value: Value): Array<keyof Value & string> {\n return Object.keys(value).filter((key): key is keyof Value & string => key in value)\n}\n\nexport function isEmailLocale(value: unknown): value is EmailLocale {\n return EMAIL_LOCALES.some((code) => code === value)\n}\n\n/** A tag's language and script, as Unicode's likely subtags fill them in: `zh-TW` is `zh-Hant`. */\nfunction languageScript(tag: string): string | null {\n try {\n const { language, script } = new Intl.Locale(tag).maximize()\n return `${language}-${script ?? ''}`\n } catch {\n return null\n }\n}\n\n/**\n * The first of someone's languages Cloud writes in: the same tag, or the same language in the same\n * script, so `de-AT` reads German and `zh-TW`, written in Traditional, doesn't read Simplified.\n */\nexport function emailLocale(languages: readonly string[]): EmailLocale | null {\n const byTag = new Map(EMAIL_LOCALES.map((code) => [code.toLowerCase(), code]))\n const byScript = new Map(EMAIL_LOCALES.map((code) => [languageScript(code), code]))\n for (const language of languages) {\n const match = byTag.get(language.toLowerCase()) ?? byScript.get(languageScript(language))\n if (match) return match\n }\n return null\n}\n\n/** Locales written right to left. */\nconst RIGHT_TO_LEFT: ReadonlySet<EmailLocale> = new Set<EmailLocale>(['ar'])\n\nconst RIGHT_TO_LEFT_MARK = String.fromCodePoint(0x200f)\nconst FIRST_STRONG_ISOLATE = String.fromCodePoint(0x2068)\nconst POP_DIRECTIONAL_ISOLATE = String.fromCodePoint(0x2069)\n\n/**\n * Right-to-left messages as the app shows them: each between right-to-left marks, so punctuation\n * after a Latin name ends the sentence on its left, and each placeholder isolated, so a name or\n * address put into it keeps its own order: `report.pdf`, not `pdf.report`.\n */\nfunction directed(messages: Record<string, string>): Record<string, string> {\n return mapValues(messages, (message) => {\n const isolated = message.replaceAll(\n /\\{\\w+\\}/g,\n (placeholder) => `${FIRST_STRONG_ISOLATE}${placeholder}${POP_DIRECTIONAL_ISOLATE}`\n )\n return `${RIGHT_TO_LEFT_MARK}${isolated}${RIGHT_TO_LEFT_MARK}`\n })\n}\n\nexport type EmailMessages = StoreValue<Messages<typeof emailMessageDefaults>>\n\n/** The words, formats, and direction of email written in one locale. */\nexport type EmailLocalization = {\n locale: EmailLocale\n dir: 'ltr' | 'rtl'\n t: EmailMessages\n /** A moment in UTC, as Cloud doesn't know the reader's time zone: 13 November 2026, 10:00 UTC. */\n dateTime: (iso: string) => string\n /** Bytes in binary units, as the portal shows them: 300 MB, 10 GB. */\n storage: (bytes: number) => string\n}\n\nconst STORAGE_UNITS = [\n { unit: 'gigabyte', bytes: 1024 ** 3 },\n { unit: 'megabyte', bytes: 1024 ** 2 },\n { unit: 'kilobyte', bytes: 1024 }\n] as const\n\nfunction messages(locale: EmailLocale): EmailMessages {\n const translations: Record<string, Components> =\n locale === 'en'\n ? {}\n : {\n [locale]: {\n email: RIGHT_TO_LEFT.has(locale) ? directed(TRANSLATIONS[locale]) : TRANSLATIONS[locale]\n }\n }\n // Every translation is in the cache, so nothing is ever fetched.\n const i18n = createI18n(atom(locale), {\n baseLocale: 'en',\n cache: translations,\n get: async () => ({})\n })\n return i18n('email', emailMessageDefaults).get()\n}\n\nconst localizations = new Map<EmailLocale, EmailLocalization>()\n\nexport function emailLocalization(locale: EmailLocale): EmailLocalization {\n const cached = localizations.get(locale)\n if (cached) return cached\n const dateTime = new Intl.DateTimeFormat(locale, {\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n timeZone: 'UTC',\n timeZoneName: 'short'\n })\n const localization: EmailLocalization = {\n locale,\n dir: RIGHT_TO_LEFT.has(locale) ? 'rtl' : 'ltr',\n t: messages(locale),\n dateTime: (iso) => dateTime.format(new Date(iso)),\n storage: (bytes) => {\n const { unit, bytes: size } = STORAGE_UNITS.find((step) => bytes >= step.bytes) ?? {\n unit: 'byte',\n bytes: 1\n }\n return new Intl.NumberFormat(locale, {\n style: 'unit',\n unit,\n unitDisplay: 'short',\n maximumFractionDigits: 1\n }).format(bytes / size)\n }\n }\n localizations.set(locale, localization)\n return localization\n}\n\n/** The language an `Accept-Language` header prefers among Cloud's, or null when it names none. */\nexport function acceptedLocale(header: string | null | undefined): EmailLocale | null {\n const languages = parseAccept(header ?? '')\n .filter((language) => language.q > 0)\n .map((language) => language.type)\n return emailLocale(languages)\n}\n","/** The brand every OpenPencil email shares, from the waitlist to Cloud: its colors and type. */\n\n/** The ivory app-icon tile, served as PNG because mail clients do not draw SVG. */\nexport const LOGO_URL = 'https://openpencil.dev/brand/app-icon-1024.png'\nexport const SITE_URL = 'https://openpencil.dev'\n/** The download page's beta section, with the newest desktop beta's installers. */\nexport const DESKTOP_BETA_URL = 'https://openpencil.dev/download#beta'\n/** The repository's bug report form. */\nexport const BUG_REPORT_URL =\n 'https://github.com/open-pencil/open-pencil/issues/new?template=bug_report.yml'\n\nconst FONT = '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif'\nconst INK = '#171717'\nconst MUTED = '#6B6B6B'\n/** Deep teal from the mark; white text on it passes WCAG AA. */\nconst TEAL = '#0A6C65'\n\n/** Inline styles, since mail clients drop most stylesheets. */\nexport const styles = {\n body: { backgroundColor: '#F5F5EF', fontFamily: FONT, margin: '0', padding: '40px 16px' },\n card: {\n maxWidth: '480px',\n margin: '0 auto',\n padding: '40px',\n backgroundColor: '#FFFFFF',\n borderRadius: '16px',\n border: '1px solid #E7E5DC'\n },\n logo: { borderRadius: '10px', margin: '0 0 28px' },\n heading: {\n color: INK,\n fontSize: '22px',\n fontWeight: '600',\n lineHeight: '1.3',\n margin: '0 0 12px'\n },\n text: { color: '#404040', fontSize: '15px', lineHeight: '1.6', margin: '0 0 16px' },\n action: { paddingTop: '8px' },\n button: {\n backgroundColor: TEAL,\n borderRadius: '10px',\n color: '#FFFFFF',\n fontSize: '15px',\n fontWeight: '600',\n padding: '12px 22px',\n textDecoration: 'none'\n },\n signature: { color: '#404040', fontSize: '15px', lineHeight: '1.6', margin: '28px 0 0' },\n note: { color: MUTED, fontSize: '13px', lineHeight: '1.6', margin: '28px 0 0' },\n link: { color: TEAL, textDecoration: 'underline' },\n footer: {\n color: MUTED,\n fontSize: '12px',\n lineHeight: '1.6',\n textAlign: 'center' as const,\n margin: '24px 0 0'\n },\n footerLink: { color: MUTED }\n}\n","import { inject, type InjectionKey } from 'vue'\n\nimport type { EmailLocalization } from '../i18n'\n\n/** The reader's language, which every email and its layout write in. */\nexport const EMAIL_LOCALIZATION: InjectionKey<EmailLocalization> = Symbol('email-localization')\n\nexport function useEmailLocalization(): EmailLocalization {\n const localization = inject(EMAIL_LOCALIZATION)\n if (!localization) throw new Error('An email renders inside EmailRoot, which gives its language')\n return localization\n}\n\n/** \"Hi Ada,\" or, when the account has no name, \"Hi,\". */\nexport function greeting({ t }: EmailLocalization, name: string | null): string {\n return name ? t.greeting({ name }) : t.greetingWithoutName\n}\n","<script setup lang=\"ts\">\nimport {\n Body,\n Button,\n Container,\n Head,\n Heading,\n // eslint-disable-next-line @open-pencil/structure/no-mixed-case-acronym-identifiers -- Upstream export spelling.\n Html as HTML,\n Img,\n Link,\n Preview,\n Section,\n Text\n} from '@vue-email/components'\n\nimport { LOGO_URL, SITE_URL, styles } from './brand'\nimport { useEmailLocalization } from './localization'\n\n/**\n * The branded email every OpenPencil service sends, in its reader's language and direction: a\n * heading, the paragraphs in the default slot, one button, the sender's name in `signature` when a\n * person writes, and small print in `note`.\n */\nconst { preview, heading, action } = defineProps<{\n /** The line mail clients show beside the subject. */\n preview: string\n heading: string\n /** The one thing the email asks the reader to do, if there is one. */\n action?: { label: string; url: string }\n}>()\n\nconst { locale, dir, t } = useEmailLocalization()\n</script>\n\n<template>\n <HTML :lang=\"locale\" :dir=\"dir\">\n <Head />\n <Preview>{{ preview }}</Preview>\n <Body :style=\"styles.body\">\n <Container :style=\"styles.card\">\n <Img :src=\"LOGO_URL\" :width=\"44\" :height=\"44\" alt=\"OpenPencil\" :style=\"styles.logo\" />\n <Heading as=\"h1\" :style=\"styles.heading\">{{ heading }}</Heading>\n <slot />\n <Section v-if=\"action\" :style=\"styles.action\">\n <Button :href=\"action.url\" :style=\"styles.button\">{{ action.label }}</Button>\n </Section>\n <Text v-if=\"$slots.signature\" :style=\"styles.signature\"><slot name=\"signature\" /></Text>\n <Text v-if=\"$slots.note\" :style=\"styles.note\"><slot name=\"note\" /></Text>\n </Container>\n <Text :style=\"styles.footer\">\n {{ t.footer }} · <Link :href=\"SITE_URL\" :style=\"styles.footerLink\">openpencil.dev</Link>\n </Text>\n </Body>\n </HTML>\n</template>\n","<script setup lang=\"ts\">\nimport { Text } from '@vue-email/components'\n\nimport { styles } from './brand'\n</script>\n\n<template>\n <Text :style=\"styles.text\"><slot /></Text>\n</template>\n","<script setup lang=\"ts\">\nimport { Link } from '@vue-email/components'\n\nimport type { CommentNotificationPayload } from '../schema'\nimport { styles } from './brand'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** To someone a comment names, or who takes part in its thread: who wrote what, and where. */\nconst { payload } = defineProps<{ payload: CommentNotificationPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\nconst words = {\n author: payload.authorName ?? t.commentSomeone,\n document: payload.documentName\n}\nconst lead = payload.reason === 'mention' ? t.commentMention(words) : t.commentReply(words)\n// The translation places the link inside its sentence, where `{link}` is.\nconst [beforeLink = '', afterLink = ''] = t.commentSettings.split('{link}')\n</script>\n\n<template>\n <BrandEmail\n :preview=\"payload.excerpt\"\n :heading=\"payload.reason === 'mention' ? t.commentMentionHeading : t.commentReplyHeading\"\n :action=\"{ label: t.openComment, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ lead }}</EmailText>\n <EmailText>“{{ payload.excerpt }}”</EmailText>\n <template #note>\n {{ beforeLink\n }}<Link :href=\"payload.settingsURL\" :style=\"styles.link\">{{ t.commentSettingsLink }}</Link\n >{{ afterLink }}\n </template>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport { Link } from '@vue-email/components'\n\nimport type { DocumentBlockedPayload } from '../schema'\nimport { styles } from './brand'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/**\n * To a workspace's owner: an administrator took one of its documents down. It says why, when the\n * administrator gave a reason, and where to contest it.\n */\nconst { payload } = defineProps<{ payload: DocumentBlockedPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\nconst document = { document: payload.documentName }\n// The translation places the address inside its sentence, where `{email}` is.\nconst [beforeEmail = '', afterEmail = ''] = t\n .documentBlockedContest({ email: '{email}' })\n .split('{email}')\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.documentBlocked(document)\"\n :heading=\"t.documentBlockedHeading\"\n :action=\"{ label: t.openHome, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.documentBlocked(document) }}</EmailText>\n <EmailText v-if=\"payload.reason\">\n {{ t.documentBlockedReason({ reason: payload.reason }) }}\n </EmailText>\n <EmailText v-if=\"payload.contactEmail\">\n {{ beforeEmail\n }}<Link :href=\"`mailto:${payload.contactEmail}`\" :style=\"styles.link\">{{\n payload.contactEmail\n }}</Link\n >{{ afterEmail }}\n </EmailText>\n <EmailText v-else>{{ t.documentBlockedContestAdministrators }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { DocumentInvitationEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\nconst { payload } = defineProps<{ payload: DocumentInvitationEmailPayload }>()\n\nconst { t, dateTime } = useEmailLocalization()\nconst names = { inviter: payload.inviterName ?? t.someone, document: payload.documentName }\nconst message =\n payload.permission === 'edit' ? t.documentInvitationEdit(names) : t.documentInvitationView(names)\n</script>\n\n<template>\n <BrandEmail\n :preview=\"message\"\n :heading=\"t.documentInvitationHeading\"\n :action=\"{ label: t.documentInvitationAction, url: payload.acceptanceURL }\"\n >\n <EmailText>{{ message }}</EmailText>\n <template #note>{{ t.invitationExpires({ date: dateTime(payload.expiresAt) }) }}</template>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { DocumentReportReason } from '#cloud/contract'\n\nimport type { DocumentReportPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\n/** To administrators: someone reported a shared document, in their own words. */\nconst { payload } = defineProps<{ payload: DocumentReportPayload }>()\n\nconst { t } = useEmailLocalization()\nconst reasons: Record<DocumentReportReason, string> = {\n 'spam-phishing': t.reportReasonSpamPhishing,\n illegal: t.reportReasonIllegal,\n copyright: t.reportReasonCopyright,\n harassment: t.reportReasonHarassment,\n other: t.reportReasonOther\n}\nconst report = { document: payload.documentName, reason: reasons[payload.reason] }\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.documentReportPreview(report)\"\n :heading=\"t.documentReportHeading\"\n :action=\"{ label: t.documentReportAction, url: payload.actionURL }\"\n >\n <EmailText>{{ t.documentReport(report) }}</EmailText>\n <EmailText>{{ payload.description }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport { Link } from '@vue-email/components'\n\nimport type { DocumentReportDecidedPayload } from '../schema'\nimport { styles } from './brand'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\n/** To whoever reported a document: what the administrators decided, and where to disagree. */\nconst { payload } = defineProps<{ payload: DocumentReportDecidedPayload }>()\n\nconst { t } = useEmailLocalization()\nconst document = { document: payload.documentName }\nconst decision = {\n blocked: { heading: t.reportBlockedHeading, message: t.reportBlocked(document) },\n actioned: { heading: t.reportActionedHeading, message: t.reportActioned(document) },\n dismissed: { heading: t.reportDismissedHeading, message: t.reportDismissed(document) }\n}[payload.outcome]\n// The translation places the address inside its sentence, where `{email}` is.\nconst [beforeEmail = '', afterEmail = ''] = t.reportDisagree({ email: '{email}' }).split('{email}')\n</script>\n\n<template>\n <BrandEmail :preview=\"decision.message\" :heading=\"decision.heading\">\n <EmailText>{{ decision.message }}</EmailText>\n <EmailText v-if=\"payload.contactEmail\">\n {{ beforeEmail\n }}<Link :href=\"`mailto:${payload.contactEmail}`\" :style=\"styles.link\">{{\n payload.contactEmail\n }}</Link\n >{{ afterEmail }}\n </EmailText>\n <EmailText v-else>{{ t.reportDisagreeAdministrators }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { DocumentReportReceivedPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\n/** To whoever reported a document: their report arrived, and they'll hear the decision. */\nconst { payload } = defineProps<{ payload: DocumentReportReceivedPayload }>()\n\nconst { t } = useEmailLocalization()\nconst document = { document: payload.documentName }\n</script>\n\n<template>\n <BrandEmail :preview=\"t.reportReceived(document)\" :heading=\"t.reportReceivedHeading\">\n <EmailText>{{ t.reportReceived(document) }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { DocumentRestoredPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** To a workspace's owner: a document an administrator took down is back. */\nconst { payload } = defineProps<{ payload: DocumentRestoredPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\nconst document = { document: payload.documentName }\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.documentRestored(document)\"\n :heading=\"t.documentRestoredHeading\"\n :action=\"{ label: t.openHome, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.documentRestored(document) }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { EmailChangeRequestedPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** To the address being replaced: which address is taking over, before it confirms. */\nconst { payload } = defineProps<{ payload: EmailChangeRequestedPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.emailChangePreview({ email: payload.newEmail })\"\n :heading=\"t.emailChangeHeading\"\n :action=\"{ label: t.reviewAccount, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.emailChange({ email: payload.newEmail }) }}</EmailText>\n <EmailText>{{ t.emailChangeNotYou }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport { provide, type Component } from 'vue'\n\nimport type { EmailLocalization } from '../i18n'\nimport { EMAIL_LOCALIZATION } from './localization'\n\n/** Renders an email in its reader's language, which it and its layout read. */\nconst { email, props, localization } = defineProps<{\n email: Component\n props: Record<string, unknown>\n localization: EmailLocalization\n}>()\n\nprovide(EMAIL_LOCALIZATION, localization)\n</script>\n\n<template>\n <component :is=\"email\" v-bind=\"props\" />\n</template>\n","<script setup lang=\"ts\">\nimport type { AuthenticationEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** Confirms the address a new account signed up with, or one an account is moving to. */\nconst { payload } = defineProps<{ payload: AuthenticationEmailPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\nconst copy =\n payload.purpose === 'change'\n ? {\n preview: t.verifyChangePreview,\n heading: t.verifyChangeHeading,\n message: t.verifyChange,\n note: t.verifyChangeNote\n }\n : {\n preview: t.verifyAccountPreview,\n heading: t.verifyAccountHeading,\n message: t.verifyAccount,\n note: t.verifyAccountNote\n }\n</script>\n\n<template>\n <BrandEmail\n :preview=\"copy.preview\"\n :heading=\"copy.heading\"\n :action=\"{ label: t.verifyAction, url: payload.actionURL ?? '#' }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ copy.message }}</EmailText>\n <template #note>{{ copy.note }}</template>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport { Link } from '@vue-email/components'\n\nimport type { EnrollmentEmailPayload } from '../schema'\nimport { BUG_REPORT_URL, DESKTOP_BETA_URL, styles } from './brand'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/**\n * A letter from OpenPencil's founder to someone who asked for the official Cloud before it opened,\n * or joined its waitlist on openpencil.dev: thanks for waiting, it is a beta, and where to say what\n * breaks. Replies reach a person, through the deployment's reply address. The waitlist gave no\n * name, so its letter opens with the thanks rather than a greeting.\n */\nconst { payload } = defineProps<{ payload: EnrollmentEmailPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\n// Each translation places its link inside the sentence, where `{link}` is.\n// The waitlist letter already says Cloud is open, so its beta paragraph starts at the beta.\nconst beta = payload.waitlist ? t.invitationWaitlistBeta : t.invitationBeta\nconst [beforeIssue = '', afterIssue = ''] = beta.split('{link}')\nconst [beforeDownload = '', afterDownload = ''] = t.invitationDesktop.split('{link}')\n</script>\n\n<template>\n <BrandEmail\n :preview=\"payload.waitlist ? t.invitationWaitlistPreview : t.invitationPreview\"\n :heading=\"t.invitationHeading\"\n :action=\"{ label: t.invitationAction, url: payload.actionURL }\"\n >\n <EmailText v-if=\"payload.waitlist\">{{ t.invitationWaitlistThanks }}</EmailText>\n <template v-else>\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.invitationThanks }}</EmailText>\n </template>\n <EmailText>\n {{ beforeIssue\n }}<Link :href=\"BUG_REPORT_URL\" :style=\"styles.link\">{{ t.invitationIssueLink }}</Link\n >{{ afterIssue }}\n </EmailText>\n <EmailText>\n {{ beforeDownload\n }}<Link :href=\"DESKTOP_BETA_URL\" :style=\"styles.link\">{{ t.invitationDownloadLink }}</Link\n >{{ afterDownload }}\n </EmailText>\n <template #signature>\n {{ t.invitationSignatureName }}<br />\n {{ t.invitationSignatureRole }}\n </template>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { AdminEnrollmentNotificationPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\n/** To administrators: someone asked for access, in their own words. */\nconst { payload } = defineProps<{ payload: AdminEnrollmentNotificationPayload }>()\n\nconst { t } = useEmailLocalization()\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.enrollmentNotificationPreview({ email: payload.requesterEmail })\"\n :heading=\"t.enrollmentNotificationHeading\"\n :action=\"{ label: t.enrollmentNotificationAction, url: payload.actionURL }\"\n >\n <EmailText>\n {{ t.enrollmentNotification({ name: payload.requesterName, email: payload.requesterEmail }) }}\n </EmailText>\n <EmailText>{{ payload.reason }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { EnrollmentEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** Where an access request stands, to the person who made it. */\nconst { kind, payload } = defineProps<{\n kind: 'requested' | 'approved' | 'rejected' | 'revoked'\n payload: EnrollmentEmailPayload\n}>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\nconst copy = {\n requested: {\n preview: t.enrollmentRequestedPreview,\n heading: t.enrollmentRequestedHeading,\n message: t.enrollmentRequested,\n action: t.openCloud\n },\n approved: {\n preview: t.enrollmentApprovedPreview,\n heading: t.enrollmentApprovedHeading,\n message: t.enrollmentApproved,\n action: t.enrollmentApprovedAction\n },\n rejected: {\n preview: t.enrollmentRejectedPreview,\n heading: t.enrollmentRejectedHeading,\n message: t.enrollmentRejected,\n action: t.enrollmentRejectedAction\n },\n revoked: {\n preview: t.enrollmentRevokedPreview,\n heading: t.enrollmentRevokedHeading,\n message: t.enrollmentRevoked,\n action: t.enrollmentRevokedAction\n }\n}[kind]\n</script>\n\n<template>\n <BrandEmail\n :preview=\"copy.preview\"\n :heading=\"copy.heading\"\n :action=\"{ label: copy.action, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ copy.message }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { NewSignInPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** An account was signed in to from somewhere it never was before. */\nconst { payload } = defineProps<{ payload: NewSignInPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t, dateTime } = localization\n\nfunction signedInWith(): string {\n if (payload.desktop) return t.newSignInApp\n const { browser, system } = payload\n if (browser && system) return t.newSignInBrowser({ browser, system })\n return browser ?? system ?? t.newSignInUnknownBrowser\n}\n\nconst device = signedInWith()\nconst date = dateTime(payload.signedInAt)\nconst message = payload.ipAddress\n ? t.newSignInFrom({ device, address: payload.ipAddress, date })\n : t.newSignIn({ device, date })\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.newSignInPreview({ device })\"\n :heading=\"t.newSignInHeading\"\n :action=\"{ label: t.reviewSessions, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ message }}</EmailText>\n <EmailText>{{ t.newSignInNotYou }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { AuthenticationEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\nconst { payload } = defineProps<{ payload: AuthenticationEmailPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.passwordChangedPreview\"\n :heading=\"t.passwordChangedHeading\"\n :action=\"{ label: t.openCloud, url: payload.actionURL ?? '#' }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.passwordChanged }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { AuthenticationEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\nconst { payload } = defineProps<{ payload: AuthenticationEmailPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.passwordResetPreview\"\n :heading=\"t.passwordResetHeading\"\n :action=\"{ label: t.passwordResetAction, url: payload.actionURL ?? '#' }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.passwordReset }}</EmailText>\n <template #note>{{ t.passwordResetNote }}</template>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { StorageLimitReachedPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/** The account holds all the storage its plan includes, so its workspaces are read-only. */\nconst { payload } = defineProps<{ payload: StorageLimitReachedPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t, storage } = localization\nconst amounts = { used: storage(payload.usedBytes), limit: storage(payload.limitBytes) }\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.storageFullPreview(amounts)\"\n :heading=\"t.storageFullHeading\"\n :action=\"{\n label: payload.upgradable ? t.storageFullAction : t.openCloud,\n url: payload.actionURL\n }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ t.storageFull(amounts) }}</EmailText>\n <EmailText>{{ payload.upgradable ? t.storageFullUpgrade : t.storageFullFreeSpace }}</EmailText>\n </BrandEmail>\n</template>\n","import { isValid as isBase64 } from 'js-base64'\nimport * as v from 'valibot'\n\n/**\n * Where an account stands: it may use the server, waits for an administrator, was refused or had\n * its access taken back, has to prove its second step in this session, as after signing in through\n * a linked account such as Google, or has to accept the server's current terms first.\n */\nexport const cloudAccountStateSchema = v.picklist([\n 'active',\n 'pending',\n 'rejected',\n 'revoked',\n 'two-step',\n 'terms'\n])\nexport const cloudIdentitySchema = v.object({\n userId: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.string(),\n /** The account's picture, such as one a social provider gave it. */\n image: v.optional(v.nullable(v.string())),\n deploymentRole: v.optional(v.picklist(['user', 'admin']))\n})\n\nexport const cloudAccountStatusResponseSchema = v.object({\n user: cloudIdentitySchema,\n state: cloudAccountStateSchema\n})\n\n/** Accepting the server's terms: the version the person read, which must be the current one. */\nexport const cloudTermsAcceptanceSchema = v.object({ version: v.pipe(v.string(), v.minLength(1)) })\n\n/**\n * The providers a person can sign in with besides a password, which this editor has buttons for,\n * in the order it shows them. Every list of providers in Cloud derives from this one.\n */\nexport const CLOUD_SOCIAL_PROVIDERS = ['google', 'apple', 'github'] as const\nexport const cloudSocialProviderSchema = v.picklist(CLOUD_SOCIAL_PROVIDERS)\nexport type CloudSocialProvider = v.InferOutput<typeof cloudSocialProviderSchema>\n/** Each provider's name, as its owner writes it in every language. */\nexport const CLOUD_SOCIAL_PROVIDER_NAMES: Record<CloudSocialProvider, string> = {\n google: 'Google',\n apple: 'Apple',\n github: 'GitHub'\n}\nexport const cloudAuthenticationProviderSchema = v.picklist([\n 'credential',\n ...CLOUD_SOCIAL_PROVIDERS\n])\nexport const cloudAuthenticationMethodSchema = v.object({\n id: v.string(),\n provider: cloudAuthenticationProviderSchema,\n createdAt: v.string(),\n canUnlink: v.boolean()\n})\n\n/** Whether this editor knows `provider`, so a newer server's other providers can be left out. */\nexport function isKnownSocialProvider(provider: string): provider is CloudSocialProvider {\n return (CLOUD_SOCIAL_PROVIDERS as readonly string[]).includes(provider)\n}\n\n/** Whether `provider` is a way to sign in this editor knows: a password or a known provider. */\nexport function isKnownAuthenticationProvider(\n provider: string\n): provider is CloudAuthenticationProvider {\n return provider === 'credential' || isKnownSocialProvider(provider)\n}\n\n/**\n * A newer server may list a provider this editor has no words or button for: those entries are\n * left out rather than failing the whole response, and anything else malformed still fails.\n */\nexport const cloudAuthenticationMethodsResponseSchema = v.object({\n methods: v.pipe(\n v.array(v.looseObject({ provider: v.string() })),\n v.filterItems((method) => isKnownAuthenticationProvider(method.provider)),\n v.array(cloudAuthenticationMethodSchema)\n ),\n availableSocialProviders: v.pipe(\n v.array(v.string()),\n v.filterItems(isKnownSocialProvider),\n v.array(cloudSocialProviderSchema)\n )\n})\nexport const cloudPasswordChangeSchema = v.object({\n currentPassword: v.string(),\n newPassword: v.string()\n})\nexport const cloudSocialLinkSchema = v.object({\n provider: cloudSocialProviderSchema,\n callbackURL: v.pipe(v.string(), v.url())\n})\nexport const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) })\nexport const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() })\nexport const accountSecurityErrorCodeSchema = v.picklist([\n 'current_password_invalid',\n 'password_too_short',\n 'password_too_long',\n 'last_authentication_method',\n 'session_not_fresh',\n 'authentication_method_failed',\n 'code_invalid',\n 'email_unchanged',\n 'email_change_unavailable',\n 'current_session',\n 'picture_invalid',\n 'account_sole_admin',\n 'last_admin_required',\n 'terms_changed'\n])\nexport const accountSecurityErrorResponseSchema = v.object({\n error: v.object({ code: accountSecurityErrorCodeSchema })\n})\n\nexport const cloudMFAStatusSchema = v.object({\n required: v.boolean(),\n enabled: v.boolean(),\n totpEnabled: v.boolean(),\n assured: v.boolean(),\n totpAvailable: v.boolean(),\n passkeysAvailable: v.boolean(),\n recoveryCodesAvailable: v.boolean()\n})\nexport const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema })\nexport const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) })\nexport const cloudMFAEnableResponseSchema = v.object({\n totpURI: v.string(),\n backupCodes: v.array(v.string())\n})\nexport const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) })\nexport const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) })\nexport const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) })\nexport const cloudPasskeySchema = v.object({\n id: v.string(),\n name: v.nullish(v.string()),\n createdAt: v.string()\n})\nexport const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) })\nexport const cloudPasskeyDeleteSchema = v.object({ id: v.string() })\n\n/**\n * Personal access tokens: an account's own credentials for scripts and CI, sent as\n * `Authorization: Bearer <token>`. A token acts as its account on the document API only; it never\n * changes how the account is reached, makes other tokens, or reaches administration.\n */\nexport const CLOUD_ACCESS_TOKEN_PREFIX = 'opc_'\nexport const CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH = 64\nexport const CLOUD_ACCESS_TOKEN_MAX_DAYS = 365\nexport const cloudAccessTokenSchema = v.object({\n id: v.string(),\n name: v.string(),\n /** The token's first characters, prefix included, to tell tokens apart; never the whole token. */\n start: v.nullable(v.string()),\n createdAt: v.string(),\n expiresAt: v.nullable(v.string()),\n lastUsedAt: v.nullable(v.string())\n})\nexport const cloudAccessTokensResponseSchema = v.object({\n tokens: v.array(cloudAccessTokenSchema)\n})\nexport const cloudAccessTokenCreateSchema = v.object({\n name: v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH)\n ),\n expiresInDays: v.pipe(\n v.number(),\n v.integer(),\n v.minValue(1),\n v.maxValue(CLOUD_ACCESS_TOKEN_MAX_DAYS)\n )\n})\n/** A new token, the only time the whole of it is shown. */\nexport const cloudAccessTokenCreatedResponseSchema = v.object({\n token: v.pipe(v.string(), v.startsWith(CLOUD_ACCESS_TOKEN_PREFIX)),\n accessToken: cloudAccessTokenSchema\n})\nexport const cloudAccessTokenRevokeSchema = v.object({ id: v.pipe(v.string(), v.minLength(1)) })\n\nexport function parseCloudAccessTokenCreate(input: unknown) {\n return v.parse(cloudAccessTokenCreateSchema, input)\n}\nexport function parseCloudAccessTokenRevoke(input: unknown) {\n return v.parse(cloudAccessTokenRevokeSchema, input)\n}\n\nexport function parseCloudTermsAcceptance(input: unknown) {\n return v.parse(cloudTermsAcceptanceSchema, input)\n}\nexport function parseCloudMFAEnable(input: unknown) {\n return v.parse(cloudMFAEnableSchema, input)\n}\nexport function parseCloudMFAVerify(input: unknown) {\n return v.parse(cloudMFAVerifySchema, input)\n}\nexport function parseCloudPasskeyDelete(input: unknown) {\n return v.parse(cloudPasskeyDeleteSchema, input)\n}\nexport function parseCloudPasswordChange(input: unknown) {\n return v.parse(cloudPasswordChangeSchema, input)\n}\nexport function parseCloudSocialLink(input: unknown) {\n return v.parse(cloudSocialLinkSchema, input)\n}\nexport function parseCloudUnlinkAuthenticationMethod(input: unknown) {\n return v.parse(cloudUnlinkAuthenticationMethodSchema, input)\n}\n\nexport const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) })\n\n/** Who an account belongs to, as the portal shows it. */\nexport const cloudPersonSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n /** The address of the account's picture, which the server serves; null shows initials. */\n image: v.nullable(v.string())\n})\n/** What a person can see and change about themselves. */\nexport const cloudProfileSchema = v.object({\n ...cloudPersonSchema.entries,\n createdAt: v.string(),\n /** Whether the server can send the verification a new email address needs. */\n emailChangeAvailable: v.boolean()\n})\nexport const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema })\nexport const cloudProfileUpdateSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\n/** The largest picture an account may upload, once the page has cropped and shrunk it. */\nexport const CLOUD_PICTURE_MAX_BYTES = 256 * 1024\n/** The width and height a page shrinks a picture to before it uploads it. */\nexport const CLOUD_PICTURE_SIZE = 256\nexport const cloudPictureUploadSchema = v.object({\n /** The picture's PNG or JPEG bytes, in Base64. */\n data: v.pipe(\n v.string(),\n v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4),\n v.check((value) => isBase64(value))\n )\n})\n/** The address the account's picture is now served from. */\nexport const cloudPictureResponseSchema = v.object({ image: v.string() })\nexport const cloudEmailChangeSchema = v.object({\n newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n callbackURL: v.pipe(v.string(), v.url())\n})\n\n/** How a sign-in was made: the method it used, or the desktop app's approved code. */\nconst SIGN_IN_METHODS = [\n 'password',\n ...CLOUD_SOCIAL_PROVIDERS,\n 'passkey',\n 'two-step',\n 'email-link',\n 'desktop',\n 'other'\n] as const\nexport const cloudSignInMethodSchema = v.picklist(SIGN_IN_METHODS)\n/** A method a newer server names that this editor does not know reads as `other`; a value that is\n * not a method name at all still fails. */\nconst signInMethodResponseSchema = v.pipe(\n v.string(),\n v.transform((method) => (v.is(cloudSignInMethodSchema, method) ? method : ('other' as const)))\n)\nexport const cloudAccountSessionSchema = v.object({\n id: v.string(),\n /** The session this request was made with. */\n current: v.boolean(),\n method: v.nullable(signInMethodResponseSchema),\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string(),\n lastActiveAt: v.string(),\n expiresAt: v.string()\n})\nexport const cloudAccountSessionsResponseSchema = v.object({\n sessions: v.array(cloudAccountSessionSchema)\n})\nexport const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) })\nexport const cloudSignInSchema = v.object({\n id: v.string(),\n method: signInMethodResponseSchema,\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string()\n})\nexport const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) })\n\n/** A workspace an account deletion reads: one it would delete, or one that stops it. */\nexport const cloudAccountDeletionWorkspaceSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string()\n})\n/** A document the account would lose, which Download all saves first. */\nexport const cloudAccountDeletionDocumentSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n workspaceName: v.string()\n})\n/**\n * What deleting the account takes: the workspaces only it belongs to, which go with their\n * documents; the ones it leaves to their other members; the ones it alone administers for other\n * members, which stop the deletion until it makes someone else an admin; and the documents it\n * would lose, those workspaces' and the ones it created in workspaces it leaves.\n */\nexport const cloudAccountDeletionSchema = v.object({\n /** The account is the deployment's only administrator, which also stops the deletion. */\n lastAdministrator: v.boolean(),\n blockedBy: v.array(cloudAccountDeletionWorkspaceSchema),\n deletes: v.array(cloudAccountDeletionWorkspaceSchema),\n leaves: v.array(cloudAccountDeletionWorkspaceSchema),\n documents: v.array(cloudAccountDeletionDocumentSchema)\n})\nexport const cloudAccountDeletionResponseSchema = v.object({\n deletion: cloudAccountDeletionSchema\n})\n/** The password, for a session that signed in too long ago to delete the account on its own. */\nexport const cloudAccountDeleteSchema = v.object({\n password: v.optional(v.pipe(v.string(), v.minLength(1)))\n})\n\nexport function parseCloudProfileUpdate(input: unknown) {\n return v.parse(cloudProfileUpdateSchema, input)\n}\nexport function parseCloudPictureUpload(input: unknown) {\n return v.parse(cloudPictureUploadSchema, input)\n}\nexport function parseCloudEmailChange(input: unknown) {\n return v.parse(cloudEmailChangeSchema, input)\n}\nexport function parseCloudAccountDelete(input: unknown) {\n return v.parse(cloudAccountDeleteSchema, input)\n}\nexport function parseCloudSessionRevoke(input: unknown) {\n return v.parse(cloudSessionRevokeSchema, input)\n}\n\nexport type AccountSecurityErrorCode = v.InferOutput<typeof accountSecurityErrorCodeSchema>\nexport type CloudAuthenticationProvider = v.InferOutput<typeof cloudAuthenticationProviderSchema>\nexport type CloudAuthenticationMethod = v.InferOutput<typeof cloudAuthenticationMethodSchema>\nexport type CloudAuthenticationMethods = v.InferOutput<\n typeof cloudAuthenticationMethodsResponseSchema\n>\n\nexport type CloudAccountStatus = v.InferOutput<typeof cloudAccountStatusResponseSchema>\nexport type CloudProfile = v.InferOutput<typeof cloudProfileSchema>\nexport type CloudAccessToken = v.InferOutput<typeof cloudAccessTokenSchema>\nexport type CloudAccessTokenCreate = v.InferOutput<typeof cloudAccessTokenCreateSchema>\nexport type CloudSignInMethod = v.InferOutput<typeof cloudSignInMethodSchema>\nexport type CloudAccountSession = v.InferOutput<typeof cloudAccountSessionSchema>\nexport type CloudSignIn = v.InferOutput<typeof cloudSignInSchema>\nexport type CloudAccountDeletion = v.InferOutput<typeof cloudAccountDeletionSchema>\n","import * as v from 'valibot'\n\n/** Whether `tag` is a well-formed BCP 47 language tag: `de`, `pt-BR`, `zh-Hant-TW`. */\nfunction isLanguageTag(tag: string): boolean {\n try {\n return Intl.getCanonicalLocales(tag).length === 1\n } catch {\n return false\n }\n}\n\n/**\n * A language as the app names it, which the server writes email in when it has that language, or\n * the nearest it has, and otherwise in English.\n */\nexport const cloudLanguageTagSchema = v.pipe(\n v.string(),\n v.maxLength(35),\n v.check(isLanguageTag, 'Not a language tag')\n)\n\n/** The language an account's email is written in, as the app last said it uses. */\nexport const cloudLocaleUpdateSchema = v.object({ locale: cloudLanguageTagSchema })\n\nexport function parseCloudLocaleUpdate(input: unknown) {\n return v.parse(cloudLocaleUpdateSchema, input)\n}\n","import type { Hono } from 'hono'\nimport type { BlankEnv, BlankInput } from 'hono/types'\nimport * as v from 'valibot'\n\nimport type { JSONRoute } from './routes'\n\n/**\n * The contract between editors, Cloud, and the services Cloud advertises: AI models today, and\n * other paid capabilities such as image generation and search as they arrive. Cloud only\n * advertises the service and signs short-lived tokens for it; the service, official or\n * self-hosted, calls the providers and keeps the credit wallet. It is versioned apart from the\n * Cloud protocol so a service can change without a Cloud release.\n */\nexport const CLOUD_SERVICES_CONTRACT_VERSION = '1' as const\n/** The `aud` of every token Cloud signs for its services. */\nexport const CLOUD_SERVICES_TOKEN_AUDIENCE = 'openpencil-services' as const\n/** Where Cloud publishes the public keys a service verifies its tokens with. */\nexport const CLOUD_SERVICES_JWKS_PATH = '/.well-known/jwks.json' as const\n\n/**\n * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat\n * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.\n */\nexport const CLOUD_SERVICES_API_PATHS = {\n base: '/v1',\n chatCompletions: '/v1/chat/completions',\n catalog: '/v1/catalog',\n wallet: '/v1/wallet',\n usage: '/v1/usage',\n search: '/v1/search'\n} as const\n\nconst urlSchema = v.pipe(v.string(), v.url())\nconst creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\nexport const cloudServicesDiscoverySchema = v.object({\n endpoint: urlSchema,\n contractVersion: v.literal(CLOUD_SERVICES_CONTRACT_VERSION)\n})\nexport type CloudServicesDiscovery = v.InferOutput<typeof cloudServicesDiscoverySchema>\n\nexport const createServicesTokenSchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) })\nexport type CreateServicesTokenInput = v.InferOutput<typeof createServicesTokenSchema>\n\nexport function parseCreateServicesToken(input: unknown): CreateServicesTokenInput {\n return v.parse(createServicesTokenSchema, input)\n}\n\nexport const servicesTokenSchema = v.object({\n token: v.pipe(v.string(), v.minLength(1)),\n expiresAt: v.pipe(v.string(), v.isoTimestamp())\n})\nexport type ServicesToken = v.InferOutput<typeof servicesTokenSchema>\n\n/** What a service may rely on once a token's signature, issuer, audience, and expiry check. */\nexport const servicesTokenClaimsSchema = v.object({\n iss: urlSchema,\n aud: v.literal(CLOUD_SERVICES_TOKEN_AUDIENCE),\n sub: v.pipe(v.string(), v.minLength(1)),\n workspaceId: v.pipe(v.string(), v.uuid()),\n /**\n * The account whose credits the request spends: the workspace's owner, whose allowance every\n * workspace they own shares.\n */\n accountId: v.pipe(v.string(), v.minLength(1)),\n /** Credits the owner's plan grants each month; `null` when Cloud sets no allowance. */\n monthlyCreditAllowance: v.nullable(creditsSchema),\n iat: v.pipe(v.number(), v.integer()),\n exp: v.pipe(v.number(), v.integer())\n})\nexport type ServicesTokenClaims = v.InferOutput<typeof servicesTokenClaimsSchema>\n\nexport const chatModelSchema = v.object({\n id: v.pipe(v.string(), v.minLength(1)),\n label: v.pipe(v.string(), v.minLength(1)),\n /** Credits per million input and output tokens. */\n creditsPerMillionInputTokens: creditsSchema,\n creditsPerMillionOutputTokens: creditsSchema,\n contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),\n capabilities: v.object({ reasoning: v.boolean(), vision: v.boolean(), tools: v.boolean() })\n})\nexport type ChatModel = v.InferOutput<typeof chatModelSchema>\n\n/** What one web search costs; a service without search leaves it out of its catalog. */\nexport const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema })\nexport type SearchPricing = v.InferOutput<typeof searchPricingSchema>\n\nconst modelIDSchema = v.pipe(v.string(), v.minLength(1))\n\n/**\n * The model the service recommends for each of the editor's roles: Design runs the chat, Review\n * critiques designs, Fast does quick tasks such as naming conversations, and Vision reads images.\n * An editor signed in to the service with no model of its own yet sets itself up with them, so\n * nobody has to choose one. Vision `null` recommends none, and the editor leaves it unassigned.\n */\nexport const roleModelsSchema = v.object({\n design: modelIDSchema,\n review: modelIDSchema,\n fast: modelIDSchema,\n vision: v.nullable(modelIDSchema)\n})\nexport type RoleModels = v.InferOutput<typeof roleModelsSchema>\n\nexport const serviceCatalogSchema = v.pipe(\n v.object({\n models: v.array(chatModelSchema),\n defaultModelID: modelIDSchema,\n /**\n * Absent from a service that predates it, or whose default model can't run the chat. Editors\n * then use `defaultModelID` for every role, except Vision when that model reads no images,\n * and set nothing up when it calls no tools.\n */\n roleModels: v.optional(roleModelsSchema),\n search: v.optional(searchPricingSchema)\n }),\n // Every recommendation names a model the catalog lists and can do its role: Design and Fast\n // call tools, and Vision reads images. An editor then never sets up a role it can't run.\n v.check(({ models, roleModels }) => {\n if (!roleModels) return true\n const can = (id: string | null, capability: 'tools' | 'vision' | null) => {\n if (id === null) return true\n const model = models.find((candidate) => candidate.id === id)\n return model !== undefined && (capability === null || model.capabilities[capability])\n }\n return (\n can(roleModels.design, 'tools') &&\n can(roleModels.review, null) &&\n can(roleModels.fast, 'tools') &&\n can(roleModels.vision, 'vision')\n )\n }, 'A recommended model is not in the catalog or cannot do its role')\n)\nexport type ServiceCatalog = v.InferOutput<typeof serviceCatalogSchema>\n\nexport const creditBucketSchema = v.object({\n kind: v.picklist(['allowance', 'purchased', 'grant']),\n remaining: creditsSchema,\n expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))\n})\nexport type CreditBucket = v.InferOutput<typeof creditBucketSchema>\n\n/**\n * A service records a request's charge before the request's answer ends, so a wallet read after\n * an answer includes what it cost.\n */\nexport const creditWalletSchema = v.object({\n /** Credits left to spend; `null` when the service sets no limit. */\n balance: v.nullable(creditsSchema),\n /** Spent first to last. */\n buckets: v.array(creditBucketSchema)\n})\nexport type CreditWallet = v.InferOutput<typeof creditWalletSchema>\n\nexport const usageEntrySchema = v.object({\n id: v.pipe(v.string(), v.minLength(1)),\n createdAt: v.pipe(v.string(), v.isoTimestamp()),\n kind: v.picklist(['model', 'image', 'search']),\n modelID: v.nullable(v.string()),\n userId: v.pipe(v.string(), v.minLength(1)),\n credits: creditsSchema\n})\nexport type UsageEntry = v.InferOutput<typeof usageEntrySchema>\n\n/** The most results one search returns. */\nexport const MAX_SEARCH_RESULTS = 10\n/** The longest query a search takes, in characters. */\nexport const MAX_SEARCH_QUERY_LENGTH = 1_000\n\nexport const searchRequestSchema = v.object({\n query: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_SEARCH_QUERY_LENGTH)),\n numResults: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(MAX_SEARCH_RESULTS)),\n 5\n )\n})\nexport type SearchRequestInput = v.InferInput<typeof searchRequestSchema>\nexport type SearchRequest = v.InferOutput<typeof searchRequestSchema>\n\nexport function parseSearchRequest(input: unknown): SearchRequest {\n return v.parse(searchRequestSchema, input)\n}\n\n/** One page a search found, with the part of its text that answers the query. */\nexport const searchResultSchema = v.object({\n // Only web pages: editors open it when clicked, so a `javascript:` URL must never pass.\n url: v.pipe(urlSchema, v.regex(/^https?:\\/\\//i, 'A search result links to an HTTP(S) page')),\n title: v.string(),\n publishedAt: v.nullable(v.pipe(v.string(), v.isoTimestamp())),\n author: v.nullable(v.string()),\n text: v.string()\n})\nexport type SearchResult = v.InferOutput<typeof searchResultSchema>\n\nexport const searchResponseSchema = v.object({ results: v.array(searchResultSchema) })\nexport type SearchResponse = v.InferOutput<typeof searchResponseSchema>\n\nexport const usageQuerySchema = v.object({\n cursor: v.optional(v.pipe(v.string(), v.minLength(1)))\n})\nexport type UsageQuery = v.InferOutput<typeof usageQuerySchema>\n\nexport function parseUsageQuery(input: unknown): UsageQuery {\n return v.parse(usageQuerySchema, input)\n}\n\nexport const usagePageSchema = v.object({\n entries: v.array(usageEntrySchema),\n next: v.nullable(v.string())\n})\nexport type UsagePage = v.InferOutput<typeof usagePageSchema>\n\n/** Errors a service answers with, beside the upstream provider's own. */\nexport const serviceErrorCodeSchema = v.picklist([\n 'invalid_request',\n 'unauthorized',\n 'insufficient_credits',\n 'model_not_allowed',\n 'capability_unavailable',\n 'rate_limited'\n])\nexport type ServiceErrorCode = v.InferOutput<typeof serviceErrorCodeSchema>\n\nexport const serviceErrorSchema = v.object({\n error: v.object({\n code: serviceErrorCodeSchema,\n message: v.optional(v.string()),\n /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */\n resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))\n })\n})\nexport type ServiceError = v.InferOutput<typeof serviceErrorSchema>\n\nexport const SERVICE_ERROR_STATUS = {\n invalid_request: 400,\n unauthorized: 401,\n insufficient_credits: 402,\n model_not_allowed: 403,\n /** A capability, such as search, the service does not offer. */\n capability_unavailable: 404,\n rate_limited: 429\n} as const satisfies Record<ServiceErrorCode, number>\n\n/**\n * Every route a service answers besides chat completions, which OpenAI-compatible clients call\n * themselves. Editors build a typed client from it with Hono's `hc`; a service's own app must\n * match it, so the two cannot drift apart.\n */\nexport type CloudServicesSchema = JSONRoute<\n 'get',\n typeof CLOUD_SERVICES_API_PATHS.catalog,\n BlankInput,\n ServiceCatalog\n> &\n JSONRoute<'get', typeof CLOUD_SERVICES_API_PATHS.wallet, BlankInput, CreditWallet> &\n JSONRoute<'get', typeof CLOUD_SERVICES_API_PATHS.usage, { query: UsageQuery }, UsagePage> &\n JSONRoute<\n 'post',\n typeof CLOUD_SERVICES_API_PATHS.search,\n { json: SearchRequestInput },\n SearchResponse\n >\n\nexport type CloudServicesAPI = Hono<BlankEnv, CloudServicesSchema>\n\n/**\n * Whether a bearer token may travel to `url`: over HTTPS, or in the clear only to a loopback\n * address, for development. Only literal addresses count, since a name such as `localhost` is\n * whatever the resolver answers. Services and billing tokens act as the account until they expire.\n */\nexport function sendsTokenSafely(url: string | URL): boolean {\n const { protocol, hostname } = new URL(url)\n if (protocol === 'https:') return true\n if (protocol !== 'http:') return false\n return hostname === '[::1]' || /^127(\\.\\d{1,3}){3}$/.test(hostname)\n}\n","import type { Hono } from 'hono'\nimport type { BlankEnv, BlankInput } from 'hono/types'\nimport * as v from 'valibot'\n\nimport type { JSONRoute } from './routes'\n\n/**\n * The contract between Cloud, its editors, and the billing service a deployment advertises: what\n * plans and credit packs it sells, and where an account buys them or manages what it has. Cloud\n * only advertises the service and signs short-lived tokens for an account; the service talks to\n * the payment provider, and sets the account's entitlements and credits as it is paid.\n */\nexport const CLOUD_BILLING_CONTRACT_VERSION = '1' as const\n/**\n * The `aud` of the tokens Cloud signs for its billing service, with the services' signing key,\n * whose public keys it publishes at `CLOUD_SERVICES_JWKS_PATH`.\n */\nexport const CLOUD_BILLING_TOKEN_AUDIENCE = 'openpencil-billing' as const\n\n/**\n * The page of a Cloud server where the signed-in person sees their plan, buys a plan or credits,\n * and manages what they pay for; editors link to it whenever the server advertises billing.\n */\nexport const CLOUD_ACCOUNT_PLAN_PATH = '/account/plan' as const\n\n/**\n * The plan page with billing's own pages opening at once: where billing sends someone whose\n * session there ended, so Cloud signs them in to billing again.\n */\nexport const CLOUD_ACCOUNT_BILLING_PATH = `${CLOUD_ACCOUNT_PLAN_PATH}?open=billing` as const\n\n/**\n * The billing service's own pages, below the discovered `endpoint`: where Cloud's plan page sends\n * the signed-in person, posting a billing token as the form field `token` to `session`, and the\n * public pricing page. The service answers that post with `303 See Other`, never `307` or `308`,\n * which a browser follows by posting the same body, the token, again to wherever they point.\n */\nexport const CLOUD_BILLING_PAGE_PATHS = {\n session: '/session',\n pricing: '/pricing'\n} as const\n\n/**\n * Where the billing service answers, below the discovered `endpoint`. Cloud posts to `seats`,\n * with a billing token for the account as its bearer, whenever the people who can edit in that\n * account's workspaces change; the service reads the count from Cloud's internal API.\n */\nexport const CLOUD_BILLING_API_PATHS = {\n base: '/v1',\n catalog: '/v1/catalog',\n seats: '/v1/seats',\n account: '/v1/account',\n checkout: '/v1/checkout',\n portal: '/v1/portal'\n} as const\n\nconst urlSchema = v.pipe(v.string(), v.url())\nconst idSchema = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/))\nconst centsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\nconst bytesSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\nconst creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\n/**\n * What an account without a plan has: the deployment's free plan, which a pricing page compares\n * the plans with.\n */\nexport const billingFreePlanSchema = v.object({\n /** The storage an account may use, or `null` for no limit. */\n storageBytes: v.nullable(bytesSchema),\n /** Whether the free plan includes services, such as AI and search. */\n services: v.boolean(),\n /** Credits granted each month with services, or `null` for no monthly limit. */\n monthlyCredits: v.nullable(creditsSchema)\n})\nexport type BillingFreePlan = v.InferOutput<typeof billingFreePlanSchema>\n\nexport const cloudBillingDiscoverySchema = v.object({\n endpoint: urlSchema,\n contractVersion: v.literal(CLOUD_BILLING_CONTRACT_VERSION),\n freePlan: v.optional(billingFreePlanSchema)\n})\nexport type CloudBillingDiscovery = v.InferOutput<typeof cloudBillingDiscoverySchema>\n\nexport const billingTokenSchema = v.object({\n token: v.pipe(v.string(), v.minLength(1)),\n expiresAt: v.pipe(v.string(), v.isoTimestamp())\n})\nexport type BillingToken = v.InferOutput<typeof billingTokenSchema>\n\n/**\n * What the billing service may rely on once a token's signature, issuer, audience, and expiry\n * check. The account is the signed-in user, who buys and manages only their own plan.\n */\nexport const billingTokenClaimsSchema = v.object({\n iss: urlSchema,\n aud: v.literal(CLOUD_BILLING_TOKEN_AUDIENCE),\n /** The account: the Cloud user whose plan and credits these are. */\n sub: v.pipe(v.string(), v.minLength(1)),\n /** Where the payment provider sends receipts and invoices. */\n email: v.pipe(v.string(), v.email()),\n iat: v.pipe(v.number(), v.integer()),\n exp: v.pipe(v.number(), v.integer())\n})\nexport type BillingTokenClaims = v.InferOutput<typeof billingTokenClaimsSchema>\n\nconst seatCountSchema = v.pipe(v.number(), v.integer(), v.minValue(1))\n\n/**\n * A plan priced by the seat: everyone who can edit in the account's workspaces takes one, and the\n * account pays for at least `minimum`. Every seat costs the price of the tier its count reaches,\n * and adds its storage and credits to what the account shares.\n */\nexport const billingSeatPricingSchema = v.object({\n minimum: seatCountSchema,\n /** From the fewest seats up: the first from 1, each later one from more seats. */\n tiers: v.pipe(\n v.array(v.object({ fromSeats: seatCountSchema, unitPriceCents: centsSchema })),\n v.minLength(1),\n v.check((tiers) => tiers[0]?.fromSeats === 1, 'The first seat tier starts at one seat'),\n v.check(\n (tiers) =>\n tiers.every(\n (tier, index) => index === 0 || tier.fromSeats > (tiers[index - 1]?.fromSeats ?? 0)\n ),\n 'Seat tiers start at more seats each'\n )\n ),\n storageBytesPerSeat: bytesSchema,\n monthlyCreditsPerSeat: creditsSchema\n})\nexport type BillingSeatPricing = v.InferOutput<typeof billingSeatPricingSchema>\n\n/**\n * A plan an account subscribes to, billed every month in US dollars before tax. A plan priced by\n * the seat states its price, storage, and credits at its minimum, so an editor that reads no\n * `seats` still shows what it starts at.\n */\nexport const billingPlanSchema = v.object({\n id: idSchema,\n name: v.pipe(v.string(), v.minLength(1)),\n monthlyPriceCents: centsSchema,\n storageBytes: bytesSchema,\n monthlyCredits: creditsSchema,\n seats: v.optional(billingSeatPricingSchema)\n})\nexport type BillingPlan = v.InferOutput<typeof billingPlanSchema>\n\n/** Credits an account on a plan buys once, in US dollars before tax. */\nexport const creditPackSchema = v.object({\n id: idSchema,\n credits: creditsSchema,\n priceCents: centsSchema,\n /** How long the credits last from purchase. */\n validDays: v.pipe(v.number(), v.integer(), v.minValue(1))\n})\nexport type CreditPack = v.InferOutput<typeof creditPackSchema>\n\n/** What the service sells; an account without a plan has its deployment's free entitlements. */\nexport const billingCatalogSchema = v.object({\n plans: v.array(billingPlanSchema),\n creditPacks: v.array(creditPackSchema)\n})\nexport type BillingCatalog = v.InferOutput<typeof billingCatalogSchema>\n\n/**\n * The account's subscription as the payment provider holds it, or `null` without one. A\n * `past_due` plan keeps its entitlements while payment is retried.\n */\nexport const billingAccountSchema = v.object({\n subscription: v.nullable(\n v.object({\n planId: idSchema,\n status: v.picklist(['active', 'past_due']),\n /** When the current period ends: the next charge, or the end of a cancelled plan. */\n currentPeriodEnd: v.pipe(v.string(), v.isoTimestamp()),\n /** Whether the plan ends at `currentPeriodEnd` instead of renewing. */\n cancelsAtPeriodEnd: v.boolean()\n })\n )\n})\nexport type BillingAccount = v.InferOutput<typeof billingAccountSchema>\n\n/** What to buy: a plan to subscribe to, or a credit pack. */\nexport const checkoutRequestSchema = v.union([\n v.object({ planId: idSchema }),\n v.object({ creditPackId: idSchema })\n])\nexport type CheckoutRequest = v.InferOutput<typeof checkoutRequestSchema>\n\n/** Where to send the person: the payment provider's checkout or account portal. */\nexport const billingRedirectSchema = v.object({\n // Only the payment provider's own pages, never a scheme a browser would run.\n url: v.pipe(urlSchema, v.regex(/^https:\\/\\//i, 'Billing sends people to an HTTPS page'))\n})\nexport type BillingRedirect = v.InferOutput<typeof billingRedirectSchema>\n\nexport const billingErrorCodeSchema = v.picklist([\n 'invalid_request',\n 'unauthorized',\n /** A credit pack for an account without a plan, or a plan it already has. */\n 'not_allowed',\n 'provider_unavailable'\n])\nexport type BillingErrorCode = v.InferOutput<typeof billingErrorCodeSchema>\n\n/** The HTTP status billing answers each error with. */\nexport const BILLING_ERROR_STATUS = {\n invalid_request: 400,\n unauthorized: 401,\n not_allowed: 409,\n provider_unavailable: 502\n} as const satisfies Record<BillingErrorCode, number>\n\nexport const billingErrorSchema = v.object({\n error: v.object({ code: billingErrorCodeSchema, message: v.optional(v.string()) })\n})\nexport type BillingError = v.InferOutput<typeof billingErrorSchema>\n\n/** The billing service's routes, for a typed Hono client (`hc<CloudBillingAPI>`). */\nexport type CloudBillingSchema = JSONRoute<\n 'get',\n typeof CLOUD_BILLING_API_PATHS.catalog,\n BlankInput,\n BillingCatalog\n> &\n JSONRoute<'get', typeof CLOUD_BILLING_API_PATHS.account, BlankInput, BillingAccount> &\n JSONRoute<\n 'post',\n typeof CLOUD_BILLING_API_PATHS.checkout,\n { json: CheckoutRequest },\n BillingRedirect\n > &\n JSONRoute<'post', typeof CLOUD_BILLING_API_PATHS.portal, BlankInput, BillingRedirect>\n\nexport type CloudBillingAPI = Hono<BlankEnv, CloudBillingSchema>\n","import * as v from 'valibot'\n\nexport const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1024 * 1024 * 1024\n\nconst checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/))\n\n/** Whether a value is a SHA-256 checksum as the server names stored objects, base64 encoded. */\nexport function isCloudChecksum(value: string): boolean {\n return v.is(checksumSchema, value)\n}\n\n/** The most images one revision, or one request for image uploads, may name. */\nexport const CLOUD_MAX_DOCUMENT_IMAGES = 10_000\n\n/**\n * The most a Cloud API request body may hold; a server refuses anything past it before reading\n * it. Files go to the object store, never through the API, so only lists grow large: a save's\n * images fit with room to spare, and a client commits image uploads, whose part lists can run\n * long, in batches under half of it.\n */\nexport const CLOUD_API_MAX_BODY_BYTES = 8 * 1024 * 1024\n\n/**\n * An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it\n * by, or an older plain name. A client leaves images under other names inside the file.\n */\nexport const CLOUD_IMAGE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/\nconst imageNameSchema = v.pipe(v.string(), v.regex(CLOUD_IMAGE_NAME_PATTERN))\n\nconst objectDownloadSchema = v.object({\n url: v.pipe(v.string(), v.url()),\n method: v.literal('GET'),\n headers: v.record(v.string(), v.string()),\n expiresAt: v.string()\n})\n\n/** An image a stored revision uses, where to download it, and what to check it against. */\nexport const documentImageDownloadSchema = v.object({\n name: imageNameSchema,\n checksum: checksumSchema,\n byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),\n download: objectDownloadSchema\n})\nexport type DocumentImageDownload = v.InferOutput<typeof documentImageDownloadSchema>\n\n/** Where to download an image a document uses, found by its checksum. */\nexport const documentImageLinkSchema = v.object({\n checksum: checksumSchema,\n byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),\n download: objectDownloadSchema\n})\nexport type DocumentImageLink = v.InferOutput<typeof documentImageLinkSchema>\n\n/** The images a live room names, by checksum, that a peer needs links for. */\nexport const requestImageLinksSchema = v.object({\n checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))\n})\nexport type RequestImageLinksInput = v.InferOutput<typeof requestImageLinksSchema>\n\nexport const documentPermissionSchema = v.picklist(['view', 'edit'])\nexport type DocumentPermission = v.InferOutput<typeof documentPermissionSchema>\n\nexport const documentAccessSourceSchema = v.picklist(['owner', 'workspace', 'direct-grant'])\nexport type DocumentAccessSource = v.InferOutput<typeof documentAccessSourceSchema>\n\nexport const documentAccessSchema = v.object({\n permission: documentPermissionSchema,\n canManageSharing: v.boolean(),\n sources: v.array(documentAccessSourceSchema)\n})\nexport type DocumentAccess = v.InferOutput<typeof documentAccessSchema>\n\n/** What a document is: a Figma design or a FigJam board, which the file it stores says too. */\nexport const documentKindSchema = v.picklist(['design', 'board'])\nexport type CloudDocumentKind = v.InferOutput<typeof documentKindSchema>\n\nexport const documentSummarySchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n workspaceId: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n /** A design unless said otherwise; servers from before boards list no kind. */\n kind: v.optional(documentKindSchema, 'design'),\n currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),\n version: v.number(),\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type DocumentSummary = v.InferOutput<typeof documentSummarySchema>\n\n/** A document someone granted the person directly, in a workspace they are not a member of. */\nexport const sharedDocumentSchema = v.object({\n ...documentSummarySchema.entries,\n workspaceName: v.string(),\n permission: documentPermissionSchema,\n sharedBy: v.nullable(v.object({ name: v.string() })),\n sharedAt: v.string()\n})\nexport type SharedDocument = v.InferOutput<typeof sharedDocumentSchema>\n\n/**\n * A document in Trash the person may restore: who deleted it and when, and when it goes for good.\n * `canPurge` says whether they may also delete it for good before then.\n */\nexport const trashedDocumentSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n workspaceId: v.pipe(v.string(), v.uuid()),\n workspaceName: v.string(),\n name: v.string(),\n kind: v.optional(documentKindSchema, 'design'),\n deletedAt: v.string(),\n deletedBy: v.nullable(v.object({ name: v.string() })),\n purgeAt: v.string(),\n canPurge: v.boolean()\n})\nexport type TrashedDocument = v.InferOutput<typeof trashedDocumentSchema>\n\nexport const trashSchema = v.object({ documents: v.array(trashedDocumentSchema) })\n\nexport const documentDownloadSchema = v.object({\n document: documentSummarySchema,\n revisionId: v.pipe(v.string(), v.uuid()),\n byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),\n checksum: checksumSchema,\n contentType: v.string(),\n download: objectDownloadSchema,\n /** The images the stored file leaves out, which a client puts back under their names. */\n images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))\n})\nexport type DocumentDownload = v.InferOutput<typeof documentDownloadSchema>\n\nexport const cloudActorSchema = v.object({\n userId: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.string()\n})\nexport type CloudActorContract = v.InferOutput<typeof cloudActorSchema>\n\nexport const cloudSessionSchema = v.object({ user: cloudActorSchema })\nexport type CloudSession = v.InferOutput<typeof cloudSessionSchema>\n\nexport const workspaceUsageSchema = v.object({\n bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),\n objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),\n documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))\n})\nexport type WorkspaceUsage = v.InferOutput<typeof workspaceUsageSchema>\n\nexport const CLOUD_DOCUMENT_NAME_MAX_LENGTH = 255\n\nexport const createDocumentSchema = v.object({\n id: v.optional(v.pipe(v.string(), v.uuid())),\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(CLOUD_DOCUMENT_NAME_MAX_LENGTH)),\n /** A design unless said otherwise; older clients create only designs. */\n kind: v.optional(documentKindSchema, 'design')\n})\nexport type CreateDocumentInput = v.InferOutput<typeof createDocumentSchema>\n/** A new document as a client sends it, which may leave out its kind to make a design. */\nexport type CreateDocumentRequest = v.InferInput<typeof createDocumentSchema>\n\nexport const createUploadSchema = v.object({\n baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),\n byteSize: v.pipe(\n v.number(),\n v.integer(),\n v.minValue(1),\n v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)\n ),\n checksum: checksumSchema,\n contentType: v.literal('application/octet-stream')\n})\nexport type CreateUploadInput = v.InferOutput<typeof createUploadSchema>\n\nconst imageSizeSchema = v.pipe(\n v.number(),\n v.integer(),\n v.minValue(1),\n v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)\n)\n\n/** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */\nexport const objectUploadSchema = v.variant('kind', [\n v.object({\n kind: v.literal('single'),\n url: v.pipe(v.string(), v.url()),\n method: v.literal('PUT'),\n headers: v.record(v.string(), v.string()),\n expiresAt: v.string()\n }),\n v.object({\n kind: v.literal('multipart'),\n uploadId: v.string(),\n partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),\n parts: v.array(\n v.object({\n partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),\n url: v.pipe(v.string(), v.url()),\n method: v.literal('PUT'),\n headers: v.record(v.string(), v.string())\n })\n ),\n expiresAt: v.string()\n })\n])\nexport type ObjectUploadTarget = v.InferOutput<typeof objectUploadSchema>\n\n/** An upload the server offers for an image the workspace lacks. */\nexport const imageUploadOfferSchema = v.object({\n checksum: checksumSchema,\n uploadId: v.pipe(v.string(), v.uuid()),\n upload: objectUploadSchema\n})\nexport type ImageUploadOffer = v.InferOutput<typeof imageUploadOfferSchema>\n\n/** The images a save will refer to; the server answers with uploads for those it lacks. */\nexport const requestImageUploadsSchema = v.object({\n images: v.pipe(\n v.array(v.object({ checksum: checksumSchema, byteSize: imageSizeSchema })),\n v.minLength(1),\n v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)\n )\n})\nexport type RequestImageUploadsInput = v.InferOutput<typeof requestImageUploadsSchema>\n\nexport const completedUploadPartSchema = v.object({\n partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(10_000)),\n etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))\n})\n\nexport const commitUploadSchema = v.object({\n checksum: checksumSchema,\n /** The document title captured with this revision; omitted by older clients. */\n name: v.optional(createDocumentSchema.entries.name),\n /** What the uploaded file is, which the document takes; omitted by older clients. */\n kind: v.optional(documentKindSchema),\n multipart: v.optional(\n v.object({\n uploadId: v.pipe(v.string(), v.minLength(1)),\n parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(10_000))\n })\n ),\n /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */\n images: v.optional(\n v.pipe(\n v.array(v.object({ name: imageNameSchema, checksum: checksumSchema })),\n v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)\n ),\n []\n )\n})\nexport type CommitUploadInput = v.InferOutput<typeof commitUploadSchema>\n\n/** The image uploads a save asked for, committed together once their bytes are in place. */\nexport const commitImageUploadsSchema = v.object({\n uploads: v.pipe(\n v.array(\n v.object({\n uploadId: v.pipe(v.string(), v.uuid()),\n checksum: checksumSchema,\n multipart: commitUploadSchema.entries.multipart\n })\n ),\n v.minLength(1),\n v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)\n )\n})\nexport type CommitImageUploadsInput = v.InferOutput<typeof commitImageUploadsSchema>\n/** A commit as a client sends it, which may leave out the images a whole file holds itself. */\nexport type CommitUploadRequest = v.InferInput<typeof commitUploadSchema>\n\nexport function parseCreateDocument(input: unknown): CreateDocumentInput {\n return v.parse(createDocumentSchema, input)\n}\n\nexport function parseCreateUpload(input: unknown): CreateUploadInput {\n return v.parse(createUploadSchema, input)\n}\n\nexport function parseRequestImageUploads(input: unknown): RequestImageUploadsInput {\n return v.parse(requestImageUploadsSchema, input)\n}\n\nexport function parseCommitImageUploads(input: unknown): CommitImageUploadsInput {\n return v.parse(commitImageUploadsSchema, input)\n}\n\nexport function parseRequestImageLinks(input: unknown): RequestImageLinksInput {\n return v.parse(requestImageLinksSchema, input)\n}\n\nexport function parseCommitUpload(input: unknown): CommitUploadInput {\n return v.parse(commitUploadSchema, input)\n}\n","import * as v from 'valibot'\n\nimport { documentPermissionSchema } from './documents'\n\nexport const collaborationPrincipalSchema = v.variant('kind', [\n v.object({\n kind: v.literal('user'),\n userId: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email())\n }),\n v.object({\n kind: v.literal('guest'),\n guestId: v.string(),\n name: v.string()\n })\n])\nexport type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalSchema>\n\n/**\n * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so\n * other peers can trust it over what the peer says of itself.\n */\nexport const cloudPresenceSchema = v.object({\n kind: v.picklist(['user', 'guest']),\n id: v.string(),\n name: v.string(),\n permission: documentPermissionSchema\n})\nexport type CloudPresence = v.InferOutput<typeof cloudPresenceSchema>\n\nexport const collaborationTicketSchema = v.object({\n token: v.string(),\n provider: v.optional(v.picklist(['trystero', 'relay'])),\n serverURL: v.optional(v.pipe(v.string(), v.url())),\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),\n principal: collaborationPrincipalSchema,\n permission: documentPermissionSchema,\n /**\n * Why a peer whose access would let them edit may only view: `storage-limit` when the document's\n * owner holds their whole storage allowance, until they free space or their plan grows.\n */\n readOnly: v.optional(v.picklist(['storage-limit'])),\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n expiresAt: v.string(),\n serverEnforcedWrites: v.boolean(),\n /**\n * Whether the relay answers `RELAY_HEARTBEAT`. A relay from before it takes a ping for a\n * malformed frame and turns the peer away, so editors ask only a relay that says it answers.\n */\n relayHeartbeat: v.optional(v.boolean(), false)\n})\nexport type CollaborationTicket = v.InferOutput<typeof collaborationTicketSchema>\n","import * as v from 'valibot'\n\nexport const workspaceRoleSchema = v.picklist(['viewer', 'editor', 'admin'])\nexport type WorkspaceRole = v.InferOutput<typeof workspaceRoleSchema>\n\nexport const workspaceSummarySchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n slug: v.string(),\n role: workspaceRoleSchema,\n /**\n * Whether the signed-in account owns the workspace, and so pays for its plan and AI credits.\n * Absent from servers released before it.\n */\n owner: v.optional(v.boolean()),\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type WorkspaceSummary = v.InferOutput<typeof workspaceSummarySchema>\n\nexport const createWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),\n slug: v.optional(\n v.pipe(\n v.string(),\n v.trim(),\n v.minLength(3),\n v.maxLength(63),\n v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)\n )\n )\n})\nexport type CreateWorkspaceInput = v.InferOutput<typeof createWorkspaceSchema>\n\nexport const workspaceListSchema = v.object({\n workspaces: v.array(workspaceSummarySchema)\n})\nexport type WorkspaceList = v.InferOutput<typeof workspaceListSchema>\n\nexport const updateWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\nexport type UpdateWorkspaceInput = v.InferOutput<typeof updateWorkspaceSchema>\n\n/** Someone who belongs to a workspace, and what they may do in it. */\nexport const workspaceMemberSchema = v.object({\n userId: v.string(),\n name: v.string(),\n email: v.string(),\n image: v.nullable(v.string()),\n role: workspaceRoleSchema,\n joinedAt: v.string()\n})\nexport type WorkspaceMember = v.InferOutput<typeof workspaceMemberSchema>\n\n/** An invitation to join a workspace that has not been accepted yet. */\nexport const workspaceInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n email: v.string(),\n role: workspaceRoleSchema,\n /** Who sent it; the name is null once their account is gone. */\n invitedBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n invitedAt: v.string(),\n expiresAt: v.string()\n})\nexport type WorkspaceInvitation = v.InferOutput<typeof workspaceInvitationSchema>\n\nexport const workspaceMembersSchema = v.object({\n members: v.array(workspaceMemberSchema),\n /** Only administrators see pending invitations. */\n invitations: v.array(workspaceInvitationSchema)\n})\nexport type WorkspaceMembers = v.InferOutput<typeof workspaceMembersSchema>\n\nexport const createWorkspaceInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n role: workspaceRoleSchema\n})\nexport type CreateWorkspaceInvitationInput = v.InferOutput<typeof createWorkspaceInvitationSchema>\n\n/** A new invitation and its link, for an administrator to pass on when email is off. */\nexport const createdWorkspaceInvitationSchema = v.object({\n invitation: workspaceInvitationSchema,\n acceptanceURL: v.string()\n})\nexport type CreatedWorkspaceInvitation = v.InferOutput<typeof createdWorkspaceInvitationSchema>\n\nexport const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema })\nexport type UpdateWorkspaceMemberInput = v.InferOutput<typeof updateWorkspaceMemberSchema>\n\nexport function parseCreateWorkspace(input: unknown): CreateWorkspaceInput {\n return v.parse(createWorkspaceSchema, input)\n}\n\nexport function parseUpdateWorkspace(input: unknown): UpdateWorkspaceInput {\n return v.parse(updateWorkspaceSchema, input)\n}\n\nexport function parseCreateWorkspaceInvitation(input: unknown): CreateWorkspaceInvitationInput {\n return v.parse(createWorkspaceInvitationSchema, input)\n}\n\nexport function parseUpdateWorkspaceMember(input: unknown): UpdateWorkspaceMemberInput {\n return v.parse(updateWorkspaceMemberSchema, input)\n}\n","import * as v from 'valibot'\n\nimport { collaborationPrincipalSchema } from './collaboration'\nimport { documentPermissionSchema, requestImageLinksSchema } from './documents'\nimport { workspaceRoleSchema } from './workspaces'\n\nexport const documentShareSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n permission: documentPermissionSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string(),\n expiresAt: v.nullable(v.string()),\n revokedAt: v.nullable(v.string()),\n lastUsedAt: v.nullable(v.string())\n})\nexport type DocumentShare = v.InferOutput<typeof documentShareSchema>\n\n/** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */\nconst shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())))\n\nexport const createDocumentShareSchema = v.object({\n permission: documentPermissionSchema,\n expiresAt: shareExpirySchema\n})\nexport type CreateDocumentShareInput = v.InferOutput<typeof createDocumentShareSchema>\n\nexport const updateDocumentShareSchema = v.object({\n permission: v.optional(documentPermissionSchema),\n expiresAt: shareExpirySchema\n})\nexport type UpdateDocumentShareInput = v.InferOutput<typeof updateDocumentShareSchema>\n\nexport const resolveDocumentShareSchema = v.object({\n secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),\n guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))\n})\nexport type ResolveDocumentShareInput = v.InferOutput<typeof resolveDocumentShareSchema>\n\n/** A guest's request for the links of images a shared document's live room names. */\nexport const requestSharedImageLinksSchema = v.object({\n ...resolveDocumentShareSchema.entries,\n ...requestImageLinksSchema.entries\n})\nexport type RequestSharedImageLinksInput = v.InferOutput<typeof requestSharedImageLinksSchema>\n\nexport function parseRequestSharedImageLinks(input: unknown): RequestSharedImageLinksInput {\n return v.parse(requestSharedImageLinksSchema, input)\n}\n\nexport const resolvedDocumentShareSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n /** What this person may do; a guest on an edit link may only view where guests may not edit. */\n permission: documentPermissionSchema,\n /** What the link lets someone signed in to the server do. */\n linkPermission: documentPermissionSchema,\n principal: collaborationPrincipalSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))\n})\nexport type ResolvedDocumentShare = v.InferOutput<typeof resolvedDocumentShareSchema>\n\nexport const cloudUserProfileSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n image: v.nullable(v.pipe(v.string(), v.url()))\n})\nexport type CloudUserProfile = v.InferOutput<typeof cloudUserProfileSchema>\n\nexport const documentGrantSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n userId: v.string(),\n permission: documentPermissionSchema,\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type DocumentGrant = v.InferOutput<typeof documentGrantSchema>\n\n/** What accepting an invitation gave: access to a document, or a place in a workspace. */\nexport const acceptedInvitationSchema = v.variant('kind', [\n v.object({ kind: v.literal('document'), grant: documentGrantSchema }),\n v.object({\n kind: v.literal('workspace'),\n workspaceId: v.pipe(v.string(), v.uuid()),\n role: workspaceRoleSchema\n })\n])\nexport type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>\n\nexport const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })\nexport type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>\n\nexport const createDocumentInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n permission: documentPermissionSchema\n})\nexport type CreateDocumentInvitationInput = v.InferOutput<typeof createDocumentInvitationSchema>\n\nexport const acceptDocumentInvitationSchema = v.object({\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type AcceptDocumentInvitationInput = v.InferOutput<typeof acceptDocumentInvitationSchema>\n\nexport const createInvitationContinuationSchema = v.object({\n invitationId: v.pipe(v.string(), v.uuid()),\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type CreateInvitationContinuationInput = v.InferOutput<\n typeof createInvitationContinuationSchema\n>\n\nexport const invitationContinuationSchema = v.object({\n id: v.pipe(v.string(), v.minLength(16), v.maxLength(128))\n})\nexport type InvitationContinuation = v.InferOutput<typeof invitationContinuationSchema>\n\nconst invitationPreviewFields = {\n inviterName: v.string(),\n expiresAt: v.string(),\n recipientHint: v.string()\n}\n\n/** What an invitation link opens: one document, or a whole workspace. */\nexport const invitationPreviewSchema = v.variant('kind', [\n v.object({\n kind: v.literal('document'),\n documentName: v.string(),\n permission: documentPermissionSchema,\n ...invitationPreviewFields\n }),\n v.object({\n kind: v.literal('workspace'),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n ...invitationPreviewFields\n })\n])\nexport type InvitationPreview = v.InferOutput<typeof invitationPreviewSchema>\n\nexport const documentInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n email: v.pipe(v.string(), v.email()),\n permission: documentPermissionSchema,\n invitedBy: v.string(),\n invitedAt: v.string(),\n expiresAt: v.string(),\n acceptedAt: v.nullable(v.string())\n})\nexport type DocumentInvitation = v.InferOutput<typeof documentInvitationSchema>\n\nexport function parseCreateInvitationContinuation(\n input: unknown\n): CreateInvitationContinuationInput {\n return v.parse(createInvitationContinuationSchema, input)\n}\n\nexport function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {\n return v.parse(createDocumentShareSchema, input)\n}\n\nexport function parseUpdateDocumentShare(input: unknown): UpdateDocumentShareInput {\n return v.parse(updateDocumentShareSchema, input)\n}\n\nexport function parseResolveDocumentShare(input: unknown): ResolveDocumentShareInput {\n return v.parse(resolveDocumentShareSchema, input)\n}\n\nexport function parsePutDocumentGrant(input: unknown): PutDocumentGrantInput {\n return v.parse(putDocumentGrantSchema, input)\n}\n\nexport function parseCreateDocumentInvitation(input: unknown): CreateDocumentInvitationInput {\n return v.parse(createDocumentInvitationSchema, input)\n}\n\nexport function parseAcceptDocumentInvitation(input: unknown): AcceptDocumentInvitationInput {\n return v.parse(acceptDocumentInvitationSchema, input)\n}\n","import * as v from 'valibot'\n\nimport { resolveDocumentShareSchema } from './sharing'\n\n/** Why someone reports a document shared with them. */\nexport const documentReportReasonSchema = v.picklist([\n 'spam-phishing',\n 'illegal',\n 'copyright',\n 'harassment',\n 'other'\n])\nexport type DocumentReportReason = v.InferOutput<typeof documentReportReasonSchema>\n\n/** How long a report's description may be. */\nexport const DOCUMENT_REPORT_DESCRIPTION_MAX = 2000\n\n/**\n * A report about a document someone opened from a share link: the link's secret proves they can\n * see it, as resolving the link does, and a guest names themselves as they do there.\n */\nexport const fileDocumentReportSchema = v.object({\n secret: resolveDocumentShareSchema.entries.secret,\n guestId: resolveDocumentShareSchema.entries.guestId,\n reason: documentReportReasonSchema,\n description: v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(DOCUMENT_REPORT_DESCRIPTION_MAX)\n ),\n /** Where an administrator may answer; optional, and never shown to the document's people. */\n replyEmail: v.optional(v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email(), v.maxLength(254)))\n})\nexport type FileDocumentReportInput = v.InferOutput<typeof fileDocumentReportSchema>\n\nexport function parseFileDocumentReport(input: unknown): FileDocumentReportInput {\n return v.parse(fileDocumentReportSchema, input)\n}\n\n/** What filing a report answers: that it arrived, and nothing about the document. */\nexport const fileDocumentReportResponseSchema = v.object({ received: v.literal(true) })\n","import { zipObject } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport {\n CLOUD_SOCIAL_PROVIDERS,\n cloudIdentitySchema,\n cloudAccountSessionSchema,\n cloudPersonSchema,\n cloudSignInSchema\n} from '../account'\nimport { documentKindSchema } from '../documents'\nimport { documentReportReasonSchema } from '../reports'\nimport { workspaceRoleSchema } from '../workspaces'\n\nconst timestampSchema = v.pipe(v.string(), v.isoTimestamp())\nconst nullableTimestampSchema = v.nullable(timestampSchema)\nconst countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\n/**\n * What every admin list answers besides its rows: how many rows match the search and filter\n * across every page, and how many match the search under each filter.\n */\nfunction listTotals<const Filter extends string>(filters: readonly Filter[]) {\n return {\n total: countSchema,\n counts: v.object(\n zipObject(\n filters,\n filters.map(() => countSchema)\n )\n )\n }\n}\n\nexport const adminErrorCodeSchema = v.picklist([\n 'bad_request',\n 'unauthorized',\n 'forbidden',\n 'not_found',\n 'rate_limited',\n 'invalid_enrollment_transition',\n 'last_admin_required',\n 'self_admin_action_forbidden',\n // The sign-in method is the account's last, so removing it would lock its owner out.\n 'last_authentication_method',\n // Only an account whose request was never approved can be deleted from the console.\n 'account_approved',\n 'email_regeneration_unavailable',\n 'mfa_required',\n // Two-step is on, but this session has not proved it lately; confirming it lets it back in.\n 'two_step_unconfirmed',\n 'document_not_restorable',\n 'workspace_gone'\n])\n\nexport const adminErrorResponseSchema = v.object({\n error: v.object({ code: adminErrorCodeSchema })\n})\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentSchema = v.object({\n id: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.nullable(v.string()),\n reason: v.nullable(v.string()),\n status: enrollmentStatusSchema,\n requestedAt: timestampSchema,\n reviewedAt: nullableTimestampSchema,\n reviewedBy: v.nullable(v.string()),\n /** The reviewer's name, in lists, while the server still knows them. */\n reviewerName: v.optional(v.nullable(v.string())),\n reviewNote: v.nullable(v.string()),\n approvedUserId: v.nullable(v.string()),\n requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))\n})\n\nexport const enrollmentsResponseSchema = v.object({\n enrollments: v.array(enrollmentSchema),\n ...listTotals(enrollmentStatusSchema.options)\n})\nexport const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema })\n/** How many waiting requests were approved with the official deployment's invitation letter. */\nexport const enrollmentInviteResponseSchema = v.object({\n invited: v.pipe(v.number(), v.integer(), v.minValue(0))\n})\n\nexport const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })\n\nexport const cloudAdminUserSchema = v.object({\n ...cloudPersonSchema.entries,\n role: v.optional(v.string()),\n banned: v.nullable(v.boolean()),\n banReason: v.optional(v.nullable(v.string())),\n createdAt: timestampSchema,\n /** An authenticator app or a passkey confirms this account's sign-ins. */\n twoStep: v.boolean(),\n /** When one of the account's sessions was last used, or null when none is left. */\n lastActiveAt: nullableTimestampSchema,\n workspaceCount: countSchema,\n /** How the account signs in: `credential` for a password, or a provider such as `google`. */\n methods: v.array(v.string()),\n /**\n * On a server that approves people, where this account's request to join stands: an account\n * exists from its first sign-in, before anyone approved it. Absent where everyone may join.\n */\n request: v.optional(v.nullable(enrollmentStatusSchema))\n})\n\n/** Which accounts a list of people shows. */\nexport const cloudAdminUserFilterSchema = v.picklist([\n 'all',\n 'administrators',\n 'suspended',\n 'without-two-step'\n])\n/** Narrows a list of people, under any filter, to those who sign in a given way. */\nexport const cloudAdminUserMethodSchema = v.picklist(['password', ...CLOUD_SOCIAL_PROVIDERS])\nexport const cloudAdminUsersResponseSchema = v.object({\n users: v.array(cloudAdminUserSchema),\n ...listTotals(cloudAdminUserFilterSchema.options)\n})\n\nexport const cloudAdminUserDetailSchema = v.object({\n user: v.object({\n ...cloudAdminUserSchema.entries,\n emailVerified: v.boolean()\n }),\n /** `canRemove`: the account keeps a way in that still works without it. */\n methods: v.array(\n v.object({\n id: v.string(),\n provider: v.string(),\n createdAt: timestampSchema,\n canRemove: v.boolean()\n })\n ),\n authenticator: v.boolean(),\n passkeyCount: countSchema,\n sessions: v.array(cloudAccountSessionSchema),\n signIns: v.array(cloudSignInSchema),\n workspaces: v.array(\n v.object({\n id: v.string(),\n name: v.string(),\n role: workspaceRoleSchema,\n memberCount: countSchema,\n joinedAt: timestampSchema\n })\n )\n})\n\nexport const adminMutationResponseSchema = v.object({ ok: v.literal(true) })\n\nexport const transactionalEmailAdminSchema = v.object({\n id: v.string(),\n kind: v.string(),\n recipientEmailNormalized: v.pipe(v.string(), v.email()),\n status: v.string(),\n attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),\n nextAttemptAt: timestampSchema,\n transport: v.nullable(v.string()),\n transportMessageId: v.nullable(v.string()),\n lastErrorCode: v.nullable(v.string()),\n createdAt: timestampSchema,\n acceptedAt: nullableTimestampSchema,\n regeneratable: v.boolean()\n})\n/** Which messages a list of email shows, by how their delivery went. */\nexport const cloudAdminEmailFilterSchema = v.picklist(['all', 'sent', 'waiting', 'failed'])\nexport const adminEmailResponseSchema = v.object({\n messages: v.array(transactionalEmailAdminSchema),\n ...listTotals(cloudAdminEmailFilterSchema.options)\n})\n\n/** Who or what an event names; `name` is null once the server no longer knows it. */\nconst auditPartySchema = v.object({ id: v.string(), name: v.nullable(v.string()) })\n\nexport const adminAuditEventSchema = v.object({\n id: v.string(),\n actor: auditPartySchema,\n action: v.string(),\n /** What the event is about: an account, an access request, an email, or a document. */\n subject: v.object({ ...auditPartySchema.entries, type: v.string() }),\n metadata: v.unknown(),\n createdAt: timestampSchema\n})\n/** Which events a list of activity shows, by what they are about. */\nexport const cloudAdminAuditFilterSchema = v.picklist([\n 'all',\n 'accounts',\n 'requests',\n 'email',\n 'documents'\n])\nexport const adminAuditResponseSchema = v.object({\n events: v.array(adminAuditEventSchema),\n ...listTotals(cloudAdminAuditFilterSchema.options)\n})\n\n/** A document as the console shows it: where it lives, who made it, and whether it is taken down. */\nexport const cloudAdminDocumentSchema = v.object({\n id: v.string(),\n name: v.string(),\n /** A design or a board. Servers from before send none, and had only designs. */\n kind: v.optional(documentKindSchema, 'design'),\n workspace: v.object({ id: v.string(), name: v.string() }),\n /** Who made it, while the server knows them. */\n owner: v.nullable(v.object({ id: v.string(), name: v.string(), email: v.string() })),\n createdAt: timestampSchema,\n updatedAt: timestampSchema,\n disabledAt: nullableTimestampSchema,\n disabledReason: v.nullable(v.string()),\n /** Reports about it still waiting for a decision. */\n openReports: countSchema,\n /**\n * When someone deleted it forever, and when cleanup destroys it; until then an administrator\n * can still restore it. Servers from before Trash send neither.\n */\n purgedAt: v.optional(nullableTimestampSchema, null),\n destroyedAt: v.optional(nullableTimestampSchema, null),\n /**\n * The saved revision whose thumbnail previews it; null before its first save. Servers from\n * before previews send none.\n */\n revisionId: v.optional(v.nullable(v.string()), null),\n /**\n * Who beyond its workspace can open it: anyone, in the community gallery, and whoever holds one\n * of its live share links, `editLinks` of which let them edit. Servers from before send none.\n */\n exposure: v.optional(\n v.object({ community: v.boolean(), links: countSchema, editLinks: countSchema }),\n { community: false, links: 0, editLinks: 0 }\n )\n})\n/** Which documents a list shows: live ones, or those deleted forever an administrator can restore. */\nexport const cloudAdminDocumentFilterSchema = v.picklist(['all', 'reported', 'disabled', 'purged'])\nexport const cloudAdminDocumentsResponseSchema = v.object({\n documents: v.array(cloudAdminDocumentSchema),\n ...listTotals(cloudAdminDocumentFilterSchema.options)\n})\n\nexport const cloudAdminReportStatusSchema = v.picklist(['open', 'dismissed', 'actioned'])\nexport const cloudAdminReportSchema = v.object({\n id: v.string(),\n reason: documentReportReasonSchema,\n description: v.string(),\n status: cloudAdminReportStatusSchema,\n /** The account that filed it, or null for a guest. */\n reporter: v.nullable(v.object({ id: v.string(), name: v.nullable(v.string()) })),\n replyEmail: v.nullable(v.string()),\n createdAt: timestampSchema,\n resolvedAt: nullableTimestampSchema,\n document: cloudAdminDocumentSchema,\n /** The link it was opened from, and whether that link still works. */\n share: v.nullable(v.object({ id: v.string(), revoked: v.boolean() }))\n})\n/** Which reports a list shows, by where they stand. */\nexport const cloudAdminReportFilterSchema = v.picklist(['open', 'actioned', 'dismissed', 'all'])\nexport const cloudAdminReportsResponseSchema = v.object({\n reports: v.array(cloudAdminReportSchema),\n ...listTotals(cloudAdminReportFilterSchema.options)\n})\n\nexport const adminOperationsResponseSchema = v.object({\n deployment: v.picklist(['official', 'self-hosted']),\n enrollmentMode: v.picklist(['open', 'approval', 'closed']),\n emailTransport: v.picklist(['none', 'smtp', 'cloudflare']),\n pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),\n openReports: countSchema,\n pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n accounts: countSchema,\n workspaces: countSchema,\n documents: countSchema,\n storedBytes: countSchema\n})\n\nexport type AdminErrorCode = v.InferOutput<typeof adminErrorCodeSchema>\nexport type Enrollment = v.InferOutput<typeof enrollmentSchema>\nexport type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>\nexport type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>\nexport type CloudAdminUserFilter = v.InferOutput<typeof cloudAdminUserFilterSchema>\nexport type CloudAdminUserMethod = v.InferOutput<typeof cloudAdminUserMethodSchema>\nexport type CloudAdminEmailFilter = v.InferOutput<typeof cloudAdminEmailFilterSchema>\nexport type CloudAdminAuditFilter = v.InferOutput<typeof cloudAdminAuditFilterSchema>\nexport type EnrollmentStatus = v.InferOutput<typeof enrollmentStatusSchema>\nexport type CloudAdminUsers = v.InferOutput<typeof cloudAdminUsersResponseSchema>\nexport type CloudAdminUserDetail = v.InferOutput<typeof cloudAdminUserDetailSchema>\nexport type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>\nexport type AdminAuditEvent = v.InferOutput<typeof adminAuditEventSchema>\nexport type AdminOperations = v.InferOutput<typeof adminOperationsResponseSchema>\nexport type CloudAdminDocument = v.InferOutput<typeof cloudAdminDocumentSchema>\nexport type CloudAdminDocumentFilter = v.InferOutput<typeof cloudAdminDocumentFilterSchema>\nexport type CloudAdminReport = v.InferOutput<typeof cloudAdminReportSchema>\nexport type CloudAdminReportFilter = v.InferOutput<typeof cloudAdminReportFilterSchema>\nexport type CloudAdminReportStatus = v.InferOutput<typeof cloudAdminReportStatusSchema>\n","import { deflateSync, Inflate } from 'fflate'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as Y from 'yjs'\n\n/** Where the relay accepts WebSocket upgrades, under the Cloud API origin. */\nexport const RELAY_PATH = '/api/collaboration/relay'\n\n/**\n * The relay URL's query parameter naming the ticket's document, so a runtime that keeps each\n * document's room in its own place can route the socket there before the ticket arrives.\n */\nexport const RELAY_DOCUMENT_PARAM = 'document'\n\n/** The relay's public URL on the same origin as the API, unless the deployment names another. */\nexport function defaultRelayURL(publicURL: string): string {\n const url = new URL(RELAY_PATH, publicURL)\n url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'\n return url.href\n}\n\n/**\n * The room messages collaboration sends. The relay reads the document ones to keep its copy,\n * persist it, and drop writes from viewers; it forwards the rest unread.\n */\nexport const COLLAB_ACTIONS = {\n yjsUpdate: 'yjs-update',\n syncStep1: 'sync-step1',\n syncReply: 'sync-reply',\n awareness: 'awareness',\n agentPreview: 'agent-preview',\n upload: 'upload',\n /** From the server only: the document's version history changed, so open lists load it again. */\n versions: 'versions',\n /** From the server only: a comment thread changed; the payload is its ID as UTF-8. */\n comments: 'comments'\n} as const\n\n/**\n * The most a room message may decode to, compressed or not. A peer's update past it is dropped\n * before it is decoded, so a small compressed reply cannot expand without bound.\n */\nexport const MAX_COLLAB_MESSAGE_BYTES = 256 * 1024 * 1024\n\n/**\n * What a peer joining needs is the whole document, which repeats the same field names across\n * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already\n * groups that repetition, and together they make a room's first sync about a twelfth the size.\n * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.\n */\nexport function encodeSyncReply(document: Y.Doc, stateVector: Uint8Array): Uint8Array {\n return deflateSync(Y.encodeStateAsUpdateV2(document, stateVector))\n}\n\n/**\n * Compressed input is inflated this much at a time, so a reply stops within a step of passing\n * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.\n */\nconst INFLATE_STEP = 16 * 1024\n\n/**\n * The V2 update a peer sent, inflated first when `compressed`, as a sync reply is; null once it\n * would decode past `limit` bytes. Throws on data that does not inflate.\n */\nexport function decodeRoomUpdate(\n data: Uint8Array,\n { limit, compressed = false }: { limit: number; compressed?: boolean }\n): Uint8Array | null {\n if (!compressed) return data.length <= limit ? data : null\n const chunks: Uint8Array[] = []\n let size = 0\n const inflate = new Inflate((chunk) => {\n size += chunk.length\n if (size <= limit) chunks.push(chunk)\n })\n for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {\n inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length)\n if (size > limit) return null\n }\n const inflated = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n inflated.set(chunk, at)\n at += chunk.length\n }\n return inflated\n}\n\n/** The peer ID the relay itself uses: it holds the room's document and answers sync requests. */\nexport const RELAY_SERVER_PEER = 'server'\n\n/** The longest name a peer's presence may carry; peers drop presence with a longer one. */\nexport const MAX_PRESENCE_NAME_LENGTH = 40\n\n/** A name as presence carries it: trimmed and cut to what every peer accepts. */\nexport function presenceName(name: string): string {\n return name.trim().slice(0, MAX_PRESENCE_NAME_LENGTH)\n}\n\n/**\n * Close codes in the WebSocket application range. A client reconnects with a fresh ticket after\n * `expired`, and gives up on the others.\n */\nexport const RELAY_CLOSE = {\n unauthorized: 4401,\n expired: 4403,\n roomFull: 4409,\n messageTooLarge: 4413,\n protocol: 4400,\n /** The document was restored to a version, so its room started over under a new ID. */\n restored: 4410\n} as const\n\n/**\n * The text a peer sends to learn whether the relay still hears it, and the relay's answer. Relay\n * frames are binary, so neither is taken for one, and a Durable Object answers without waking.\n */\nexport const RELAY_HEARTBEAT = { ping: 'ping', pong: 'pong' } as const\n\nconst CLIENT_AUTH = 0\nconst CLIENT_MESSAGE = 1\nconst CLIENT_FRAGMENT = 2\nconst SERVER_WELCOME = 0\nconst SERVER_JOIN = 1\nconst SERVER_LEAVE = 2\nconst SERVER_MESSAGE = 3\nconst SERVER_FRAGMENT = 4\n\n/**\n * The most one WebSocket message carries. A frame past it travels as fragments of this size that\n * the receiver joins again, so a large paste or a room's first sync fits under any host's message\n * cap, such as the 32 MiB of Cloudflare Workers, and the relay can turn away a viewer's or an\n * unadmitted peer's large frame before holding it whole.\n */\nexport const RELAY_FRAGMENT_BYTES = 256 * 1024\n\n/** The smallest per-message limit a relay may set: one fragment and its few bytes of framing. */\nexport const RELAY_MINIMUM_MESSAGE_BYTES = RELAY_FRAGMENT_BYTES + 16\n\n/**\n * What the relay adds to a frame it forwards: the frame type, the sender's peer ID, and lengths.\n * A client reads frames this much past the relay's own limit, so a forwarded edit at that limit\n * still arrives.\n */\nexport const RELAY_FORWARDING_BYTES = 64 * 1024\n\n/** Frames a client sends: its ticket first, again to refresh it, then room messages. */\nexport type RelayClientFrame =\n | { type: 'auth'; token: string }\n | { type: 'message'; namespace: string; target: string | null; payload: Uint8Array }\n\n/** Frames the relay sends: who is in the room, arrivals and departures, and forwarded messages. */\nexport type RelayServerFrame =\n | { type: 'welcome'; peerId: string; peers: string[] }\n | { type: 'join'; peerId: string }\n | { type: 'leave'; peerId: string }\n | { type: 'message'; namespace: string; from: string; payload: Uint8Array }\n\n/** Encodes into a buffer of its own, which `WebSocket.send` accepts. */\nfunction toSendable(write: (encoder: encoding.Encoder) => void): Uint8Array<ArrayBuffer> {\n return new Uint8Array(encoding.encode(write))\n}\n\nexport function encodeRelayClientFrame(frame: RelayClientFrame): Uint8Array<ArrayBuffer> {\n return toSendable((encoder) => {\n if (frame.type === 'auth') {\n encoding.writeVarUint(encoder, CLIENT_AUTH)\n encoding.writeVarString(encoder, frame.token)\n return\n }\n encoding.writeVarUint(encoder, CLIENT_MESSAGE)\n encoding.writeVarString(encoder, frame.namespace)\n encoding.writeVarString(encoder, frame.target ?? '')\n encoding.writeVarUint8Array(encoder, frame.payload)\n })\n}\n\nexport function encodeRelayServerFrame(frame: RelayServerFrame): Uint8Array<ArrayBuffer> {\n return toSendable((encoder) => {\n switch (frame.type) {\n case 'welcome':\n encoding.writeVarUint(encoder, SERVER_WELCOME)\n encoding.writeVarString(encoder, frame.peerId)\n encoding.writeVarUint(encoder, frame.peers.length)\n for (const peer of frame.peers) encoding.writeVarString(encoder, peer)\n return\n case 'join':\n case 'leave':\n encoding.writeVarUint(encoder, frame.type === 'join' ? SERVER_JOIN : SERVER_LEAVE)\n encoding.writeVarString(encoder, frame.peerId)\n return\n case 'message':\n encoding.writeVarUint(encoder, SERVER_MESSAGE)\n encoding.writeVarString(encoder, frame.namespace)\n encoding.writeVarString(encoder, frame.from)\n encoding.writeVarUint8Array(encoder, frame.payload)\n }\n })\n}\n\n/** The frame as it goes over the socket: itself, or fragments of it when it is large. */\nfunction fragments(tag: number, frame: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>[] {\n if (frame.byteLength <= RELAY_FRAGMENT_BYTES) return [frame]\n const parts: Uint8Array<ArrayBuffer>[] = []\n for (let offset = 0; offset < frame.byteLength; offset += RELAY_FRAGMENT_BYTES) {\n const end = Math.min(offset + RELAY_FRAGMENT_BYTES, frame.byteLength)\n parts.push(\n toSendable((encoder) => {\n encoding.writeVarUint(encoder, tag)\n encoding.writeVarUint(encoder, end < frame.byteLength ? 1 : 0)\n encoding.writeVarUint8Array(encoder, frame.subarray(offset, end))\n })\n )\n }\n return parts\n}\n\n/** A client frame as the socket messages that carry it, in order. */\nexport function relayClientMessages(frame: RelayClientFrame): Uint8Array<ArrayBuffer>[] {\n return fragments(CLIENT_FRAGMENT, encodeRelayClientFrame(frame))\n}\n\n/** A server frame as the socket messages that carry it, in order. */\nexport function relayServerMessages(frame: RelayServerFrame): Uint8Array<ArrayBuffer>[] {\n return fragments(SERVER_FRAGMENT, encodeRelayServerFrame(frame))\n}\n\n/** What one socket message gave: a whole frame, part of one, or a reason to close. */\nexport type RelayAssembly =\n | { type: 'frame'; data: Uint8Array }\n | { type: 'partial' }\n | { type: 'too-large' }\n | { type: 'malformed' }\n\n/**\n * Joins one socket's fragments into the frames they carry. A socket sends a frame's fragments in\n * a row, so a whole frame arriving between them is malformed. `limit` caps the joined frame and is\n * read for every message, so it can follow what the sender may do.\n */\nfunction createAssembler(tag: number, limit: () => number) {\n let parts: Uint8Array[] = []\n let size = 0\n /** Set while the rest of a refused frame arrives, so its tail never reads as a frame of its own. */\n let discarding = false\n const reset = () => {\n parts = []\n size = 0\n }\n return {\n push(data: Uint8Array): RelayAssembly {\n let decoder: decoding.Decoder\n let type: number\n try {\n decoder = decoding.createDecoder(data)\n type = decoding.readVarUint(decoder)\n } catch {\n reset()\n return { type: 'malformed' }\n }\n if (type !== tag) {\n if (parts.length > 0) {\n reset()\n return { type: 'malformed' }\n }\n return { type: 'frame', data }\n }\n let more: number\n let chunk: Uint8Array\n try {\n more = decoding.readVarUint(decoder)\n chunk = decoding.readVarUint8Array(decoder)\n } catch {\n // A fragment that cannot be read is taken as unfinished: only a sound last one ends it.\n reset()\n discarding = true\n return { type: 'malformed' }\n }\n if (decoder.pos !== data.byteLength || more > 1) {\n reset()\n discarding = more !== 0\n return { type: 'malformed' }\n }\n if (discarding) {\n discarding = more === 1\n return { type: 'partial' }\n }\n size += chunk.byteLength\n if (size > limit()) {\n reset()\n discarding = more === 1\n return { type: 'too-large' }\n }\n parts.push(chunk.slice())\n if (more === 1) return { type: 'partial' }\n const joined = new Uint8Array(size)\n let at = 0\n for (const part of parts) {\n joined.set(part, at)\n at += part.byteLength\n }\n reset()\n return { type: 'frame', data: joined }\n }\n }\n}\n\n/** Joins the fragments a client sends; the relay holds one per socket. */\nexport function createRelayClientAssembler(limit: () => number) {\n return createAssembler(CLIENT_FRAGMENT, limit)\n}\n\n/** Joins the fragments the relay sends; a client holds one per socket. */\nexport function createRelayServerAssembler(limit: () => number) {\n return createAssembler(SERVER_FRAGMENT, limit)\n}\n\n/**\n * lib0 reads byte arrays as views of the underlying buffer, which can run past the end of the\n * frame's own view, as with pooled socket buffers. A frame is valid only when decoding consumed\n * exactly its bytes, and payloads are copied out of the shared buffer.\n */\nfunction complete<T>(decoder: decoding.Decoder, data: Uint8Array, frame: T): T | null {\n return decoder.pos === data.byteLength ? frame : null\n}\n\nfunction readPayload(decoder: decoding.Decoder): Uint8Array {\n return decoding.readVarUint8Array(decoder).slice()\n}\n\n/** Returns null for a frame that is malformed or of an unknown type. */\nexport function decodeRelayClientFrame(data: Uint8Array): RelayClientFrame | null {\n try {\n const decoder = decoding.createDecoder(data)\n const type = decoding.readVarUint(decoder)\n if (type === CLIENT_AUTH) {\n return complete(decoder, data, { type: 'auth', token: decoding.readVarString(decoder) })\n }\n if (type !== CLIENT_MESSAGE) return null\n const namespace = decoding.readVarString(decoder)\n const target = decoding.readVarString(decoder)\n const payload = readPayload(decoder)\n return complete(decoder, data, { type: 'message', namespace, target: target || null, payload })\n } catch {\n return null\n }\n}\n\n/** Returns null for a frame that is malformed or of an unknown type. */\nexport function decodeRelayServerFrame(data: Uint8Array): RelayServerFrame | null {\n try {\n const decoder = decoding.createDecoder(data)\n switch (decoding.readVarUint(decoder)) {\n case SERVER_WELCOME: {\n const peerId = decoding.readVarString(decoder)\n const count = decoding.readVarUint(decoder)\n const peers: string[] = []\n for (let index = 0; index < count; index++) peers.push(decoding.readVarString(decoder))\n return complete(decoder, data, { type: 'welcome', peerId, peers })\n }\n case SERVER_JOIN:\n return complete(decoder, data, { type: 'join', peerId: decoding.readVarString(decoder) })\n case SERVER_LEAVE:\n return complete(decoder, data, { type: 'leave', peerId: decoding.readVarString(decoder) })\n case SERVER_MESSAGE: {\n const namespace = decoding.readVarString(decoder)\n const from = decoding.readVarString(decoder)\n const payload = readPayload(decoder)\n return complete(decoder, data, { type: 'message', namespace, from, payload })\n }\n default:\n return null\n }\n } catch {\n return null\n }\n}\n","import compareVersions from 'semver/functions/compare.js'\nimport parseVersion from 'semver/functions/parse.js'\nimport * as v from 'valibot'\n\nimport { isKnownSocialProvider } from './account'\nimport { cloudBillingDiscoverySchema } from './billing'\nimport { cloudServicesDiscoverySchema } from './services'\n\nexport const CLOUD_PROTOCOL_VERSION = '1' as const\nexport const CLOUD_DISCOVERY_PATH = '/.well-known/openpencil' as const\n\nexport const cloudDeploymentSchema = v.picklist(['official', 'self-hosted'])\nexport type CloudDeployment = v.InferOutput<typeof cloudDeploymentSchema>\n\n/**\n * The server's sign-in providers that this editor knows. A newer server may offer one this editor\n * has no button for; it is left out rather than failing discovery, so the editor still connects.\n */\nconst socialProvidersSchema = v.pipe(\n v.array(v.string()),\n v.transform((providers) => providers.filter(isKnownSocialProvider))\n)\n\nexport const cloudAuthenticationSchema = v.object({\n emailPassword: v.optional(\n v.object({\n signIn: v.boolean(),\n signUp: v.boolean(),\n minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),\n captcha: v.optional(\n v.object({\n provider: v.literal('cloudflare-turnstile'),\n siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))\n })\n )\n })\n ),\n socialProviders: socialProvidersSchema,\n enterpriseSSO: v.boolean(),\n enrollmentMode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),\n mfa: v.optional(\n v.object({\n deploymentAdminRequired: v.boolean(),\n totp: v.boolean(),\n passkeys: v.boolean(),\n recoveryCodes: v.boolean()\n })\n )\n})\nexport type CloudAuthentication = v.InferOutput<typeof cloudAuthenticationSchema>\n\nexport const cloudCapabilitiesSchema = v.object({\n documents: v.boolean(),\n workspaces: v.boolean(),\n collaboration: v.boolean()\n})\nexport type CloudCapabilities = v.InferOutput<typeof cloudCapabilitiesSchema>\n\n/**\n * An editor version, as SemVer: a release such as `0.18.0`, or a pre-release such as\n * `0.18.0-beta.2` or a nightly's `0.18.0-nightly.20261116`.\n *\n * Editors before 0.18.0 accept only `major.minor.patch` here and fail discovery on anything else,\n * so a server names a pre-release minimum only once its minimum is already 0.18.0 or later.\n */\nexport const cloudEditorVersionSchema = v.pipe(\n v.string(),\n v.check(isSemVer, 'Expected a SemVer version')\n)\n\n/**\n * Whether the text is exactly a SemVer version, build metadata included: semver's own parse also\n * takes a `v` prefix or spaces, which a version here never has.\n */\nfunction isSemVer(value: string): boolean {\n const parsed = parseVersion(value)\n if (!parsed) return false\n const build = parsed.build.length > 0 ? `+${parsed.build.join('.')}` : ''\n return `${parsed.version}${build}` === value\n}\n\n/**\n * The header desktop editors send with each request, naming their version, so a server can refuse\n * an editor older than its `minimumEditorVersion`. Browser editors leave it out: the server serves\n * them, and an older server's CORS rules would refuse a header they don't list.\n */\nexport const CLOUD_EDITOR_VERSION_HEADER = 'X-OpenPencil-Editor-Version' as const\n\n/**\n * Whether `version` is `minimum` or later, in SemVer order: a pre-release comes before its\n * release, so `0.18.0-beta.2` is not at least `0.18.0`; a release's nightlies come after its\n * betas and order by date. To admit a release's pre-releases, name the earliest one, such as\n * `0.18.0-beta.1`, or `0.18.0-nightly.20261116` for nightlies from that day on. A\n * version that isn't SemVer, on either side, is not at least anything.\n */\nexport function isEditorVersionAtLeast(version: string, minimum: string): boolean {\n if (!isSemVer(version) || !isSemVer(minimum)) return false\n return compareVersions(version, minimum) >= 0\n}\n\n/**\n * Whether editors offer this server to everyone, and from which editor version on. Only the\n * official server's listing is read: it turns the Cloud entry points on without an editor release,\n * and an editor older than the minimum keeps them hidden.\n */\nexport const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema })\nexport type CloudListing = v.InferOutput<typeof cloudListingSchema>\n\nconst legalURLSchema = v.pipe(v.string(), v.url())\n\n/**\n * The operator's legal links, which clients show at sign-up and in account pages. A server that\n * names none shows none; `requireAcceptance` means an account accepts `termsVersion` before it uses\n * the server.\n */\nexport const cloudLegalDiscoverySchema = v.object({\n termsURL: v.optional(legalURLSchema),\n privacyURL: v.optional(legalURLSchema),\n termsVersion: v.optional(v.string()),\n requireAcceptance: v.boolean(),\n abuseEmail: v.optional(v.pipe(v.string(), v.email())),\n minimumAge: v.optional(v.pipe(v.number(), v.integer()))\n})\nexport type CloudLegalDiscovery = v.InferOutput<typeof cloudLegalDiscoverySchema>\n\n/** A web address a page may link or load: `http` or `https` only, never a script or data URL. */\nconst webURLSchema = v.pipe(\n v.string(),\n v.url(),\n v.check((value) => ['http:', 'https:'].includes(new URL(value).protocol))\n)\n\n/**\n * How a self-hosted server names itself on its public pages: the operator's name and logo in the\n * bar, and where its people get help. The official server is OpenPencil's own and names none.\n */\nexport const cloudBrandingSchema = v.object({\n name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n logoURL: v.optional(webURLSchema),\n helpURL: v.optional(webURLSchema)\n})\nexport type CloudBranding = v.InferOutput<typeof cloudBrandingSchema>\n\n/**\n * The server's community gallery: the workspace whose documents anyone may open read-only.\n * Saving to it publishes, so editors never choose it for anyone and say so when it is chosen.\n * `tourDocumentId` is the gallery document editors open as their tour.\n */\nexport const cloudCommunityDiscoverySchema = v.object({\n workspaceId: v.pipe(v.string(), v.uuid()),\n tourDocumentId: v.optional(v.pipe(v.string(), v.uuid()))\n})\nexport type CloudCommunityDiscovery = v.InferOutput<typeof cloudCommunityDiscoverySchema>\n\nexport const cloudDiscoverySchema = v.object({\n protocolVersion: v.literal(CLOUD_PROTOCOL_VERSION),\n deployment: cloudDeploymentSchema,\n apiURL: v.pipe(v.string(), v.url()),\n authURL: v.pipe(v.string(), v.url()),\n /** Whether the server's own editor works with files on this device without signing in. */\n localEditor: v.optional(v.boolean(), true),\n authentication: cloudAuthenticationSchema,\n capabilities: cloudCapabilitiesSchema,\n listing: v.optional(cloudListingSchema),\n /**\n * The oldest editor version the server works with. Older editors ask to be updated instead of\n * connecting, and the server refuses their requests.\n */\n minimumEditorVersion: v.optional(cloudEditorVersionSchema),\n /** The services editors reach with Cloud-signed tokens; absent when the deployment has none. */\n services: v.optional(cloudServicesDiscoverySchema),\n /** Where people manage their plan and buy credits; absent when the deployment does not bill. */\n billing: v.optional(cloudBillingDiscoverySchema),\n /** The community gallery; absent when the deployment has none. */\n community: v.optional(cloudCommunityDiscoverySchema),\n legal: v.optional(cloudLegalDiscoverySchema),\n branding: v.optional(cloudBrandingSchema)\n})\nexport type CloudDiscovery = v.InferOutput<typeof cloudDiscoverySchema>\n\n/** The server's own address, where its editor and pages are, from its auth API's. */\nexport function cloudServerOrigin(discovery: CloudDiscovery): string {\n return new URL(discovery.authURL).origin\n}\n\nexport function parseCloudDiscovery(input: unknown): CloudDiscovery {\n return v.parse(cloudDiscoverySchema, input)\n}\n","import { encodeParam, parseURL, withFragment, withQuery } from 'ufo'\n\n/** The two kinds of Cloud link that carry a secret: invitations and documents shared by link. */\nexport type CloudLinkKind = 'invitations' | 'share'\n\n/**\n * Every kind of Cloud link: those that carry a secret, a document's address for members, and a\n * document of the server's community gallery, which anyone may open.\n */\nexport type CloudLinkPathKind = CloudLinkKind | 'documents' | 'community'\n\nconst CLOUD_LINK_PATH = /^\\/(invitations|share|documents)\\/([^/]+)$/\n/** A community document opened in the editor; `/community/:id` alone is its page. */\nconst COMMUNITY_EDITOR_PATH = /^\\/community\\/([^/]+)\\/open$/\n\n/** The server's community gallery: every document in it, each with a page of its own. */\nexport const CLOUD_COMMUNITY_PATH = '/community'\n\n/**\n * A link on the server's own editor. The server is the link's own address, so the link needs\n * nothing else to name it; a secret travels in the fragment, so it never reaches access logs or\n * `Referer` headers.\n */\nfunction serverLink(\n serverURL: string,\n path: string,\n query: Record<string, string | undefined> = {},\n secret?: string\n): string {\n const { protocol, host } = parseURL(serverURL)\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new Error('A Cloud server address must use HTTP or HTTPS')\n }\n const link = withQuery(`${protocol}//${host}${path}`, query)\n return secret ? withFragment(link, secret) : link\n}\n\n/** An invitation to a document or a workspace, `/invitations/:id#token`. */\nexport function cloudInvitationURL(serverURL: string, invitationId: string, token: string): string {\n return serverLink(serverURL, `/invitations/${encodeParam(invitationId)}`, {}, token)\n}\n\n/** A document shared by link, `/share/:id#secret`. */\nexport function cloudShareURL(serverURL: string, shareId: string, secret: string): string {\n return serverLink(serverURL, `/share/${encodeParam(shareId)}`, {}, secret)\n}\n\n/**\n * A document's address for its members, `/documents/:id`, or one of its versions with\n * `?version=…`. It carries no secret: whoever opens it signs in, and the server decides.\n */\nexport function cloudDocumentURL(\n serverURL: string,\n documentId: string,\n versionId: string | null = null\n): string {\n return serverLink(serverURL, cloudDocumentPath(documentId), {\n version: versionId ?? undefined\n })\n}\n\nexport function cloudDocumentPath(documentId: string): string {\n return `/documents/${encodeParam(documentId)}`\n}\n\n/**\n * A document of the server's community gallery opened in the editor, `/community/:id/open`, or\n * one of its named versions with `?version=…`, which anyone opens read-only without signing in.\n */\nexport function cloudCommunityURL(\n serverURL: string,\n documentId: string,\n versionId: string | null = null\n): string {\n return serverLink(serverURL, cloudCommunityPath(documentId), {\n version: versionId ?? undefined\n })\n}\n\nexport function cloudCommunityPath(documentId: string): string {\n return `${cloudCommunityPagePath(documentId)}/open`\n}\n\n/** A community document's page on the server: its preview, versions, and ways to open it. */\nexport function cloudCommunityPagePath(documentId: string): string {\n return `${CLOUD_COMMUNITY_PATH}/${encodeParam(documentId)}`\n}\n\n/**\n * The kind and ID of a Cloud link's path, or null for any other path. The ID is decoded; a broken\n * escape such as `%E0` is no link.\n */\nexport function parseCloudLinkPath(\n pathname: string\n): { kind: CloudLinkPathKind; id: string } | null {\n const community = pathname.match(COMMUNITY_EDITOR_PATH)\n const [, kind, id] = community\n ? [pathname, 'community' as const, community[1]]\n : (pathname.match(CLOUD_LINK_PATH) ?? [])\n if (\n (kind !== 'invitations' && kind !== 'share' && kind !== 'documents' && kind !== 'community') ||\n !id\n ) {\n return null\n }\n try {\n return { kind, id: decodeURIComponent(id) }\n } catch {\n return null\n }\n}\n\n/**\n * The desktop app's form of a Cloud link, `openpencil://cloud?url=<link>#secret`: the web link,\n * whose address names the server, with its secret kept in the fragment.\n * `desktop/src/launch/links.rs` validates it before the editor sees it.\n */\nexport function cloudDesktopLinkURL(\n kind: CloudLinkKind,\n id: string,\n serverURL: string,\n secret: string\n): string {\n const link = serverLink(serverURL, `/${kind}/${encodeParam(id)}`)\n return withFragment(withQuery('openpencil://cloud', { url: link }), secret)\n}\n\n/**\n * The desktop app's form of a community document's link, `openpencil://cloud?url=<link>`: the\n * editor's address for it, with the named version it asks for, if any. It carries no secret.\n */\nexport function cloudCommunityDesktopLinkURL(\n documentId: string,\n serverURL: string,\n versionId: string | null = null\n): string {\n return withQuery('openpencil://cloud', {\n url: cloudCommunityURL(serverURL, documentId, versionId)\n })\n}\n\n/** A comment thread on a document, `/documents/:id?comment=…`, which opens it. */\nexport function cloudCommentURL(serverURL: string, documentId: string, threadId: string): string {\n return serverLink(serverURL, cloudDocumentPath(documentId), { comment: threadId })\n}\n","/**\n * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for\n * visitors who are not signed in, sign-in and desktop sign-in approval, account settings, and the\n * administration console. Every runtime serves the portal's `cloud.html` at and below these\n * paths, and the editor's `index.html` at the root and at any other page the API does not answer.\n */\nexport const CLOUD_PORTAL_PAGE_ROOTS = ['/welcome', '/auth', '/account', '/admin'] as const\n\n/**\n * The community gallery's pages, which the portal serves too: the gallery at `/community` and a\n * document's page at `/community/:id`. The editor opens a document at `/community/:id/open`.\n */\nexport const CLOUD_PORTAL_COMMUNITY_PAGES = ['/community', '/community/:documentId'] as const\n\nconst COMMUNITY_PAGE = /^\\/community(?:\\/[^/]+)?\\/?$/\n\nexport function isCloudPortalPage(path: string): boolean {\n return (\n COMMUNITY_PAGE.test(path) ||\n CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`))\n )\n}\n","import * as v from 'valibot'\n\nimport { documentDownloadSchema, documentSummarySchema } from './documents'\n\n/** How long a version's name may be; the history list shows the start of longer ones. */\nexport const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100\nexport const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1000\n\n/** A checkpoint the server kept on its own, or a version someone named. */\nexport const documentVersionKindSchema = v.picklist(['checkpoint', 'named'])\nexport type DocumentVersionKind = v.InferOutput<typeof documentVersionKindSchema>\n\nexport const documentVersionSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n revisionId: v.pipe(v.string(), v.uuid()),\n kind: documentVersionKindSchema,\n name: v.nullable(v.string()),\n description: v.nullable(v.string()),\n createdAt: v.string(),\n /** Who made the version: the author of a checkpoint's save, or who named or restored it. */\n createdBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n /** The version this one restored, while that version is still in the history. */\n restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),\n /** Whether the document holds this version now. */\n current: v.boolean()\n})\nexport type DocumentVersion = v.InferOutput<typeof documentVersionSchema>\n\nexport const documentVersionsSchema = v.object({\n versions: v.array(documentVersionSchema),\n /** Pass as `before` for the next, older page; null on the last one. */\n nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))\n})\nexport type DocumentVersions = v.InferOutput<typeof documentVersionsSchema>\n\nconst versionNameSchema = v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(DOCUMENT_VERSION_NAME_MAX_LENGTH)\n)\nconst versionDescriptionSchema = v.pipe(\n v.string(),\n v.trim(),\n v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH)\n)\n\n/** Names the document as it is now, like Save to version history. */\nexport const saveDocumentVersionSchema = v.object({\n name: versionNameSchema,\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type SaveDocumentVersionInput = v.InferOutput<typeof saveDocumentVersionSchema>\n\n/** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */\nexport const updateDocumentVersionSchema = v.object({\n name: v.nullable(versionNameSchema),\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type UpdateDocumentVersionInput = v.InferOutput<typeof updateDocumentVersionSchema>\n\nexport const duplicateDocumentVersionSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))\n})\nexport type DuplicateDocumentVersionInput = v.InferOutput<typeof duplicateDocumentVersionSchema>\n\nexport const documentVersionResponseSchema = v.object({ version: documentVersionSchema })\n/** A version with where to download it, so a link to it can show it without the history. */\nexport const documentVersionDownloadSchema = v.object({\n document: documentDownloadSchema,\n version: documentVersionSchema\n})\nexport type DocumentVersionDownload = v.InferOutput<typeof documentVersionDownloadSchema>\nexport const restoredDocumentSchema = v.object({\n document: documentSummarySchema,\n version: documentVersionSchema\n})\n\nexport function parseSaveDocumentVersion(input: unknown): SaveDocumentVersionInput {\n return v.parse(saveDocumentVersionSchema, input)\n}\nexport function parseUpdateDocumentVersion(input: unknown): UpdateDocumentVersionInput {\n return v.parse(updateDocumentVersionSchema, input)\n}\nexport function parseDuplicateDocumentVersion(input: unknown): DuplicateDocumentVersionInput {\n return v.parse(duplicateDocumentVersionSchema, input)\n}\n","import * as v from 'valibot'\n\nimport { resolveDocumentShareSchema } from './sharing'\n\n/** The most a comment may say, in characters. */\nexport const COMMENT_BODY_MAX_LENGTH = 10_000\n/** The most threads one document may hold, resolved ones included. */\nexport const MAX_COMMENT_THREADS_PER_DOCUMENT = 5_000\n/** The most comments one thread may hold, its first one included. */\nexport const MAX_COMMENTS_PER_THREAD = 500\n/** The most a page, layer or author name in a comment may hold, in characters. */\nexport const COMMENT_NAME_MAX_LENGTH = 255\nconst ID_MAX_LENGTH = 200\n\n/**\n * Who wrote a comment: an account, whose name is null once it is deleted, or a name a file gave\n * when the comment came in with it, which no account vouches for.\n */\nexport const commentAuthorSchema = v.variant('kind', [\n v.object({ kind: v.literal('user'), id: v.string(), name: v.nullable(v.string()) }),\n v.object({ kind: v.literal('imported'), name: v.string() })\n])\nexport type CommentAuthor = v.InferOutput<typeof commentAuthorSchema>\n\nexport const cloudCommentSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n author: commentAuthorSchema,\n /** The agent that wrote it on its author's behalf. */\n agent: v.nullable(v.string()),\n /** Markdown, as the editor writes it. */\n body: v.string(),\n /** The accounts it names, which hear about it. */\n mentions: v.array(v.string()),\n createdAt: v.string(),\n editedAt: v.nullable(v.string())\n})\nexport type CloudComment = v.InferOutput<typeof cloudCommentSchema>\n\n/** Where a pin sits, as the editor places it. */\nconst commentAnchorEntries = {\n pageId: v.pipe(v.string(), v.minLength(1), v.maxLength(ID_MAX_LENGTH)),\n pageName: v.nullable(v.pipe(v.string(), v.maxLength(COMMENT_NAME_MAX_LENGTH))),\n /** The top-level layer the pin follows, if any. */\n nodeId: v.nullable(v.pipe(v.string(), v.minLength(1), v.maxLength(ID_MAX_LENGTH))),\n nodeName: v.nullable(v.pipe(v.string(), v.maxLength(COMMENT_NAME_MAX_LENGTH))),\n /** The pin's offset from the layer's top-left corner. */\n offsetX: v.nullable(v.pipe(v.number(), v.finite())),\n offsetY: v.nullable(v.pipe(v.number(), v.finite())),\n /** The pin's canvas position, used once the layer is gone. */\n x: v.pipe(v.number(), v.finite()),\n y: v.pipe(v.number(), v.finite())\n}\nexport const commentAnchorSchema = v.object(commentAnchorEntries)\nexport type CommentAnchor = v.InferOutput<typeof commentAnchorSchema>\n\nexport const cloudCommentThreadSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n ...commentAnchorEntries,\n createdAt: v.string(),\n /** When anything in the thread last changed: a comment, the pin, or whether it is resolved. */\n updatedAt: v.string(),\n resolvedAt: v.nullable(v.string()),\n resolvedBy: v.nullable(v.string()),\n /** Who started it, or brought it in from a file: they may move its pin and delete it. */\n createdBy: v.string(),\n /** Whether someone else wrote in it since the asker last read it; false for a guest. */\n unread: v.boolean(),\n /** Oldest first; the first is what started the thread. */\n comments: v.array(cloudCommentSchema)\n})\nexport type CloudCommentThread = v.InferOutput<typeof cloudCommentThreadSchema>\n\n/** What the person asking may do with the document's comments. */\nexport const commentAccessSchema = v.object({\n /** Start threads, reply, and change their own comments; anyone signed in who can view. */\n canComment: v.boolean(),\n /** Delete anyone's comments; editors. */\n canModerate: v.boolean(),\n /** The asker's account, which their own comments name; null for a guest. */\n accountId: v.nullable(v.string())\n})\nexport type CommentAccess = v.InferOutput<typeof commentAccessSchema>\n\nexport const commentThreadsSchema = v.object({\n threads: v.array(cloudCommentThreadSchema),\n access: commentAccessSchema\n})\nexport type CommentThreads = v.InferOutput<typeof commentThreadsSchema>\n\nexport const commentThreadResponseSchema = v.object({ thread: cloudCommentThreadSchema })\n\nconst bodySchema = v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(COMMENT_BODY_MAX_LENGTH)\n)\n/** The most accounts one comment names. */\nexport const MAX_COMMENT_MENTIONS = 50\n/** The accounts a comment names; the server keeps those who can read the document. */\nconst mentionsSchema = v.optional(\n v.pipe(\n v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(200))),\n v.maxLength(MAX_COMMENT_MENTIONS)\n ),\n []\n)\n/** The longest agent name a comment keeps. */\nexport const MAX_COMMENT_AGENT_LENGTH = 100\nconst agentSchema = v.optional(\n v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_COMMENT_AGENT_LENGTH))\n)\n/**\n * The ID the editor gave a new thread or comment, so it keeps showing it as the server's, and a\n * request sent again finds what the first one made.\n */\nconst clientIdSchema = v.optional(v.pipe(v.string(), v.uuid()))\n\nexport const createCommentThreadSchema = v.object({\n id: clientIdSchema,\n ...commentAnchorEntries,\n body: bodySchema,\n mentions: mentionsSchema,\n agent: agentSchema\n})\nexport type CreateCommentThreadInput = v.InferOutput<typeof createCommentThreadSchema>\n\n/** Resolves or reopens a thread, or moves its pin; what is left out stays as it is. */\nexport const updateCommentThreadSchema = v.object({\n resolved: v.optional(v.boolean()),\n anchor: v.optional(commentAnchorSchema)\n})\nexport type UpdateCommentThreadInput = v.InferOutput<typeof updateCommentThreadSchema>\n\nexport const createCommentSchema = v.object({\n id: clientIdSchema,\n body: bodySchema,\n mentions: mentionsSchema,\n agent: agentSchema\n})\nexport type CreateCommentInput = v.InferOutput<typeof createCommentSchema>\n\nexport const updateCommentSchema = v.object({ body: bodySchema, mentions: mentionsSchema })\nexport type UpdateCommentInput = v.InferOutput<typeof updateCommentSchema>\n\n/** Someone a comment may name: an account that can open the document. */\nexport const commentPersonSchema = v.object({\n id: v.string(),\n name: v.string(),\n image: v.nullable(v.string())\n})\nexport type CommentPerson = v.InferOutput<typeof commentPersonSchema>\nexport const commentPeopleSchema = v.object({ people: v.array(commentPersonSchema) })\n\n/** Which comments an account hears about by email. */\nexport const commentEmailSettingSchema = v.picklist(['all', 'mentions', 'off'])\nexport type CommentEmailSetting = v.InferOutput<typeof commentEmailSettingSchema>\nexport const notificationSettingsSchema = v.object({ commentEmails: commentEmailSettingSchema })\nexport type NotificationSettings = v.InferOutput<typeof notificationSettingsSchema>\n\n/** The most threads, and comments in all, one import brings in. */\nexport const MAX_IMPORTED_COMMENT_THREADS = 1_000\nexport const MAX_IMPORTED_COMMENTS = 10_000\n\n/**\n * Threads a file held when it moved to Cloud. Their authors are names the file gave, which the\n * server keeps as such; their times are the file's.\n */\nexport const importCommentThreadsSchema = v.object({\n threads: v.pipe(\n v.array(\n v.object({\n ...commentAnchorEntries,\n createdAt: v.pipe(v.string(), v.isoTimestamp()),\n resolved: v.boolean(),\n // A file's thread comes in whole, however long; only new replies keep to the limit.\n comments: v.pipe(\n v.array(\n v.object({\n authorName: v.pipe(v.string(), v.trim(), v.maxLength(COMMENT_NAME_MAX_LENGTH)),\n body: bodySchema,\n createdAt: v.pipe(v.string(), v.isoTimestamp())\n })\n ),\n v.minLength(1),\n v.maxLength(MAX_IMPORTED_COMMENTS)\n )\n })\n ),\n v.maxLength(MAX_IMPORTED_COMMENT_THREADS),\n v.check(\n (threads) =>\n threads.reduce((total, thread) => total + thread.comments.length, 0) <=\n MAX_IMPORTED_COMMENTS,\n `An import brings in at most ${MAX_IMPORTED_COMMENTS} comments`\n )\n )\n})\nexport type ImportCommentThreadsInput = v.InferOutput<typeof importCommentThreadsSchema>\n\n/**\n * The same requests made through a share link: the link's secret rides in the body, as it does\n * for opening the document, since it must stay out of the address.\n */\nconst shareEntries = { share: v.pick(resolveDocumentShareSchema, ['secret']) }\nexport const sharedCommentsRequestSchema = v.object(shareEntries)\nexport const sharedCreateCommentThreadSchema = v.object({\n ...shareEntries,\n ...createCommentThreadSchema.entries\n})\nexport const sharedUpdateCommentThreadSchema = v.object({\n ...shareEntries,\n ...updateCommentThreadSchema.entries\n})\nexport const sharedCreateCommentSchema = v.object({\n ...shareEntries,\n ...createCommentSchema.entries\n})\nexport const sharedUpdateCommentSchema = v.object({\n ...shareEntries,\n ...updateCommentSchema.entries\n})\nexport type SharedCommentsRequest = v.InferOutput<typeof sharedCommentsRequestSchema>\n","import * as v from 'valibot'\n\nimport { documentDownloadSchema, documentKindSchema } from './documents'\n\n/**\n * Where a community document's thumbnail is served, by its document and revision: the address\n * changes with each save, so a cached copy never shows an older state.\n */\nexport const COMMUNITY_THUMBNAIL_PATH = '/api/community/thumbnails'\n\nexport function communityThumbnailPath(documentId: string, revisionId: string): string {\n return `${COMMUNITY_THUMBNAIL_PATH}/${documentId}/${revisionId}`\n}\n\n/** A version of a community document someone named, such as the release it was published for. */\nexport const communityVersionSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n description: v.nullable(v.string()),\n createdAt: v.string(),\n /** Whether the document holds this version now, with nothing changed since it was named. */\n current: v.boolean()\n})\nexport type CommunityVersion = v.InferOutput<typeof communityVersionSchema>\n\n/**\n * A document in the deployment's community workspace, which anyone may open read-only: its name,\n * when it last changed, its thumbnail's path on the server, and its named versions, newest first.\n */\nexport const communityDocumentSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n kind: documentKindSchema,\n updatedAt: v.string(),\n revisionId: v.pipe(v.string(), v.uuid()),\n thumbnailPath: v.string(),\n versions: v.array(communityVersionSchema)\n})\nexport type CommunityDocument = v.InferOutput<typeof communityDocumentSchema>\n\n/** The community workspace's documents, most recently changed first. */\nexport const communityDocumentsSchema = v.object({ documents: v.array(communityDocumentSchema) })\nexport type CommunityDocuments = v.InferOutput<typeof communityDocumentsSchema>\n\n/** Which state of a community document to open: a named version, or else the latest. */\nexport const communityDownloadQuerySchema = v.object({\n version: v.optional(v.pipe(v.string(), v.uuid()))\n})\nexport type CommunityDownloadQuery = v.InferOutput<typeof communityDownloadQuerySchema>\n\nexport function parseCommunityDownloadQuery(input: unknown): CommunityDownloadQuery {\n return v.parse(communityDownloadQuerySchema, input)\n}\n\n/** A community document, or one of its named versions, with where to download it. */\nexport const communityDownloadSchema = v.object({\n document: documentDownloadSchema,\n version: v.nullable(communityVersionSchema)\n})\nexport type CommunityDownload = v.InferOutput<typeof communityDownloadSchema>\n","<script setup lang=\"ts\">\nimport { CLOUD_SOCIAL_PROVIDER_NAMES, isKnownSocialProvider } from '#cloud/contract'\n\nimport type { TwoStepChange, TwoStepChangedPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { greeting, useEmailLocalization } from './localization'\n\n/**\n * How the account proves it's its owner's changed: an authenticator app, a passkey, or a way to\n * sign in an administrator removed.\n */\nconst { payload } = defineProps<{ payload: TwoStepChangedPayload }>()\n\nconst localization = useEmailLocalization()\nconst { t } = localization\n// Provider names stay as their owners write them; a password is named in the reader's words.\nfunction methodName(provider: string): string {\n if (provider === 'credential') return t.signInMethodPassword\n return isKnownSocialProvider(provider) ? CLOUD_SOCIAL_PROVIDER_NAMES[provider] : provider\n}\nconst method = payload.method ? methodName(payload.method) : ''\nconst changes: Record<TwoStepChange, { heading: string; message: string }> = {\n 'authenticator-on': { heading: t.authenticatorOnHeading, message: t.authenticatorOn },\n 'authenticator-off': { heading: t.authenticatorOffHeading, message: t.authenticatorOff },\n 'passkey-added': { heading: t.passkeyAddedHeading, message: t.passkeyAdded },\n 'passkey-removed': { heading: t.passkeyRemovedHeading, message: t.passkeyRemoved },\n 'reset-by-administrator': { heading: t.twoStepResetHeading, message: t.twoStepReset },\n 'sign-in-method-removed': {\n heading: t.signInMethodRemovedHeading,\n message: t.signInMethodRemoved({ method })\n }\n}\nconst change = changes[payload.change]\n</script>\n\n<template>\n <BrandEmail\n :preview=\"change.message\"\n :heading=\"change.heading\"\n :action=\"{ label: t.reviewSecurity, url: payload.actionURL }\"\n >\n <EmailText>{{ greeting(localization, payload.name) }}</EmailText>\n <EmailText>{{ change.message }}</EmailText>\n <EmailText>{{ t.twoStepNotYou }}</EmailText>\n </BrandEmail>\n</template>\n","<script setup lang=\"ts\">\nimport type { WorkspaceInvitationEmailPayload } from '../schema'\nimport BrandEmail from './BrandEmail.vue'\nimport EmailText from './EmailText.vue'\nimport { useEmailLocalization } from './localization'\n\nconst { payload } = defineProps<{ payload: WorkspaceInvitationEmailPayload }>()\n\nconst { t, dateTime } = useEmailLocalization()\nconst names = { inviter: payload.inviterName ?? t.someone, workspace: payload.workspaceName }\nconst message = {\n admin: t.workspaceInvitationAdmin,\n editor: t.workspaceInvitationEditor,\n viewer: t.workspaceInvitationViewer\n}[payload.role](names)\n</script>\n\n<template>\n <BrandEmail\n :preview=\"t.workspaceInvitationSubject(names)\"\n :heading=\"t.workspaceInvitationHeading(names)\"\n :action=\"{ label: t.workspaceInvitationAction, url: payload.acceptanceURL }\"\n >\n <EmailText>{{ message }}</EmailText>\n <EmailText>{{ t.workspaceInvitationHome }}</EmailText>\n <template #note>{{ t.invitationExpires({ date: dateTime(payload.expiresAt) }) }}</template>\n </BrandEmail>\n</template>\n","import { render } from '@vue-email/render'\nimport type { Component } from 'vue'\n\nimport {\n emailLocalization,\n type EmailLocale,\n type EmailLocalization,\n type EmailMessages\n} from './i18n'\nimport type {\n DocumentInvitationEmailPayload,\n RenderedTransactionalEmail,\n TransactionalEmailContent,\n TransactionalEmailKind,\n TransactionalEmailPayloadByKind\n} from './schema'\nimport CommentNotification from './templates/CommentNotification.vue'\nimport DocumentBlocked from './templates/DocumentBlocked.vue'\nimport DocumentInvitation from './templates/DocumentInvitation.vue'\nimport DocumentReport from './templates/DocumentReport.vue'\nimport DocumentReportDecided from './templates/DocumentReportDecided.vue'\nimport DocumentReportReceived from './templates/DocumentReportReceived.vue'\nimport DocumentRestored from './templates/DocumentRestored.vue'\nimport EmailChangeRequested from './templates/EmailChangeRequested.vue'\nimport EmailRoot from './templates/EmailRoot.vue'\nimport EmailVerification from './templates/EmailVerification.vue'\nimport EnrollmentInvitation from './templates/EnrollmentInvitation.vue'\nimport EnrollmentNotification from './templates/EnrollmentNotification.vue'\nimport EnrollmentUpdate from './templates/EnrollmentUpdate.vue'\nimport NewSignIn from './templates/NewSignIn.vue'\nimport PasswordChanged from './templates/PasswordChanged.vue'\nimport PasswordReset from './templates/PasswordReset.vue'\nimport StorageLimitReached from './templates/StorageLimitReached.vue'\nimport TwoStepChanged from './templates/TwoStepChanged.vue'\nimport WaitlistConfirmation from './templates/WaitlistConfirmation.vue'\nimport WorkspaceInvitation from './templates/WorkspaceInvitation.vue'\n\n/** One kind of email: the component that draws it from its payload, and its subject line. */\ntype EmailDefinition<Payload> = {\n component: Component\n /** What the component takes besides `payload`. */\n props?: Record<string, unknown>\n subject: (payload: Payload, t: EmailMessages) => string\n}\n\nfunction documentInvitationSubject(payload: DocumentInvitationEmailPayload, t: EmailMessages) {\n const names = { inviter: payload.inviterName ?? t.someone, document: payload.documentName }\n return payload.permission === 'edit'\n ? t.documentInvitationEditSubject(names)\n : t.documentInvitationViewSubject(names)\n}\n\nconst EMAILS: {\n [Kind in TransactionalEmailKind]: EmailDefinition<TransactionalEmailPayloadByKind[Kind]>\n} = {\n 'document-invitation': { component: DocumentInvitation, subject: documentInvitationSubject },\n 'workspace-invitation': {\n component: WorkspaceInvitation,\n subject: (payload, t) =>\n t.workspaceInvitationSubject({\n inviter: payload.inviterName ?? t.someone,\n workspace: payload.workspaceName\n })\n },\n 'enrollment-requested': {\n component: EnrollmentUpdate,\n props: { kind: 'requested' },\n subject: (_payload, t) => t.enrollmentRequestedSubject\n },\n 'enrollment-approved': {\n component: EnrollmentUpdate,\n props: { kind: 'approved' },\n subject: (_payload, t) => t.enrollmentApprovedSubject\n },\n 'enrollment-rejected': {\n component: EnrollmentUpdate,\n props: { kind: 'rejected' },\n subject: (_payload, t) => t.enrollmentRejectedSubject\n },\n 'enrollment-revoked': {\n component: EnrollmentUpdate,\n props: { kind: 'revoked' },\n subject: (_payload, t) => t.enrollmentRevokedSubject\n },\n 'enrollment-invited': {\n component: EnrollmentInvitation,\n subject: (payload, t) => (payload.waitlist ? t.invitationWaitlistSubject : t.invitationSubject)\n },\n 'admin-enrollment-notification': {\n component: EnrollmentNotification,\n subject: (_payload, t) => t.enrollmentNotificationSubject\n },\n 'email-verification': {\n component: EmailVerification,\n subject: (payload, t) =>\n payload.purpose === 'change' ? t.verifyChangeSubject : t.verifyAccountSubject\n },\n 'password-reset': { component: PasswordReset, subject: (_payload, t) => t.passwordResetSubject },\n 'password-changed': {\n component: PasswordChanged,\n subject: (_payload, t) => t.passwordChangedSubject\n },\n 'email-change-requested': {\n component: EmailChangeRequested,\n subject: (_payload, t) => t.emailChangeSubject\n },\n 'new-sign-in': { component: NewSignIn, subject: (_payload, t) => t.newSignInSubject },\n 'two-step-changed': { component: TwoStepChanged, subject: (_payload, t) => t.twoStepSubject },\n 'document-report': {\n component: DocumentReport,\n subject: (_payload, t) => t.documentReportSubject\n },\n 'storage-limit-reached': {\n component: StorageLimitReached,\n subject: (_payload, t) => t.storageFullSubject\n },\n 'document-blocked': {\n component: DocumentBlocked,\n subject: (payload, t) => t.documentBlockedSubject({ document: payload.documentName })\n },\n 'document-restored': {\n component: DocumentRestored,\n subject: (payload, t) => t.documentRestoredSubject({ document: payload.documentName })\n },\n 'document-report-received': {\n component: DocumentReportReceived,\n subject: (payload, t) => t.reportReceivedSubject({ document: payload.documentName })\n },\n 'document-report-decided': {\n component: DocumentReportDecided,\n subject: (payload, t) => t.reportDecidedSubject({ document: payload.documentName })\n },\n 'comment-notification': {\n component: CommentNotification,\n subject: (payload, t) => {\n const words = {\n author: payload.authorName ?? t.commentSomeone,\n document: payload.documentName\n }\n return payload.reason === 'mention'\n ? t.commentMentionSubject(words)\n : t.commentReplySubject(words)\n }\n }\n}\n\n/** Renders an email component as HTML and as plain text, in its reader's language. */\nasync function renderComponent(\n email: Component,\n props: Record<string, unknown>,\n subject: string,\n localization: EmailLocalization\n): Promise<RenderedTransactionalEmail> {\n const root = { email, props, localization }\n const [html, text] = await Promise.all([\n render(EmailRoot, root),\n render(EmailRoot, root, { plainText: true })\n ])\n return { subject, html, text }\n}\n\nfunction renderKind<Kind extends TransactionalEmailKind>(\n kind: Kind,\n payload: TransactionalEmailPayloadByKind[Kind],\n localization: EmailLocalization\n) {\n const { component, props, subject } = EMAILS[kind]\n const content = { ...props, payload }\n return renderComponent(component, content, subject(payload, localization.t), localization)\n}\n\nexport async function renderTransactionalEmail(\n content: TransactionalEmailContent,\n locale: EmailLocale\n): Promise<RenderedTransactionalEmail> {\n return renderKind(content.kind, content.payload, emailLocalization(locale))\n}\n\n/** The waitlist's confirmation email, which the feedback service sends rather than Cloud. */\nexport async function renderWaitlistConfirmation(\n links: { confirmURL: string; leaveURL: string },\n locale: EmailLocale\n): Promise<RenderedTransactionalEmail> {\n const localization = emailLocalization(locale)\n return renderComponent(WaitlistConfirmation, links, localization.t.waitlistSubject, localization)\n}\n","import {\n documentPermissionSchema,\n documentReportReasonSchema,\n workspaceRoleSchema\n} from '#cloud/contract'\nimport * as v from 'valibot'\n\nexport type TransactionalEmailKind =\n | 'document-invitation'\n | 'workspace-invitation'\n | 'enrollment-requested'\n | 'admin-enrollment-notification'\n | 'enrollment-approved'\n | 'enrollment-rejected'\n | 'enrollment-revoked'\n | 'enrollment-invited'\n | 'email-verification'\n | 'password-reset'\n | 'password-changed'\n | 'email-change-requested'\n | 'new-sign-in'\n | 'two-step-changed'\n | 'document-report'\n | 'storage-limit-reached'\n | 'document-blocked'\n | 'document-restored'\n | 'document-report-received'\n | 'document-report-decided'\n | 'comment-notification'\n\nconst documentInvitationEmailPayloadSchema = v.object({\n /** Null when the inviter's account is gone, so the email says someone invited you. */\n inviterName: v.nullable(v.string()),\n documentName: v.string(),\n permission: documentPermissionSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst workspaceInvitationEmailPayloadSchema = v.object({\n /** Null when the inviter's account is gone, so the email says someone invited you. */\n inviterName: v.nullable(v.string()),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst enrollmentEmailPayloadSchema = v.object({\n /** Null when the request named no one, so the email greets no one by name. */\n name: v.nullable(v.string()),\n actionURL: v.string(),\n /** An invitation letter to someone from openpencil.dev's waitlist, who asked nowhere else. */\n waitlist: v.optional(v.literal(true))\n})\n\nconst adminEnrollmentNotificationPayloadSchema = v.object({\n requesterEmail: v.string(),\n requesterName: v.string(),\n reason: v.string(),\n actionURL: v.string()\n})\n\nconst documentReportPayloadSchema = v.object({\n documentName: v.string(),\n reason: documentReportReasonSchema,\n description: v.string(),\n actionURL: v.string()\n})\n\nconst storageLimitReachedPayloadSchema = v.object({\n name: v.string(),\n usedBytes: v.number(),\n limitBytes: v.number(),\n /** Whether the server sells plans, so the account can get more storage rather than only free it. */\n upgradable: v.boolean(),\n actionURL: v.string()\n})\n\n/** To a workspace's owner: an administrator took one of its documents down. */\nconst documentBlockedPayloadSchema = v.object({\n /** The owner's name, or null when the account has none. */\n name: v.nullable(v.string()),\n documentName: v.string(),\n /** Why, as the administrator wrote it, or null when they gave no reason. */\n reason: v.nullable(v.string()),\n /** Where to write to contest it: the deployment's abuse address, or null without one. */\n contactEmail: v.nullable(v.pipe(v.string(), v.email())),\n actionURL: v.string()\n})\n\n/** To a workspace's owner: a document taken down is back. */\nconst documentRestoredPayloadSchema = v.object({\n name: v.nullable(v.string()),\n documentName: v.string(),\n actionURL: v.string()\n})\n\n/** To whoever reported a document: their report arrived. */\nconst documentReportReceivedPayloadSchema = v.object({ documentName: v.string() })\n\n/** To whoever reported a document: what the administrators decided. */\nconst documentReportDecidedPayloadSchema = v.object({\n documentName: v.string(),\n /** The document blocked, the report acted on some other way, or the document left as it was. */\n outcome: v.picklist(['blocked', 'actioned', 'dismissed']),\n /** Where to write to disagree: the deployment's abuse address, or null without one. */\n contactEmail: v.nullable(v.pipe(v.string(), v.email()))\n})\n\n/** To someone a comment names, or who takes part in its thread: what it says, and where. */\nconst commentNotificationPayloadSchema = v.object({\n /** The recipient's name, or null when the account has none. */\n name: v.nullable(v.string()),\n /** Who wrote the comment, or null when the account has no name. */\n authorName: v.nullable(v.string()),\n documentName: v.string(),\n /** The comment names the recipient, or answers a thread they take part in. */\n reason: v.picklist(['mention', 'reply']),\n /** The start of what the comment says. */\n excerpt: v.string(),\n actionURL: v.string(),\n /** Where the recipient chooses which comments they hear about. */\n settingsURL: v.string()\n})\n\nconst authenticationEmailPayloadSchema = v.object({\n name: v.string(),\n actionURL: v.optional(v.string()),\n /** What a verification link confirms: a new account, or a new address for one. */\n purpose: v.optional(v.picklist(['account', 'change']))\n})\n\nconst emailChangeRequestedPayloadSchema = v.object({\n name: v.string(),\n newEmail: v.string(),\n actionURL: v.string()\n})\n\nconst newSignInPayloadSchema = v.object({\n name: v.string(),\n signedInAt: v.string(),\n ipAddress: v.nullable(v.string()),\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n desktop: v.boolean(),\n actionURL: v.string()\n})\n\n/** What changed about how an account proves it is its owner's. */\nexport const twoStepChangeSchema = v.picklist([\n 'authenticator-on',\n 'authenticator-off',\n 'passkey-added',\n 'passkey-removed',\n 'reset-by-administrator',\n 'sign-in-method-removed'\n])\n\nconst twoStepChangedPayloadSchema = v.object({\n name: v.string(),\n change: twoStepChangeSchema,\n /** For a removed sign-in method, which: `credential` for a password, or a provider. */\n method: v.optional(v.string()),\n actionURL: v.string()\n})\n\nfunction content<const Kind extends TransactionalEmailKind, Payload extends v.GenericSchema>(\n kind: Kind,\n payload: Payload\n) {\n return v.object({ kind: v.literal(kind), payload })\n}\n\nexport const transactionalEmailContentSchema = v.variant('kind', [\n content('document-invitation', documentInvitationEmailPayloadSchema),\n content('workspace-invitation', workspaceInvitationEmailPayloadSchema),\n content('enrollment-requested', enrollmentEmailPayloadSchema),\n content('admin-enrollment-notification', adminEnrollmentNotificationPayloadSchema),\n content('enrollment-approved', enrollmentEmailPayloadSchema),\n content('enrollment-rejected', enrollmentEmailPayloadSchema),\n content('enrollment-revoked', enrollmentEmailPayloadSchema),\n content('enrollment-invited', enrollmentEmailPayloadSchema),\n content('email-verification', authenticationEmailPayloadSchema),\n content('password-reset', authenticationEmailPayloadSchema),\n content('password-changed', authenticationEmailPayloadSchema),\n content('email-change-requested', emailChangeRequestedPayloadSchema),\n content('new-sign-in', newSignInPayloadSchema),\n content('two-step-changed', twoStepChangedPayloadSchema),\n content('document-report', documentReportPayloadSchema),\n content('storage-limit-reached', storageLimitReachedPayloadSchema),\n content('document-blocked', documentBlockedPayloadSchema),\n content('document-restored', documentRestoredPayloadSchema),\n content('document-report-received', documentReportReceivedPayloadSchema),\n content('document-report-decided', documentReportDecidedPayloadSchema),\n content('comment-notification', commentNotificationPayloadSchema)\n])\n\n/** A transactional email's kind with the payload that kind renders. */\nexport type TransactionalEmailContent = v.InferOutput<typeof transactionalEmailContentSchema>\n\nexport type DocumentInvitationEmailPayload = v.InferOutput<\n typeof documentInvitationEmailPayloadSchema\n>\nexport type WorkspaceInvitationEmailPayload = v.InferOutput<\n typeof workspaceInvitationEmailPayloadSchema\n>\nexport type EnrollmentEmailPayload = v.InferOutput<typeof enrollmentEmailPayloadSchema>\nexport type AdminEnrollmentNotificationPayload = v.InferOutput<\n typeof adminEnrollmentNotificationPayloadSchema\n>\nexport type AuthenticationEmailPayload = v.InferOutput<typeof authenticationEmailPayloadSchema>\nexport type EmailChangeRequestedPayload = v.InferOutput<typeof emailChangeRequestedPayloadSchema>\nexport type NewSignInPayload = v.InferOutput<typeof newSignInPayloadSchema>\nexport type TwoStepChange = v.InferOutput<typeof twoStepChangeSchema>\nexport type TwoStepChangedPayload = v.InferOutput<typeof twoStepChangedPayloadSchema>\n\nexport type TransactionalEmailPayloadByKind = {\n [Kind in TransactionalEmailKind]: Extract<TransactionalEmailContent, { kind: Kind }>['payload']\n}\n\nexport type TransactionalEmailMessage<\n Kind extends TransactionalEmailKind = TransactionalEmailKind\n> = {\n id: string\n kind: Kind\n recipientEmail: string\n payload: TransactionalEmailPayloadByKind[Kind]\n}\n\nexport type RenderedTransactionalEmail = {\n subject: string\n html: string\n text: string\n}\nexport type DocumentReportPayload = v.InferOutput<typeof documentReportPayloadSchema>\nexport type StorageLimitReachedPayload = v.InferOutput<typeof storageLimitReachedPayloadSchema>\nexport type DocumentBlockedPayload = v.InferOutput<typeof documentBlockedPayloadSchema>\nexport type DocumentRestoredPayload = v.InferOutput<typeof documentRestoredPayloadSchema>\nexport type DocumentReportReceivedPayload = v.InferOutput<\n typeof documentReportReceivedPayloadSchema\n>\nexport type DocumentReportDecidedPayload = v.InferOutput<typeof documentReportDecidedPayloadSchema>\nexport type CommentNotificationPayload = v.InferOutput<typeof commentNotificationPayloadSchema>\n","import {\n transactionalEmailContentSchema,\n type TransactionalEmailContent,\n type TransactionalEmailKind,\n type TransactionalEmailPayloadByKind\n} from '#cloud/email'\nimport { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\nimport * as v from 'valibot'\n\nconst EMAIL_PAYLOAD_SALT = utf8ToBytes('openpencil-cloud-transactional-email')\nconst EMAIL_PAYLOAD_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nfunction emailPayloadKey(secret: string, id: string, kind: TransactionalEmailKind): Uint8Array {\n return hkdf(\n sha256,\n utf8ToBytes(secret),\n EMAIL_PAYLOAD_SALT,\n encoder.encode(`openpencil-cloud-email:${kind}:${id}`),\n 32\n )\n}\n\nexport async function encryptTransactionalEmailPayload<Kind extends TransactionalEmailKind>(\n secret: string,\n id: string,\n kind: Kind,\n payload: TransactionalEmailPayloadByKind[Kind]\n): Promise<string> {\n return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))\n .setProtectedHeader(EMAIL_PAYLOAD_HEADER)\n .encrypt(emailPayloadKey(secret, id, kind))\n}\n\nexport async function decryptTransactionalEmailPayload(\n secret: string,\n id: string,\n kind: TransactionalEmailKind,\n value: string\n): Promise<TransactionalEmailContent> {\n const { plaintext, protectedHeader } = await compactDecrypt(\n value,\n emailPayloadKey(secret, id, kind)\n )\n if (\n protectedHeader.alg !== EMAIL_PAYLOAD_HEADER.alg ||\n protectedHeader.enc !== EMAIL_PAYLOAD_HEADER.enc\n ) {\n throw new Error('Unsupported transactional email payload encryption')\n }\n const payload = v.parse(v.pipe(v.string(), v.parseJson()), decoder.decode(plaintext))\n return v.parse(transactionalEmailContentSchema, { kind, payload })\n}\n","import { renderTransactionalEmail } from '#cloud/email'\nimport type { EmailLocale, TransactionalEmailKind } from '#cloud/email'\nimport type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { backoffDelay, HOUR_MS, SECOND_MS, type Backoff } from '@open-pencil/std/timing'\n\nimport { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'\nimport type {\n EnqueueTransactionalEmailInput,\n TransactionalEmailDeliveryOptions,\n TransactionalEmailDeliveryResult,\n TransactionalEmailService,\n TransactionalEmailTransport\n} from './types'\n\nconst DEFAULT_MAXIMUM_ATTEMPTS = 5\n/** Mail is retried patiently: a provider that refused it is rarely back within seconds. */\nconst EMAIL_RETRY: Backoff = { baseMs: 30 * SECOND_MS, capMs: HOUR_MS, jitter: false }\n\nexport type TransactionalEmailTransportErrorKind =\n | 'configuration'\n | 'suppressed'\n | 'permanent'\n | 'rate-limited'\n | 'transient'\n\nexport class TransactionalEmailTransportError extends Error {\n override readonly name = 'TransactionalEmailTransportError'\n\n constructor(\n readonly kind: TransactionalEmailTransportErrorKind,\n readonly code: string,\n message: string,\n options?: ErrorOptions\n ) {\n super(message, options)\n }\n}\n\ntype ClaimedTransactionalEmail = {\n id: string\n kind: TransactionalEmailKind\n recipientEmailNormalized: string\n payloadEncrypted: string\n locale: EmailLocale\n attemptCount: number\n}\n\nfunction normalizedEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nfunction retryDelayMilliseconds(attemptCount: number): number {\n return backoffDelay(attemptCount - 1, EMAIL_RETRY)\n}\n\nfunction transportFailure(error: unknown): TransactionalEmailTransportError {\n return error instanceof TransactionalEmailTransportError\n ? error\n : new TransactionalEmailTransportError(\n 'transient',\n 'transport_error',\n 'Transactional email transport failed',\n { cause: error }\n )\n}\n\nfunction failureStatus(\n error: TransactionalEmailTransportError,\n attemptCount: number,\n maximumAttempts: number\n): TransactionalEmailStatus {\n if (error.kind === 'suppressed') return 'suppressed'\n if (error.kind === 'configuration' || error.kind === 'permanent') return 'failed'\n return attemptCount >= maximumAttempts ? 'failed' : 'pending'\n}\n\nexport function createTransactionalEmailService(\n database: Kysely<CloudDatabase>,\n options: {\n encryptionSecret: string\n from: string\n /** Where replies go; mail clients answer `from` without it. */\n replyTo?: string\n transport?: TransactionalEmailTransport\n }\n): TransactionalEmailService {\n return {\n async enqueue<Kind extends TransactionalEmailKind>(\n input: EnqueueTransactionalEmailInput<Kind>,\n transaction: Transaction<CloudDatabase> | undefined\n ): Promise<string> {\n const id = crypto.randomUUID()\n const payloadEncrypted = await encryptTransactionalEmailPayload(\n options.encryptionSecret,\n id,\n input.kind,\n input.payload\n )\n const executor = transaction ?? database\n const recipientEmailNormalized = normalizedEmail(input.recipientEmail)\n // An account is written to in the language it chose, whoever sends to it.\n const recipientLocale =\n input.recipientLocale !== undefined\n ? input.recipientLocale\n : (\n await executor\n .selectFrom('user')\n .select('locale')\n .where((expression) =>\n expression(\n expression.fn('lower', [expression.ref('email')]),\n '=',\n recipientEmailNormalized\n )\n )\n .executeTakeFirst()\n )?.locale\n const row = await executor\n .insertInto('transactionalEmail')\n .values({\n id,\n idempotencyKey: input.idempotencyKey,\n kind: input.kind,\n recipientEmailNormalized,\n payloadEncrypted,\n locale: recipientLocale ?? input.fallbackLocale ?? 'en',\n status: 'pending',\n nextAttemptAt: new Date(),\n claimId: null,\n claimedAt: null,\n transport: null,\n transportMessageId: null,\n lastErrorCode: null,\n acceptedAt: null\n })\n .onConflict((conflict) => conflict.column('idempotencyKey').doNothing())\n .returning('id')\n .executeTakeFirst()\n if (row) return row.id\n return (\n await executor\n .selectFrom('transactionalEmail')\n .select('id')\n .where('idempotencyKey', '=', input.idempotencyKey)\n .executeTakeFirstOrThrow()\n ).id\n },\n\n async deliverPending(\n deliveryOptions: TransactionalEmailDeliveryOptions\n ): Promise<TransactionalEmailDeliveryResult> {\n if (!options.transport) {\n return { claimed: 0, accepted: 0, retrying: 0, failed: 0, suppressed: 0 }\n }\n const now = deliveryOptions.now ?? new Date()\n const maximumAttempts = deliveryOptions.maximumAttempts ?? DEFAULT_MAXIMUM_ATTEMPTS\n const staleBefore = new Date(now.getTime() - deliveryOptions.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const claimed = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('transactionalEmail')\n .select([\n 'id',\n 'kind',\n 'recipientEmailNormalized',\n 'payloadEncrypted',\n 'locale',\n 'attemptCount'\n ])\n .where('payloadEncrypted', 'is not', null)\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('nextAttemptAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'sending'),\n expression('claimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('nextAttemptAt')\n .limit(deliveryOptions.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n await transaction\n .updateTable('transactionalEmail')\n .set({ status: 'sending', claimId, claimedAt: now, updatedAt: now })\n .where(\n 'id',\n 'in',\n candidates.map((candidate) => candidate.id)\n )\n .execute()\n return candidates.filter(\n (candidate): candidate is ClaimedTransactionalEmail => candidate.payloadEncrypted !== null\n )\n })\n\n const result: TransactionalEmailDeliveryResult = {\n claimed: claimed.length,\n accepted: 0,\n retrying: 0,\n failed: 0,\n suppressed: 0\n }\n for (const message of claimed) {\n const attemptCount = message.attemptCount + 1\n try {\n const content = await decryptTransactionalEmailPayload(\n options.encryptionSecret,\n message.id,\n message.kind,\n message.payloadEncrypted\n )\n const rendered = await renderTransactionalEmail(content, message.locale)\n const sent = await options.transport.send({\n deliveryId: message.id,\n from: options.from,\n replyTo: options.replyTo,\n to: message.recipientEmailNormalized,\n subject: rendered.subject,\n html: rendered.html,\n text: rendered.text,\n headers: { 'X-OpenPencil-Delivery-ID': message.id }\n })\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: null,\n status: 'accepted',\n attemptCount,\n transport: options.transport.id,\n transportMessageId: sent.transportMessageId,\n lastErrorCode: null,\n acceptedAt: new Date(sent.acceptedAt),\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n result.accepted++\n } catch (unknownError) {\n const error = transportFailure(unknownError)\n const status = failureStatus(error, attemptCount, maximumAttempts)\n const terminal = status === 'failed' || status === 'suppressed'\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: terminal ? null : message.payloadEncrypted,\n status,\n attemptCount,\n nextAttemptAt: new Date(now.getTime() + retryDelayMilliseconds(attemptCount)),\n transport: options.transport.id,\n lastErrorCode: error.code,\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n if (status === 'suppressed') result.suppressed++\n else if (status === 'failed') result.failed++\n else result.retrying++\n }\n }\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentInvitationMessage, InvitationOutbox } from '#cloud/server/invitations'\nimport type { Transaction } from 'kysely'\n\nimport type { TransactionalEmailService } from './types'\n\nexport function createInvitationOutbox(email: TransactionalEmailService): InvitationOutbox {\n return {\n enqueueDocumentInvitation(\n message: DocumentInvitationMessage,\n transaction?: Transaction<CloudDatabase>\n ): Promise<string> {\n return email.enqueue(\n {\n idempotencyKey: `document-invitation/${message.deliveryId}`,\n kind: 'document-invitation',\n recipientEmail: message.recipientEmail,\n fallbackLocale: message.locale,\n payload: {\n inviterName: message.inviterName,\n documentName: message.documentName,\n permission: message.permission,\n expiresAt: message.expiresAt,\n acceptanceURL: message.acceptanceURL\n }\n },\n transaction\n )\n }\n }\n}\n","import {\n TransactionalEmailTransportError,\n type TransactionalEmailEnvelope,\n type TransactionalEmailTransport,\n type TransactionalEmailTransportErrorKind\n} from '#cloud/server/email'\n\n/** The part of a Worker's `send_email` binding the transport uses. */\nexport type CloudflareEmailBinding = {\n send(message: {\n to: string\n from: string\n replyTo?: string\n subject: string\n html: string\n text: string\n headers?: Record<string, string>\n }): Promise<{ messageId: string }>\n}\n\n/** Cloudflare Email Service error codes, by what retrying them would do. */\nconst ERROR_KINDS: Record<string, TransactionalEmailTransportErrorKind> = {\n E_SENDER_NOT_VERIFIED: 'configuration',\n E_RECIPIENT_NOT_ALLOWED: 'configuration',\n E_SENDER_DOMAIN_NOT_AVAILABLE: 'configuration',\n E_RECIPIENT_SUPPRESSED: 'suppressed',\n E_VALIDATION_ERROR: 'permanent',\n E_FIELD_MISSING: 'permanent',\n E_TOO_MANY_RECIPIENTS: 'permanent',\n E_TOO_MANY_ATTACHMENTS: 'permanent',\n E_CONTENT_TOO_LARGE: 'permanent',\n E_DELIVERY_FAILED: 'permanent',\n E_RATE_LIMIT_EXCEEDED: 'rate-limited',\n E_DAILY_LIMIT_EXCEEDED: 'rate-limited'\n}\n\nfunction errorCode(error: unknown): string {\n return error instanceof Error && 'code' in error && typeof error.code === 'string'\n ? error.code\n : 'E_UNKNOWN'\n}\n\n/** Sends transactional email through a Worker's `send_email` binding. */\nexport function createCloudflareEmailTransport(\n binding: CloudflareEmailBinding\n): TransactionalEmailTransport {\n return {\n id: 'cloudflare-email-service',\n async send(message: TransactionalEmailEnvelope) {\n try {\n const result = await binding.send({\n to: message.to,\n from: message.from,\n ...(message.replyTo ? { replyTo: message.replyTo } : {}),\n subject: message.subject,\n html: message.html,\n text: message.text,\n headers: message.headers\n })\n return { transportMessageId: result.messageId, acceptedAt: new Date().toISOString() }\n } catch (error) {\n const code = errorCode(error)\n throw new TransactionalEmailTransportError(\n ERROR_KINDS[code] ?? 'transient',\n code,\n 'Cloudflare Email Service rejected a transactional email',\n { cause: error }\n )\n }\n }\n }\n}\n","export type AdminErrorCode =\n | 'invalid_enrollment_transition'\n | 'invitations_unavailable'\n | 'last_admin_required'\n | 'self_admin_action_forbidden'\n | 'last_authentication_method'\n | 'account_approved'\n | 'email_regeneration_unavailable'\n | 'mfa_required'\n | 'two_step_unconfirmed'\n | 'document_not_restorable'\n | 'workspace_gone'\n\nexport class AdminDomainError extends Error {\n override readonly name = 'AdminDomainError'\n constructor(\n readonly code: AdminErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n\nconst CONFLICTS = new Set<AdminErrorCode>([\n 'invalid_enrollment_transition',\n 'account_approved',\n 'document_not_restorable',\n 'workspace_gone'\n])\n\nexport function adminErrorStatus(error: AdminDomainError): 400 | 409 {\n return CONFLICTS.has(error.code) ? 409 : 400\n}\n","import type { Context, Next } from 'hono'\n\nexport function requireTrustedMutationOrigin(trustedOrigins: ReadonlySet<string>) {\n return async (context: Context, next: Next) => {\n if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(context.req.method)) return next()\n const origin = context.req.header('origin')\n if (!origin || !trustedOrigins.has(origin)) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return next()\n }\n}\n","import * as v from 'valibot'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n/** Accounts and access requests are named by UUID; anything else names no row. */\nexport const isUUID = (value: string) => v.is(uuidSchema, value)\n\n/** The most rows one admin list request returns. */\nexport const ADMIN_LIST_MAXIMUM = 500\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentReviewSchema = v.object({\n note: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(1000)))\n})\nexport const userRoleMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n enabled: v.boolean()\n})\n\nexport const userMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))\n})\n\n/** One of an account's sign-in methods, as the person's page lists them. */\nexport const signInMethodMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n methodId: v.pipe(v.string(), v.trim(), v.minLength(1))\n})\n\n/** Why an administrator takes a document down, which the audit log keeps. */\nexport const documentTakedownSchema = v.object({\n reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))\n})\n\nexport type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>\n","/** The document does not exist, or the person may not know it does. */\nexport class DocumentNotFoundError extends Error {\n override readonly name = 'DocumentNotFoundError'\n}\n/** The person may see the document but not do this to it. */\nexport class DocumentForbiddenError extends Error {\n override readonly name = 'DocumentForbiddenError'\n}\n/** A save named a base revision the document has moved on from. */\nexport class DocumentConflictError extends Error {\n override readonly name = 'DocumentConflictError'\n}\n/** An upload is not the file it declared, or no longer one that can land. */\nexport class UploadInvalidError extends Error {\n override readonly name = 'UploadInvalidError'\n}\n/**\n * Destroying a document deleted forever with no grace failed. The failure, its cause, was\n * reported where cleanup reports; the document is out of Trash, and cleanup tries again.\n */\nexport class DocumentPurgeFailedError extends Error {\n override readonly name = 'DocumentPurgeFailedError'\n}\n","import { sql, type Expression, type Transaction } from 'kysely'\n\nimport type { CloudDatabase } from './tables'\n\nexport const CURRENT_TIMESTAMP = sql<Date>`current_timestamp`\nexport const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`\n\nconst CHECK_VALUE_PATTERN = /^[a-z][a-z0-9-]*$/\n\nexport function checkColumnIn(column: string, values: readonly string[]): Expression<boolean> {\n if (values.length === 0 || values.some((value) => !CHECK_VALUE_PATTERN.test(value))) {\n throw new Error('Check constraint values must be non-empty lowercase identifiers')\n }\n return sql<boolean>`${sql.ref(column)} in (${sql.join(values.map((value) => sql.lit(value)))})`\n}\n\n/**\n * Holds a lock named `key` until the transaction ends, for a check and a write that must not\n * interleave with another transaction's, such as reserving storage from an account's allowance,\n * which spans rows no single one of which could be locked for it.\n */\nexport async function lockForTransaction(\n transaction: Transaction<CloudDatabase>,\n key: string\n): Promise<void> {\n await sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`.execute(transaction)\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { lockForTransaction } from '#cloud/server/db/expressions'\nimport type { Transaction } from 'kysely'\n\nimport { DAY_MS } from '@open-pencil/std/timing'\n\n/**\n * How many invitations, to documents and workspaces alike, one person may send in a day, and how\n * many one address may receive from everyone. Each sends an email naming the inviter and the file,\n * both of which the sender chooses, so without a daily budget invitations are a way to send spam.\n */\nexport const INVITATION_BUDGET = {\n windowMs: DAY_MS,\n perSender: 100,\n perRecipient: 5\n} as const\n\n/** An invitation past the sender's or the recipient's daily budget. */\nexport class InvitationLimitError extends Error {\n override readonly name = 'InvitationLimitError'\n}\n\nasync function sentSince(\n transaction: Transaction<CloudDatabase>,\n column: 'senderId' | 'emailNormalized',\n value: string,\n since: Date\n): Promise<number> {\n const row = await transaction\n .selectFrom('invitationSend')\n .select((expression) => expression.fn.countAll<string>().as('count'))\n .where(column, '=', value)\n .where('sentAt', '>', since)\n .executeTakeFirstOrThrow()\n return Number(row.count)\n}\n\n/**\n * Counts an invitation from `senderId` to `email` against both daily budgets, in the transaction\n * that creates it, or refuses it once either budget is used. Sends are logged apart from the\n * invitations, so deleting a workspace or document gives nothing back, and the check holds locks\n * on the sender and the recipient, so two invitations at once cannot both take the last one.\n */\nexport async function spendInvitationBudget(\n transaction: Transaction<CloudDatabase>,\n invitation: { senderId: string; email: string },\n now = new Date()\n): Promise<void> {\n const email = invitation.email.trim().toLowerCase()\n // Always sender first, then recipient, so two transactions never wait on each other in turn.\n await lockForTransaction(transaction, `invitation-sender:${invitation.senderId}`)\n await lockForTransaction(transaction, `invitation-recipient:${email}`)\n const since = new Date(now.getTime() - INVITATION_BUDGET.windowMs)\n const bySender = await sentSince(transaction, 'senderId', invitation.senderId, since)\n const byRecipient = await sentSince(transaction, 'emailNormalized', email, since)\n if (bySender >= INVITATION_BUDGET.perSender || byRecipient >= INVITATION_BUDGET.perRecipient) {\n throw new InvitationLimitError()\n }\n await transaction\n .insertInto('invitationSend')\n .values({\n id: crypto.randomUUID(),\n senderId: invitation.senderId,\n emailNormalized: email,\n sentAt: now\n })\n .execute()\n}\n","import { DAY_MS } from '@open-pencil/std/timing'\n\n/** How many random bytes an invitation link's secret has. */\nexport const INVITATION_SECRET_BYTES = 24\n/** How long an invitation link works, for a document or a workspace alike. */\nexport const INVITATION_LIFETIME_MS = 7 * DAY_MS\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { INVITATION_BUDGET } from '#cloud/server/invitations'\nimport type { Kysely } from 'kysely'\n\nexport function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {\n return {\n async cleanupExpired(before: Date): Promise<number> {\n const [limits, invitations] = await Promise.all([\n database\n .deleteFrom('apiRateLimit')\n .where('windowStartedAt', '<', before)\n .executeTakeFirst(),\n // Never a send the invitation budget still counts, whatever cutoff the sweep passes.\n database\n .deleteFrom('invitationSend')\n .where(\n 'sentAt',\n '<',\n new Date(Math.min(before.getTime(), Date.now() - INVITATION_BUDGET.windowMs))\n )\n .executeTakeFirst()\n ])\n return Number(limits.numDeletedRows) + Number(invitations.numDeletedRows)\n }\n }\n}\n\nexport type RateLimitCleanupService = ReturnType<typeof createRateLimitCleanupService>\n","import type { CloudActor } from '#cloud/server/auth'\nimport type { Context } from 'hono'\n\nexport type ClientIdentityOptions = {\n trustedHeaders: string[]\n}\n\n/**\n * The client address a trusted proxy reported. List-valued headers such as `X-Forwarded-For` carry\n * whatever the client sent followed by what each proxy appended, so only the right-most entry,\n * the one the trusted proxy wrote, identifies the client.\n */\nexport function trustedClientIP(context: Context, options: ClientIdentityOptions): string | null {\n for (const header of options.trustedHeaders) {\n const value = context.req\n .header(header)\n ?.split(',')\n .map((entry) => entry.trim())\n .findLast((entry) => entry.length > 0)\n if (value) return value\n }\n return null\n}\n\nexport const rateLimitKey = {\n email(email: string): string {\n return `email:${email.trim().toLowerCase()}`\n },\n ip(ip: string): string {\n return `ip:${ip}`\n },\n actor(actor: CloudActor): string {\n return `actor:${actor.userId}`\n },\n resource(resourceId: string, identity: string): string {\n return `resource:${resourceId}:${identity}`\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport type { ClientRateLimitInfo, Store } from 'hono-rate-limiter'\nimport type { Kysely } from 'kysely'\n\nexport class PostgresRateLimitStore implements Store {\n readonly localKeys = false\n readonly prefix: string\n private windowMs = 60_000\n\n constructor(\n private readonly database: Kysely<CloudDatabase>,\n private readonly secret: string,\n namespace: string,\n options: { windowMs?: number } = {}\n ) {\n this.prefix = `${namespace}:`\n this.windowMs = options.windowMs ?? this.windowMs\n }\n\n init(options: { windowMs: number }): void {\n this.windowMs = options.windowMs\n }\n\n private hash(key: string): string {\n return bytesToHex(sha256(utf8ToBytes(`${this.secret}:${this.prefix}:${key}`)))\n }\n\n async increment(key: string): Promise<ClientRateLimitInfo> {\n const now = new Date()\n const resetTime = new Date(\n Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs\n )\n const row = await this.database\n .insertInto('apiRateLimit')\n .values({\n keyHash: this.hash(key),\n windowStartedAt: new Date(resetTime.getTime() - this.windowMs),\n requestCount: 1,\n updatedAt: now\n })\n .onConflict((conflict) =>\n conflict.column('keyHash').doUpdateSet((expression) => ({\n requestCount: expression\n .case()\n .whenRef('apiRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')\n .then(expression('apiRateLimit.requestCount', '+', 1))\n .else(1)\n .end(),\n windowStartedAt: expression.ref('excluded.windowStartedAt'),\n updatedAt: expression.ref('excluded.updatedAt')\n }))\n )\n .returning(['requestCount', 'windowStartedAt'])\n .executeTakeFirstOrThrow()\n return {\n totalHits: Number(row.requestCount),\n resetTime: new Date(new Date(row.windowStartedAt).getTime() + this.windowMs)\n }\n }\n\n async decrement(key: string): Promise<void> {\n await this.database\n .updateTable('apiRateLimit')\n .set((expression) => ({\n requestCount: expression.fn('greatest', [\n expression('requestCount', '-', 1),\n expression.val(0)\n ])\n }))\n .where('keyHash', '=', this.hash(key))\n .execute()\n }\n\n async resetKey(key: string): Promise<void> {\n await this.database.deleteFrom('apiRateLimit').where('keyHash', '=', this.hash(key)).execute()\n }\n}\n","import type { CloudAPIEnvironment, RateLimitUse } from '#cloud/server/api/types'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Context, Env, Input, MiddlewareHandler } from 'hono'\nimport { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'\nimport { every } from 'hono/combine'\nimport { matchedRoutes } from 'hono/route'\nimport type { Kysely } from 'kysely'\n\nimport { trustedClientIP, type ClientIdentityOptions } from './keys'\nimport { PostgresRateLimitStore } from './postgres'\n\nexport type RateLimitPolicy = {\n namespace: string\n windowMs: number\n limit: number\n}\n\n/**\n * A budget counted per resource, such as a document, with `actorLimit` capping one actor across\n * every resource, so new resources do not add budget without end.\n */\nexport type ResourceRateLimitPolicy = RateLimitPolicy & { actorLimit: number }\n\nexport const CLOUD_RATE_LIMITS = {\n publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },\n // Everything one visitor reads of the community gallery, across its paths: a page of thumbnails\n // fits, made-up addresses do not each get a fresh budget.\n communityRead: { namespace: 'community-read', windowMs: 60_000, limit: 300 },\n collaborationTicket: {\n namespace: 'collaboration-ticket',\n windowMs: 60_000,\n limit: 60,\n actorLimit: 300\n },\n invitationMutation: {\n namespace: 'invitation-mutation',\n windowMs: 60_000,\n limit: 30,\n actorLimit: 60\n },\n workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },\n documentCreation: {\n namespace: 'document-creation',\n windowMs: 60_000,\n limit: 60,\n actorLimit: 120\n },\n uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120, actorLimit: 600 },\n authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },\n servicesToken: { namespace: 'services-token', windowMs: 60_000, limit: 30 },\n billingToken: { namespace: 'billing-token', windowMs: 60_000, limit: 30 },\n adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },\n adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }\n} as const satisfies Record<string, RateLimitPolicy | ResourceRateLimitPolicy>\n\n/**\n * The limiters routes mount for their own budget, each with which requests it counts. A general\n * limiter leaves those requests to it rather than counting them twice; the routes themselves say\n * which have one, so the general limiter never matches paths.\n */\nconst routeBudgets = new WeakMap<object, (context: Context) => boolean>()\n\n/** Whether a limiter the request's route mounts for its own budget counts this request. */\nexport function routeHasOwnBudget(context: Context): boolean {\n return matchedRoutes(context).some((route) => routeBudgets.get(route.handler)?.(context))\n}\n\nfunction ownBudget<Limiter extends object>(\n limiter: Limiter,\n skip?: (context: Context) => boolean\n): Limiter {\n routeBudgets.set(limiter, (context) => !skip?.(context))\n return limiter\n}\n\ntype RateLimitOptions<E extends Env, P extends string, I extends Input> = {\n database: Kysely<CloudDatabase>\n secret: string\n policy: RateLimitPolicy\n keyGenerator(context: Context<E, P, I>): string\n handler?: RateLimitExceededEventHandler<E, P, I>\n skip?: (context: Context<E, P, I>) => boolean\n standardHeaders?: boolean | 'draft-6' | 'draft-7'\n}\n\nexport function createCloudRateLimiter<\n E extends Env = Env,\n P extends string = string,\n I extends Input = Input\n>(options: RateLimitOptions<E, P, I>) {\n return rateLimiter<E, P, I>({\n windowMs: options.policy.windowMs,\n limit: options.policy.limit,\n standardHeaders: options.standardHeaders ?? 'draft-7',\n store: new PostgresRateLimitStore(options.database, options.secret, options.policy.namespace),\n keyGenerator: (context) => options.keyGenerator(context),\n handler: options.handler\n ? (context, next, used) => options.handler?.(context, next, used)\n : undefined,\n skip: options.skip\n })\n}\n\nexport function createTrustedIPRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n client: ClientIdentityOptions,\n handler?: RateLimitExceededEventHandler,\n options?: {\n resource?: (context: Context) => string\n skip?: (context: Context) => boolean\n /** The limiter is a route's own budget, which general limiters leave to it. */\n route?: boolean\n }\n) {\n const limiter = createCloudRateLimiter({\n database,\n secret,\n policy,\n keyGenerator: (context) => {\n const ip = trustedClientIP(context, client) ?? 'unavailable'\n return options?.resource ? `resource:${options.resource(context)}:ip:${ip}` : `ip:${ip}`\n },\n skip: (context) =>\n trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),\n handler\n })\n return options?.route ? ownBudget(limiter, options.skip) : limiter\n}\n\nexport function createActorRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean,\n resource?: (context: Context<CloudAPIEnvironment, '*'>) => string\n) {\n return createCloudRateLimiter<CloudAPIEnvironment, '*'>({\n database,\n secret,\n policy,\n keyGenerator: (context) =>\n resource\n ? `resource:${resource(context)}:actor:${context.get('actor').userId}`\n : `actor:${context.get('actor').userId}`,\n skip\n })\n}\n\n/**\n * A limiter a route mounts for its own budget, such as workspace creation; general limiters leave\n * the requests it counts to it.\n */\nexport function createRouteRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean\n) {\n return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip)\n}\n\n/**\n * A route's own budget counted per resource, such as uploads per document, and capped per actor\n * across resources by `actorLimit`; general limiters leave the requests it counts to it.\n */\nexport function createResourceRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: ResourceRateLimitPolicy,\n resource: (context: Context<CloudAPIEnvironment, '*'>) => string,\n skip?: (context: Context) => boolean\n) {\n const perResource = createActorRateLimiter(database, secret, policy, skip, resource)\n const perActor = createActorRateLimiter(\n database,\n secret,\n { namespace: `${policy.namespace}-actor`, windowMs: policy.windowMs, limit: policy.actorLimit },\n skip\n )\n return ownBudget(\n every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)),\n skip\n )\n}\n\n/** Keeps the resource budget's use, which the actor-wide limiter would record over. */\nconst keepResourceUse: MiddlewareHandler<CloudAPIEnvironment> = async (context, next) => {\n context.set('resourceRateLimit', context.get('rateLimit'))\n await next()\n}\n\n/**\n * Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters\n * write them and the last would otherwise win. A refused request keeps the headers of the budget\n * that refused it.\n */\nfunction reportTighterBudget(windowMs: number): MiddlewareHandler<CloudAPIEnvironment> {\n return async (context, next) => {\n const resource = context.get('resourceRateLimit')\n const actor = context.get('rateLimit')\n const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor\n if (tighter) setBudgetHeaders(context, tighter, windowMs)\n await next()\n }\n}\n\n/** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */\nfunction setBudgetHeaders(context: Context, use: RateLimitUse, windowMs: number): void {\n const windowSeconds = Math.ceil(windowMs / 1000)\n const reset = use.resetTime\n ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1000))\n : windowSeconds\n context.header('RateLimit-Policy', `${use.limit};w=${windowSeconds}`)\n context.header('RateLimit', `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`)\n}\n\n/**\n * A limiter's resource named by a route parameter, such as the document a request uploads to. It\n * runs before the route's param validator, and the value only names the limiter's counter, which\n * `rateLimitKey` hashes; it never reaches a query.\n */\nexport function routeParamResource(name: string) {\n return (context: Context): string =>\n // Lowercased as validation lowercases UUIDs, so one row's spellings share a budget.\n // eslint-disable-next-line @open-pencil/security/no-unvalidated-route-params -- a counter name, hashed, never queried.\n context.req.param(name)?.toLowerCase() ?? 'unknown'\n}\n","import { sValidator } from '@hono/standard-validator'\nimport * as v from 'valibot'\n\nconst invalidRequest = { error: { code: 'invalid_request' as const } }\n\n/**\n * A JSON body through `schema`; handlers read it from `context.req.valid('json')`. A body that\n * fails it is a 400, never a server error. The route's type takes what the schema accepts and\n * hands handlers what it outputs, so a typed client may leave out a field with a default.\n */\nexport function validatedJSON<Schema extends v.GenericSchema>(schema: Schema) {\n return sValidator('json', schema, (result, context) =>\n result.success ? undefined : context.json(invalidRequest, 400)\n )\n}\n\n/** Query string counterpart of `validatedJSON`. */\nexport function validatedQuery<Schema extends v.GenericSchema>(schema: Schema) {\n return sValidator('query', schema, (result, context) =>\n result.success ? undefined : context.json(invalidRequest, 400)\n )\n}\n\n/**\n * A route parameter that names a row by UUID, in lowercase: the database matches any case, but an\n * ID that also names something else, such as a document's relay, must have one spelling.\n */\nconst uuidParamSchema = v.pipe(v.string(), v.uuid(), v.toLowerCase())\n\n/**\n * Route parameters through `schema`; handlers read them from `context.req.valid('param')`. A\n * parameter that fails it names nothing, so the route answers 404 as for a missing row, and the\n * value never reaches the database.\n */\nexport function validatedParams<Schema extends v.GenericSchema>(schema: Schema) {\n return sValidator('param', schema, (result, context) =>\n result.success ? undefined : context.json({ error: { code: 'not_found' as const } }, 404)\n )\n}\n\n/** A route parameter the server takes as text, such as a user ID, which is not a UUID column. */\nconst textParamSchema = v.pipe(v.string(), v.minLength(1))\n\nexport const documentParams = validatedParams(v.object({ documentId: uuidParamSchema }))\nexport const documentVersionParams = validatedParams(\n v.object({ documentId: uuidParamSchema, versionId: uuidParamSchema })\n)\nexport const documentThreadParams = validatedParams(\n v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema })\n)\nexport const documentCommentParams = validatedParams(\n v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })\n)\nexport const documentShareParams = validatedParams(\n v.object({ documentId: uuidParamSchema, shareId: uuidParamSchema })\n)\nexport const documentInvitationParams = validatedParams(\n v.object({ documentId: uuidParamSchema, invitationId: uuidParamSchema })\n)\nexport const documentUserParams = validatedParams(\n v.object({ documentId: uuidParamSchema, userId: textParamSchema })\n)\nexport const workspaceParams = validatedParams(v.object({ workspaceId: uuidParamSchema }))\nexport const workspaceInvitationParams = validatedParams(\n v.object({ workspaceId: uuidParamSchema, invitationId: uuidParamSchema })\n)\nexport const workspaceMemberParams = validatedParams(\n v.object({ workspaceId: uuidParamSchema, userId: textParamSchema })\n)\nexport const accountParams = validatedParams(v.object({ userId: uuidParamSchema }))\nexport const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }))\nexport const shareThreadParams = validatedParams(\n v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema })\n)\nexport const shareCommentParams = validatedParams(\n v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })\n)\n/** A document and one of its revisions, as a thumbnail's address names them. */\nexport const documentRevisionParams = validatedParams(\n v.object({ documentId: uuidParamSchema, revisionId: uuidParamSchema })\n)\nexport const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }))\nexport const invitationContinuationParams = validatedParams(\n v.object({ continuationId: textParamSchema })\n)\nexport const uploadParams = validatedParams(v.object({ uploadId: uuidParamSchema }))\n/** Admin records (enrollments, accounts, and messages), all named by UUID. */\nexport const idParams = validatedParams(v.object({ id: uuidParamSchema }))\n/** A picture's address names its owner and a prefix of its checksum, which the service checks. */\nexport const pictureParams = validatedParams(\n v.object({ userId: textParamSchema, version: textParamSchema })\n)\n","import { requireTrustedMutationOrigin } from '#cloud/admin/api/security'\nimport type { AdminAuditService } from '#cloud/admin/audit/service'\nimport type { AdminDocumentService } from '#cloud/admin/documents/service'\nimport type { AdminEmailService } from '#cloud/admin/email/service'\nimport type { EnrollmentService } from '#cloud/admin/enrollment/service'\nimport { adminErrorStatus, AdminDomainError } from '#cloud/admin/errors'\nimport type { AdminOperationsService } from '#cloud/admin/operations/service'\nimport type { AdminReportService } from '#cloud/admin/reports/service'\nimport {\n enrollmentStatusSchema,\n documentTakedownSchema,\n enrollmentReviewSchema,\n signInMethodMutationSchema,\n userMutationSchema,\n userRoleMutationSchema\n} from '#cloud/admin/schema'\nimport type { AdminUserService } from '#cloud/admin/users/service'\nimport {\n cloudAdminAuditFilterSchema,\n cloudAdminDocumentFilterSchema,\n cloudAdminEmailFilterSchema,\n cloudAdminReportFilterSchema,\n cloudAdminUserFilterSchema,\n cloudAdminUserMethodSchema\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport type { CloudAuthAdapter } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'\nimport {\n documentRevisionParams,\n idParams,\n validatedJSON,\n validatedQuery\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport { NoResultError, type Kysely } from 'kysely'\nimport * as v from 'valibot'\n\n/**\n * A count from the query string; anything but digits, or a number too large to be exact, is a bad\n * request rather than a NaN or out-of-range query.\n */\nconst countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber(), v.safeInteger()))\n/** What an admin list reads from its query string: a search, one of `filters`, and a page. */\nfunction listQuery<const Filter extends string>(filters: v.PicklistSchema<Filter[], undefined>) {\n return v.object({\n search: v.optional(v.string()),\n filter: v.optional(filters),\n limit: countSchema,\n offset: countSchema\n })\n}\nconst enrollmentQuerySchema = listQuery(enrollmentStatusSchema)\nconst userQuerySchema = v.object({\n ...listQuery(cloudAdminUserFilterSchema).entries,\n method: v.optional(cloudAdminUserMethodSchema)\n})\nconst emailQuerySchema = listQuery(cloudAdminEmailFilterSchema)\nconst auditQuerySchema = listQuery(cloudAdminAuditFilterSchema)\nconst documentQuerySchema = listQuery(cloudAdminDocumentFilterSchema)\nconst reportQuerySchema = listQuery(cloudAdminReportFilterSchema)\n/** Accounts are named by UUID; anything else names no one, rather than failing the query. */\nconst accountIdSchema = v.pipe(v.string(), v.uuid())\n\n/** Does what an administrator asked to another account; one that is not an account is not found. */\nasync function accountMutation(\n context: Context<CloudAPIEnvironment>,\n userId: string,\n mutate: (actorId: string, userId: string) => Promise<void>\n) {\n if (!v.is(accountIdSchema, userId)) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n // A UUID matches in any case; the lowercase spelling is the one the actor's own ID uses.\n await mutate(context.get('actor').userId, userId.toLowerCase())\n return context.json({ ok: true as const })\n}\n\nexport type CloudAdminServices = {\n email: AdminEmailService\n enrollment: EnrollmentService\n users: AdminUserService\n audit: AdminAuditService\n operations: AdminOperationsService\n documents: AdminDocumentService\n reports: AdminReportService\n}\n\nexport function createCloudAdminRoutes(\n services: CloudAdminServices,\n trustedOrigins: ReadonlySet<string>,\n security: {\n auth: CloudAuthAdapter\n database: Kysely<CloudDatabase>\n requireMFA: boolean\n secret: string\n }\n) {\n const adminRead = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminRead,\n (context) => context.req.method !== 'GET'\n )\n const adminMutation = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminMutation,\n (context) => context.req.method === 'GET'\n )\n return (\n new Hono<CloudAPIEnvironment>()\n .use('*', requireTrustedMutationOrigin(trustedOrigins))\n .use('*', async (context, next) => {\n const actor = context.get('actor')\n if (actor.deploymentRole !== 'admin') {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (security.requireMFA) {\n const status = await security.auth.mfaStatus(context.req.raw.headers)\n if (!status?.assured) {\n // Someone with two-step only has to prove it again; someone without has to turn it on.\n const code = status?.enabled ? 'two_step_unconfirmed' : 'mfa_required'\n return context.json({ error: { code } }, 403)\n }\n }\n return next()\n })\n .use('*', adminRead)\n .use('*', adminMutation)\n .onError((error, context) => {\n if (error instanceof AdminDomainError) {\n return context.json({ error: { code: error.code } }, adminErrorStatus(error))\n }\n if (error instanceof v.ValiError) {\n return context.json({ error: { code: 'invalid_request' as const } }, 400)\n }\n // An enrollment or message ID that names nothing, or a document with nothing saved.\n if (error instanceof NoResultError || error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n throw error\n })\n .get('/enrollments', validatedQuery(enrollmentQuerySchema), async (context) =>\n context.json(await services.enrollment.list(context.req.valid('query')))\n )\n .post('/enrollments/invite', async (context) =>\n context.json(await services.enrollment.invitePending(context.get('actor').userId))\n )\n .post(\n '/enrollments/:id/approve',\n idParams,\n validatedJSON(enrollmentReviewSchema),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'approved',\n context.req.valid('json')\n )\n })\n )\n .post(\n '/enrollments/:id/reject',\n idParams,\n validatedJSON(enrollmentReviewSchema),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'rejected',\n context.req.valid('json')\n )\n })\n )\n .post(\n '/enrollments/:id/revoke',\n idParams,\n validatedJSON(enrollmentReviewSchema),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'revoked',\n context.req.valid('json')\n )\n })\n )\n .get('/users', validatedQuery(userQuerySchema), async (context) =>\n context.json(await services.users.list(context.req.valid('query')))\n )\n .get('/users/:id', idParams, async (context) => {\n const detail = await services.users.detail(context.req.valid('param').id)\n if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json(detail)\n })\n .post('/users/reset-two-step', validatedJSON(userMutationSchema), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.resetTwoStep(actorId, userId)\n )\n )\n .post(\n '/users/remove-sign-in-method',\n validatedJSON(signInMethodMutationSchema),\n (context) => {\n const { userId, methodId } = context.req.valid('json')\n return accountMutation(context, userId, (actorId, id) =>\n services.users.removeSignInMethod(actorId, id, methodId)\n )\n }\n )\n .post('/users/remove-picture', validatedJSON(userMutationSchema), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.removePicture(actorId, userId)\n )\n )\n .post('/users/delete', validatedJSON(userMutationSchema), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.deleteUnapproved(actorId, userId)\n )\n )\n .post('/users/ban', validatedJSON(userMutationSchema), async (context) => {\n const input = context.req.valid('json')\n await services.users.ban(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.reason\n )\n return context.json({ ok: true as const })\n })\n .post('/users/unban', validatedJSON(userMutationSchema), async (context) => {\n const input = context.req.valid('json')\n await services.users.unban(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId\n )\n return context.json({ ok: true as const })\n })\n .post('/users/revoke-sessions', validatedJSON(userMutationSchema), async (context) => {\n const input = context.req.valid('json')\n await services.users.revokeSessions(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId\n )\n return context.json({ ok: true as const })\n })\n .post('/users/set-admin', validatedJSON(userRoleMutationSchema), async (context) => {\n const input = context.req.valid('json')\n await services.users.setAdmin(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.enabled\n )\n return context.json({ ok: true as const })\n })\n .get('/email', validatedQuery(emailQuerySchema), async (context) =>\n context.json(await services.email.list(context.req.valid('query')))\n )\n .post('/email/:id/regenerate', idParams, async (context) => {\n await services.email.regenerate(context.get('actor').userId, context.req.valid('param').id)\n return context.json({ ok: true as const })\n })\n .get('/audit', validatedQuery(auditQuerySchema), async (context) =>\n context.json(await services.audit.list(context.req.valid('query')))\n )\n .get('/operations', async (context) => context.json(await services.operations.summary()))\n .get('/reports', validatedQuery(reportQuerySchema), async (context) =>\n context.json(await services.reports.list(context.req.valid('query')))\n )\n .post('/reports/:id/dismiss', idParams, async (context) => {\n await services.reports.resolve(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'dismissed'\n )\n return context.json({ ok: true as const })\n })\n .post('/reports/:id/action', idParams, async (context) => {\n await services.reports.resolve(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'actioned'\n )\n return context.json({ ok: true as const })\n })\n .get('/documents', validatedQuery(documentQuerySchema), async (context) =>\n context.json(await services.documents.list(context.req.valid('query')))\n )\n .post(\n '/documents/:id/disable',\n idParams,\n validatedJSON(documentTakedownSchema),\n async (context) => {\n await services.documents.disable(\n context.get('actor').userId,\n context.req.valid('param').id,\n context.req.valid('json').reason\n )\n return context.json({ ok: true as const })\n }\n )\n .post('/documents/:id/enable', idParams, async (context) => {\n await services.documents.enable(context.get('actor').userId, context.req.valid('param').id)\n return context.json({ ok: true as const })\n })\n // Its address names the revision it shows, which is also its ETag. The browser asks again\n // each time, so the administrator and two-step checks always run, even for another account\n // later in the same browser; an unchanged thumbnail answers 304 without reading storage.\n .get(\n '/documents/:documentId/thumbnails/:revisionId',\n documentRevisionParams,\n async (context) => {\n const { documentId, revisionId } = context.req.valid('param')\n const etag = `\"${revisionId}\"`\n context.header('Cache-Control', 'private, no-cache')\n context.header('ETag', etag)\n if (\n context.req.header('If-None-Match') === etag &&\n (await services.documents.isCurrentRevision(documentId, revisionId))\n ) {\n return context.body(null, 304)\n }\n const thumbnail = await services.documents.thumbnail(documentId, revisionId)\n if (!thumbnail) return context.json({ error: { code: 'not_found' as const } }, 404)\n context.header('Content-Type', 'image/png')\n context.header('X-Content-Type-Options', 'nosniff')\n context.header('Content-Security-Policy', \"default-src 'none'; sandbox\")\n return context.body(new Uint8Array(thumbnail))\n }\n )\n .post('/documents/:id/download', idParams, async (context) =>\n context.json(\n await services.documents.download(\n context.get('actor').userId,\n context.req.valid('param').id\n )\n )\n )\n .post('/documents/:id/undelete', idParams, async (context) => {\n await services.documents.undelete(\n context.get('actor').userId,\n context.req.valid('param').id\n )\n return context.json({ ok: true as const })\n })\n .post('/shares/:id/revoke', idParams, async (context) => {\n await services.documents.revokeShare(\n context.get('actor').userId,\n context.req.valid('param').id\n )\n return context.json({ ok: true as const })\n })\n )\n}\n\n/** The administration routes' types, for the portal's typed client. */\nexport type CloudAdminRoutes = ReturnType<typeof createCloudAdminRoutes>\n","import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { clamp, zipObject } from 'es-toolkit'\nimport type { Expression, ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'\n\n/** The rows an admin list returns when the request does not say. */\nexport const ADMIN_PAGE_SIZE = 50\n\n/** What every admin list takes: words to search for, one of its filters, and a page. */\nexport type AdminListQuery<Filter extends string> = {\n search?: string\n filter?: Filter\n limit?: number\n offset?: number\n}\n\n/** A `like` pattern that finds `search` anywhere, matching `%`, `_`, and `\\` literally. */\nexport function containsPattern(search: string): string {\n return `%${search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n}\n\n/** The search words, or undefined when there are none. */\nexport function listSearch(query: AdminListQuery<string>): string | undefined {\n return query.search?.trim() || undefined\n}\n\n/** The page a query asks for, kept within what one request may return. */\nexport function listWindow(query: AdminListQuery<string>) {\n return {\n limit: clamp(query.limit ?? ADMIN_PAGE_SIZE, 1, ADMIN_LIST_MAXIMUM),\n offset: Math.max(0, query.offset ?? 0)\n }\n}\n\n/** A list's filters, each the condition its rows meet; the same one counts them and pages them. */\nexport type ListFilters<Filter extends string, Table extends keyof CloudDatabase> = Record<\n Filter,\n (expression: ExpressionBuilder<CloudDatabase, Table>) => Expression<SqlBool>\n>\n\n/**\n * How many of `searched`'s rows meet each filter, in one query: each count is an aggregate with a\n * `filter (where …)` clause rather than a query of its own.\n */\nexport async function countEachFilter<Filter extends string, Table extends keyof CloudDatabase>(\n searched: SelectQueryBuilder<CloudDatabase, Table, object>,\n names: readonly Filter[],\n filters: ListFilters<Filter, Table>\n): Promise<Record<Filter, number>> {\n // Kysely names each column after its filter but cannot type a generic name, so the row is read\n // as counts by name.\n const row: Record<string, unknown> = await searched\n .select((expression) =>\n names.map((name) => expression.fn.countAll<number>().filterWhere(filters[name]).as(name))\n )\n .executeTakeFirstOrThrow()\n return zipObject(\n names,\n names.map((name) => Number(row[name]))\n )\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Transaction } from 'kysely'\n\nimport type { EnrollmentStatus } from './service'\n\nexport type EnrollmentEmailOptions = {\n /**\n * The server's address: its editor, where an approved account goes next, and its own pages,\n * where people sign in and administrators review requests.\n */\n publicURL: string\n adminRecipients: string[]\n email?: TransactionalEmailService\n /**\n * Whether an approval may carry the founder's letter (`enrollment-invited`) instead of the\n * plain approval: only on the official deployment, whose letter it is.\n */\n invitations?: boolean\n}\n\nexport async function enqueueEnrollmentRequested(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: { enrollmentId: string; email: string; name: string; reason: string; revision: number }\n): Promise<void> {\n if (!options.email) return\n await options.email.enqueue(\n {\n idempotencyKey: `enrollment-requested/${input.enrollmentId}/${input.revision}`,\n kind: 'enrollment-requested',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', options.publicURL).href }\n },\n transaction\n )\n for (const recipientEmail of options.adminRecipients) {\n await options.email.enqueue(\n {\n idempotencyKey: `admin-enrollment-notification/${input.enrollmentId}/${input.revision}/${recipientEmail}`,\n kind: 'admin-enrollment-notification',\n recipientEmail,\n payload: {\n requesterEmail: input.email,\n requesterName: input.name,\n reason: input.reason,\n actionURL: new URL('/admin/requests', options.publicURL).href\n }\n },\n transaction\n )\n }\n}\n\nexport async function enqueueEnrollmentReview(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: {\n enrollmentId: string\n recipientEmail: string\n name: string\n status: Exclude<EnrollmentStatus, 'pending'>\n reviewedAt: Date\n /** An approval that sends the letter instead of the plain approval. */\n invite?: boolean\n /** The person joined openpencil.dev's waitlist rather than asking here; the letter says so. */\n waitlist?: boolean\n }\n): Promise<void> {\n if (!options.email) return\n const kind =\n input.status === 'approved' && input.invite\n ? ('enrollment-invited' as const)\n : (`enrollment-${input.status}` as const)\n await options.email.enqueue(\n {\n idempotencyKey: `${kind}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,\n kind,\n recipientEmail: input.recipientEmail,\n payload: {\n name: input.name,\n actionURL:\n input.status === 'approved'\n ? options.publicURL\n : new URL('/auth/sign-in', options.publicURL).href,\n ...(kind === 'enrollment-invited' && input.waitlist && { waitlist: true as const })\n }\n },\n transaction\n )\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { enrollmentStatusSchema } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { compact, uniq } from 'es-toolkit'\nimport { NoResultError, type Kysely } from 'kysely'\n\nimport {\n enqueueEnrollmentRequested,\n enqueueEnrollmentReview,\n type EnrollmentEmailOptions\n} from './email'\n\nexport type EnrollmentStatus = 'pending' | 'approved' | 'rejected' | 'revoked'\nexport type EnrollmentMode = 'open' | 'approval' | 'closed'\n\nexport type EnrollmentRequestInput = {\n email: string\n name?: string\n reason?: string\n /** Someone an administrator recorded from openpencil.dev's waitlist, who asked nowhere here. */\n source?: 'waitlist'\n}\nexport type EnrollmentReviewInput = {\n note?: string\n /** An approval that sends the founder's letter instead of the plain approval. */\n invite?: boolean\n /**\n * The status the reviewer saw, checked under the row's lock: a request another administrator\n * decided meanwhile is refused rather than decided again.\n */\n expectedStatus?: EnrollmentStatus\n}\nexport type EnrollmentRecord = {\n id: string\n email: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: string\n reviewedAt: string | null\n reviewedBy: string | null\n reviewerName?: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\ntype EnrollmentRow = {\n id: string\n emailNormalized: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: Date | string\n reviewedAt: Date | string | null\n reviewedBy: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\nconst ALLOWED_TRANSITIONS: Record<EnrollmentStatus, ReadonlySet<EnrollmentStatus>> = {\n pending: new Set(['approved', 'rejected']),\n approved: new Set(['revoked']),\n rejected: new Set(['pending', 'approved']),\n revoked: new Set(['pending', 'approved'])\n}\n\n/** Requests by their status; each is in exactly one. */\nconst FILTERS: ListFilters<EnrollmentStatus, 'enrollment'> = {\n pending: (expression) => expression('status', '=', 'pending'),\n approved: (expression) => expression('status', '=', 'approved'),\n rejected: (expression) => expression('status', '=', 'rejected'),\n revoked: (expression) => expression('status', '=', 'revoked')\n}\n\nfunction dateString(value: Date | string | null): string | null {\n return value ? new Date(value).toISOString() : null\n}\nfunction enrollmentRecord(row: EnrollmentRow): EnrollmentRecord {\n return {\n id: row.id,\n email: row.emailNormalized,\n name: row.name,\n reason: row.reason,\n status: row.status,\n requestedAt: dateString(row.requestedAt) ?? '',\n reviewedAt: dateString(row.reviewedAt),\n reviewedBy: row.reviewedBy,\n reviewNote: row.reviewNote,\n approvedUserId: row.approvedUserId,\n requestRevision: row.requestRevision\n }\n}\nexport function normalizeEnrollmentEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nexport function createEnrollmentService(\n database: Kysely<CloudDatabase>,\n emailOptions: EnrollmentEmailOptions = { publicURL: '', adminRecipients: [] }\n) {\n const statusForEmail = async (email: string): Promise<EnrollmentStatus | null> => {\n const row = await database\n .selectFrom('enrollment')\n .select('status')\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .executeTakeFirst()\n return row?.status ?? null\n }\n const service = {\n /**\n * Records a request, or leaves one that is waiting or approved as it is, source and all:\n * someone who asked here keeps the letter for asking. Says which it did.\n */\n async request(input: EnrollmentRequestInput): Promise<'recorded' | 'unchanged'> {\n const emailNormalized = normalizeEnrollmentEmail(input.email)\n return database.transaction().execute(async (transaction) => {\n const existing = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', emailNormalized)\n .forUpdate()\n .executeTakeFirst()\n if (existing?.status === 'approved' || existing?.status === 'pending') return 'unchanged'\n const revision = (existing?.requestRevision ?? 0) + 1\n const values = {\n name: input.name?.trim() || existing?.name || null,\n reason: input.reason?.trim() || null,\n status: 'pending' as const,\n reviewedAt: null,\n reviewedBy: null,\n reviewNote: null,\n requestRevision: revision,\n source: input.source ?? null\n }\n let row: EnrollmentRow\n if (existing) {\n row = await transaction\n .updateTable('enrollment')\n .set(values)\n .where('id', '=', existing.id)\n .returningAll()\n .executeTakeFirstOrThrow()\n } else {\n row = await transaction\n .insertInto('enrollment')\n .values({\n id: crypto.randomUUID(),\n emailNormalized,\n ...values,\n approvedUserId: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n }\n await enqueueEnrollmentRequested(transaction, emailOptions, {\n enrollmentId: row.id,\n email: row.emailNormalized,\n name: row.name ?? 'there',\n reason: row.reason ?? 'No reason provided.',\n revision\n })\n return 'recorded'\n })\n },\n statusForEmail,\n async isApproved(email: string): Promise<boolean> {\n return (await statusForEmail(email)) === 'approved'\n },\n /** A page of requests in one status, newest first, with how many match the search in each. */\n async list(query: AdminListQuery<EnrollmentStatus> = {}) {\n const search = listSearch(query)\n const status = query.filter ?? 'pending'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('enrollment')\n if (search) {\n const pattern = containsPattern(search)\n searched = searched.where((expression) =>\n expression.or([\n expression('name', 'ilike', pattern),\n expression('emailNormalized', 'ilike', pattern)\n ])\n )\n }\n const counts = await countEachFilter(searched, enrollmentStatusSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[status])\n .selectAll()\n .orderBy('requestedAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Reviewers are named by account ID; anything else names no one.\n const reviewerIds = uniq(compact(rows.map((row) => row.reviewedBy))).filter(isUUID)\n const reviewers = reviewerIds.length\n ? await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', reviewerIds)\n .execute()\n : []\n const names = new Map(reviewers.map((reviewer) => [reviewer.id, reviewer.name]))\n const enrollments = rows.map((row) => ({\n ...enrollmentRecord(row),\n reviewerName: row.reviewedBy ? (names.get(row.reviewedBy) ?? null) : null\n }))\n return { enrollments, total: counts[status], counts }\n },\n async review(\n actorId: string,\n enrollmentId: string,\n status: Exclude<EnrollmentStatus, 'pending'>,\n input: EnrollmentReviewInput\n ): Promise<EnrollmentRecord> {\n return database.transaction().execute(async (transaction) => {\n const current = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('id', '=', enrollmentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (\n !ALLOWED_TRANSITIONS[current.status].has(status) ||\n (input.expectedStatus !== undefined && current.status !== input.expectedStatus)\n ) {\n throw new AdminDomainError(\n 'invalid_enrollment_transition',\n `Enrollment cannot transition from ${current.status} to ${status}`\n )\n }\n const now = new Date()\n const approvedUser =\n status === 'approved'\n ? await transaction\n .selectFrom('user')\n .select('id')\n .where('email', '=', current.emailNormalized)\n .executeTakeFirst()\n : undefined\n const row = await transaction\n .updateTable('enrollment')\n .set({\n status,\n reviewedAt: now,\n reviewedBy: actorId,\n reviewNote: input.note?.trim() || null,\n approvedUserId: approvedUser?.id ?? current.approvedUserId\n })\n .where('id', '=', enrollmentId)\n .where('status', '=', current.status)\n .returningAll()\n .executeTakeFirstOrThrow()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: `enrollment.${status}`,\n subjectType: 'enrollment',\n subjectId: enrollmentId,\n metadata: { email: row.emailNormalized },\n createdAt: now\n })\n .execute()\n await enqueueEnrollmentReview(transaction, emailOptions, {\n enrollmentId,\n recipientEmail: row.emailNormalized,\n name: row.name ?? 'there',\n status,\n reviewedAt: now,\n invite: input.invite,\n waitlist: row.source === 'waitlist'\n })\n return enrollmentRecord(row)\n })\n },\n /**\n * Approves every waiting request and sends each person the founder's letter instead of the\n * plain approval, on the official deployment. Each approval is its own review, so one that\n * another administrator decided meanwhile is skipped rather than undoing the rest.\n */\n async invitePending(actorId: string): Promise<{ invited: number }> {\n // Approving everyone without the letters going out would be a silent bulk approval.\n if (!emailOptions.invitations || !emailOptions.email) {\n throw new AdminDomainError(\n 'invitations_unavailable',\n 'Only the official deployment, with email configured, sends invitation letters'\n )\n }\n const pending = await database\n .selectFrom('enrollment')\n .select('id')\n .where('status', '=', 'pending')\n .orderBy('requestedAt')\n .execute()\n let invited = 0\n for (const { id } of pending) {\n try {\n await service.review(actorId, id, 'approved', {\n invite: true,\n expectedStatus: 'pending'\n })\n invited++\n } catch (error) {\n // Decided by someone else meanwhile, or gone with an address change: skip it.\n if (!(error instanceof AdminDomainError) && !(error instanceof NoResultError)) throw error\n }\n }\n return { invited }\n },\n async bindApprovedUser(email: string, userId: string): Promise<void> {\n await database\n .updateTable('enrollment')\n .set({ approvedUserId: userId })\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .where('status', '=', 'approved')\n .execute()\n },\n /**\n * Moves an approved account's enrollment to the address it changed to, so the approval stays\n * with the account rather than with an address it no longer uses. Any other request from the\n * new address gives way to it.\n */\n async followEmailChange(userId: string, email: string): Promise<void> {\n const emailNormalized = normalizeEnrollmentEmail(email)\n await database.transaction().execute(async (transaction) => {\n const approved = await transaction\n .selectFrom('enrollment')\n .select(['id', 'emailNormalized'])\n .where('approvedUserId', '=', userId)\n .where('status', '=', 'approved')\n .forUpdate()\n .executeTakeFirst()\n if (!approved || approved.emailNormalized === emailNormalized) return\n await transaction\n .deleteFrom('enrollment')\n .where('emailNormalized', '=', emailNormalized)\n .where('id', '!=', approved.id)\n .execute()\n await transaction\n .updateTable('enrollment')\n .set({ emailNormalized })\n .where('id', '=', approved.id)\n .execute()\n })\n },\n async pendingCount(): Promise<number> {\n const row = await database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n }\n return service\n}\nexport type EnrollmentService = ReturnType<typeof createEnrollmentService>\n","import type { Dialect } from 'kysely'\nimport { CamelCasePlugin, Kysely } from 'kysely'\n\nimport type { CloudDatabase } from './tables'\n\nexport type CloudDatabaseOptions = {\n dialect: Dialect\n}\n\nexport function createCloudDatabase(options: CloudDatabaseOptions): Kysely<CloudDatabase> {\n return new Kysely<CloudDatabase>({\n dialect: options.dialect,\n plugins: [new CamelCasePlugin()]\n })\n}\n","import type { ExpressionBuilder } from 'kysely'\n\nimport type { CloudDatabase } from './tables'\n\n/**\n * `user.id` as text, the form every other table keeps account IDs in, such as a document's\n * `createdBy`, so the two can be compared.\n */\nexport function userIdText(expression: ExpressionBuilder<CloudDatabase, 'user'>) {\n return expression.cast<string>(expression.ref('user.id'), 'text')\n}\n\n/** Whether the user row in scope is banned, by a ban that has not run out. */\nexport function isBannedNow(expression: ExpressionBuilder<CloudDatabase, 'user'>) {\n return expression.and([\n expression('user.banned', '=', true),\n expression.or([\n expression('user.banExpires', 'is', null),\n expression('user.banExpires', '>', new Date())\n ])\n ])\n}\n","import {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { cloudAdminAuditFilterSchema, type CloudAdminAuditFilter } from '#cloud/contract'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { uniq } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\n/** Events by what they are about; every event is under `all`. */\nconst FILTERS: ListFilters<CloudAdminAuditFilter, 'adminAuditEvent'> = {\n all: (expression) => expression.lit(true),\n accounts: (expression) => expression('adminAuditEvent.subjectType', '=', 'user'),\n requests: (expression) => expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n email: (expression) => expression('adminAuditEvent.subjectType', '=', 'transactional-email'),\n documents: (expression) =>\n expression('adminAuditEvent.subjectType', 'in', [\n 'document',\n 'document-share',\n 'document-report'\n ])\n}\n\ntype AuditExpression = ExpressionBuilder<CloudDatabase, 'adminAuditEvent'>\n\n/** Events whose actor, or the account or request they are about, has `pattern` in a name or email. */\nfunction searchCondition(pattern: string) {\n return (expression: AuditExpression) => {\n const account = (column: 'adminAuditEvent.actorUserId' | 'adminAuditEvent.subjectId') =>\n expression.exists(\n expression\n .selectFrom('user')\n .select('user.id')\n .whereRef(userIdText, '=', column)\n .where((inner) =>\n inner.or([inner('user.name', 'ilike', pattern), inner('user.email', 'ilike', pattern)])\n )\n )\n return expression.or([\n account('adminAuditEvent.actorUserId'),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'user'),\n account('adminAuditEvent.subjectId')\n ]),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n expression.exists(\n expression\n .selectFrom('enrollment')\n .select('enrollment.id')\n .where((inner) =>\n inner(\n inner.cast('enrollment.id', 'text'),\n '=',\n inner.ref('adminAuditEvent.subjectId')\n )\n )\n .where((inner) =>\n inner.or([\n inner('enrollment.name', 'ilike', pattern),\n inner('enrollment.emailNormalized', 'ilike', pattern)\n ])\n )\n )\n ])\n ])\n }\n}\n\n/** The name an entry recorded about its subject, as deleting an account does. */\nfunction recordedName(metadata: unknown): string | undefined {\n if (typeof metadata !== 'object' || metadata === null || !('name' in metadata)) return undefined\n return typeof metadata.name === 'string' ? metadata.name : undefined\n}\n\nexport function createAdminAuditService(database: Kysely<CloudDatabase>) {\n return {\n /**\n * A page of events, newest first, each with its actor's and subject's names while the server\n * knows them, and how many match the search under each filter.\n */\n async list(query: AdminListQuery<CloudAdminAuditFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('adminAuditEvent')\n if (search) searched = searched.where(searchCondition(containsPattern(search)))\n const counts = await countEachFilter(searched, cloudAdminAuditFilterSchema.options, FILTERS)\n const events = await searched\n .where(FILTERS[filter])\n .selectAll()\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Accounts and requests are named by UUID; anything else is not looked up.\n const userIds = uniq(\n events.flatMap((event) =>\n event.subjectType === 'user' ? [event.actorUserId, event.subjectId] : [event.actorUserId]\n )\n ).filter(isUUID)\n const enrollmentIds = uniq(\n events.flatMap((event) => (event.subjectType === 'enrollment' ? [event.subjectId] : []))\n ).filter(isUUID)\n const documentIds = uniq(\n events.flatMap((event) => (event.subjectType === 'document' ? [event.subjectId] : []))\n ).filter(isUUID)\n const [users, enrollments, documents] = await Promise.all([\n userIds.length\n ? database.selectFrom('user').select(['id', 'name']).where('id', 'in', userIds).execute()\n : [],\n enrollmentIds.length\n ? database\n .selectFrom('enrollment')\n .select(['id', 'name', 'emailNormalized'])\n .where('id', 'in', enrollmentIds)\n .execute()\n : [],\n documentIds.length\n ? database\n .selectFrom('document')\n .select(['id', 'name'])\n .where('id', 'in', documentIds)\n .execute()\n : []\n ])\n const documentNames = new Map(documents.map((document) => [document.id, document.name]))\n const names = new Map(users.map((user) => [user.id, user.name]))\n const requesters = new Map(\n enrollments.map((enrollment) => [\n enrollment.id,\n enrollment.name ?? enrollment.emailNormalized\n ])\n )\n const subjectName = (type: string, id: string) => {\n if (type === 'enrollment') return requesters.get(id)\n if (type === 'document') return documentNames.get(id)\n return names.get(id)\n }\n const rows = events.map((event) => ({\n id: event.id,\n actor: { id: event.actorUserId, name: names.get(event.actorUserId) ?? null },\n action: event.action,\n subject: {\n type: event.subjectType,\n id: event.subjectId,\n // A deleted account is named by what its deletion's entry recorded.\n name:\n subjectName(event.subjectType, event.subjectId) ?? recordedName(event.metadata) ?? null\n },\n metadata: event.metadata,\n createdAt: event.createdAt\n }))\n return { events: rows, total: counts[filter], counts }\n }\n }\n}\n\nexport type AdminAuditService = ReturnType<typeof createAdminAuditService>\n","import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'\nimport { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { cloudAdminEmailFilterSchema, type CloudAdminEmailFilter } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\n/** The enrollment status each message describes; a message is resent only while it still holds. */\nconst ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {\n 'enrollment-requested': 'pending',\n 'enrollment-approved': 'approved',\n 'enrollment-invited': 'approved',\n 'enrollment-rejected': 'rejected',\n 'enrollment-revoked': 'revoked'\n}\n\n/** Messages by how their delivery went; every message is under `all`. */\nconst FILTERS: ListFilters<CloudAdminEmailFilter, 'transactionalEmail'> = {\n all: (expression) => expression.lit(true),\n sent: (expression) => expression('status', '=', 'accepted'),\n waiting: (expression) => expression('status', 'in', ['pending', 'sending']),\n failed: (expression) => expression('status', '=', 'failed')\n}\n\nexport function createAdminEmailService(\n database: Kysely<CloudDatabase>,\n email?: TransactionalEmailService,\n links: { publicURL: string } = { publicURL: '' }\n) {\n return {\n /** A page of messages, newest first, with how many match the search under each filter. */\n async list(query: AdminListQuery<CloudAdminEmailFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('transactionalEmail')\n if (search) {\n searched = searched.where('recipientEmailNormalized', 'ilike', containsPattern(search))\n }\n const counts = await countEachFilter(searched, cloudAdminEmailFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select([\n 'id',\n 'kind',\n 'recipientEmailNormalized',\n 'status',\n 'attemptCount',\n 'nextAttemptAt',\n 'transport',\n 'transportMessageId',\n 'lastErrorCode',\n 'createdAt',\n 'acceptedAt'\n ])\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n return {\n messages: rows.map((row) => ({\n ...row,\n regeneratable: row.kind.startsWith('enrollment-')\n })),\n total: counts[filter],\n counts\n }\n },\n async regenerate(actorId: string, messageId: string): Promise<void> {\n if (!email)\n throw new AdminDomainError('email_regeneration_unavailable', 'Email delivery is disabled')\n await database.transaction().execute(async (transaction) => {\n const original = await transaction\n .selectFrom('transactionalEmail')\n .select(['id', 'kind', 'recipientEmailNormalized'])\n .where('id', '=', messageId)\n .executeTakeFirstOrThrow()\n if (\n !original.kind.startsWith('enrollment-') ||\n original.kind === 'admin-enrollment-notification'\n ) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'This message cannot be regenerated'\n )\n }\n const kind = original.kind\n const enrollment = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', original.recipientEmailNormalized)\n .executeTakeFirst()\n if (!enrollment)\n throw new AdminDomainError('email_regeneration_unavailable', 'Enrollment is unavailable')\n if (ENROLLMENT_MESSAGE_STATUS[kind] !== enrollment.status) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'The enrollment no longer matches this message'\n )\n }\n await email.enqueue(\n {\n idempotencyKey: `admin-regeneration/${messageId}/${crypto.randomUUID()}`,\n kind,\n recipientEmail: enrollment.emailNormalized,\n payload: {\n name: enrollment.name ?? 'there',\n actionURL:\n kind === 'enrollment-approved' || kind === 'enrollment-invited'\n ? links.publicURL\n : new URL('/auth/sign-in', links.publicURL).href\n }\n },\n transaction\n )\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'email.regenerated',\n subjectType: 'transactional-email',\n subjectId: messageId,\n metadata: { replacementKind: kind }\n })\n .execute()\n })\n }\n }\n}\n\nexport type AdminEmailService = ReturnType<typeof createAdminEmailService>\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport function createAdminOperationsService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n async function emailCount(status: 'pending' | 'failed'): Promise<number> {\n const row = await database\n .selectFrom('transactionalEmail')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', status)\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n\n return {\n async summary() {\n const [\n pendingEnrollment,\n openReports,\n pendingEmail,\n failedEmail,\n accounts,\n workspaces,\n documents,\n stored\n ] = await Promise.all([\n database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('documentReport')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'open')\n .executeTakeFirstOrThrow(),\n emailCount('pending'),\n emailCount('failed'),\n database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspace')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('document')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('deletedAt', 'is', null)\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspaceStorageUsage')\n .select(({ fn }) => fn.sum<number | null>('committedBytes').as('bytes'))\n .executeTakeFirstOrThrow()\n ])\n return {\n deployment: config.deployment,\n enrollmentMode: config.enrollmentMode,\n emailTransport: config.emailTransport,\n pendingEnrollment: Number(pendingEnrollment.count),\n openReports: Number(openReports.count),\n pendingEmail,\n failedEmail,\n accounts: Number(accounts.count),\n workspaces: Number(workspaces.count),\n documents: Number(documents.count),\n storedBytes: Number(stored.bytes ?? 0)\n }\n }\n }\n}\n\nexport type AdminOperationsService = ReturnType<typeof createAdminOperationsService>\n","import type { MiddlewareHandler } from 'hono'\n\nexport type CloudLogLevel = 'error' | 'warn' | 'info'\n\nexport type CloudLoggedError = {\n name: string\n message: string\n stack?: string\n cause?: CloudLoggedError\n}\n\n/** What a log line carries besides its message; never who made a request or what it carried. */\nexport type CloudLogFields = Record<\n string,\n string | number | boolean | undefined | CloudLoggedError\n>\n\n/** One structured log line. */\nexport type CloudLogLine = CloudLogFields & { level: CloudLogLevel; message: string }\n\n/**\n * Writes a log line where the runtime's logs go, in the form they index best. Runtimes pass their\n * own to `createLoggingErrorReporter`; `writeJSONLine` is the default.\n */\nexport type CloudLogWriter = (line: CloudLogLine) => void\n\n/** Writes the line as one line of JSON, at the console method of its level. */\nexport const writeJSONLine: CloudLogWriter = (line) => {\n console[line.level](JSON.stringify(line))\n}\n\n/** How deep a chain of causes is written out. */\nconst MAXIMUM_CAUSES = 4\n\n/** An error as a log line keeps it: its name, message, stack, and causes. */\nexport function loggedError(error: unknown, depth = 0): CloudLoggedError {\n if (!(error instanceof Error)) return { name: 'NonError', message: String(error) }\n const cause =\n error.cause !== undefined && depth < MAXIMUM_CAUSES\n ? loggedError(error.cause, depth + 1)\n : undefined\n return { name: error.name, message: error.message, stack: error.stack, ...(cause && { cause }) }\n}\n\n/**\n * Writes a warning or note through the default writer, from code no runtime hands a writer to.\n * Errors go through `reportCloudError`, which logs with the runtime's.\n */\nexport function logCloud(level: CloudLogLevel, message: string, fields: CloudLogFields = {}): void {\n writeJSONLine({ ...fields, level, message })\n}\n\n/** Reads the ID that what stands in front of the server gave a request, if the runtime trusts it. */\nexport type ForwardedRequestId = (headers: Headers) => string | undefined\n\n/**\n * Names each request as the `requestId` variable, from what the runtime trusts in front of it\n * (such as Cloudflare's ray ID) or else a new UUID, and answers with it as `X-Request-Id` so a\n * person reporting a failure can quote it. Nested servers each name the request; the innermost\n * one that answered keeps its ID on the response.\n */\nexport function cloudRequestId(\n forwarded?: ForwardedRequestId\n): MiddlewareHandler<{ Variables: { requestId: string } }> {\n return async (context, next) => {\n const id = forwarded?.(context.req.raw.headers) ?? crypto.randomUUID()\n context.set('requestId', id)\n context.header('X-Request-Id', id)\n await next()\n // A response the handler built itself, such as a page an inner server answered, misses the\n // prepared header; one an inner layer named keeps its ID. A socket upgrade is left alone.\n if (context.res.status !== 101 && !context.res.headers.has('X-Request-Id')) {\n context.header('X-Request-Id', id)\n }\n }\n}\n","import type { ErrorReportContext, ErrorReporter } from '#cloud/errors'\nimport { loggedError, writeJSONLine, type CloudLogWriter } from '#cloud/server/logging'\nimport type { Context, ErrorHandler } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport { routePath } from 'hono/route'\nimport * as v from 'valibot'\n\n/** Where the server caught an error. */\nexport const CLOUD_ERROR_SOURCES = [\n 'request',\n 'background',\n 'cleanup',\n 'email',\n 'relay',\n 'scheduled',\n 'setup'\n] as const\nexport type CloudErrorSource = (typeof CLOUD_ERROR_SOURCES)[number]\n\n/**\n * What the server knows about a caught error. For a request: its method, the route pattern it\n * matched, its ID, the signed-in user's account ID, and the IDs of the records its path names;\n * never what it carried. Error tracking sends the account and record IDs only where the\n * deployment's `[error_tracking]` sets `include_ids`; the server's own log always has them.\n */\nexport type CloudErrorContext = ErrorReportContext<CloudErrorSource>\n\n/**\n * Logs a caught error and, when the deployment configures error tracking, sends it there. Runtimes\n * create one with `createLoggingErrorReporter`; its promise never rejects.\n */\nexport type CloudErrorReporter = ErrorReporter<CloudErrorSource>\n\n/**\n * A reporter that writes the error as a structured line with the runtime's writer, then hands it\n * to `send`, such as PostHog's, if the deployment has one.\n */\nexport function createLoggingErrorReporter(\n log: CloudLogWriter,\n send?: CloudErrorReporter\n): CloudErrorReporter {\n return async (error, context) => {\n try {\n log({\n level: 'error',\n message: context.message ?? 'Failed',\n source: context.source,\n method: context.method,\n route: context.route,\n requestId: context.requestId,\n userId: context.userId,\n ...context.resources,\n error: loggedError(error)\n })\n } catch (failure) {\n // A writer that fails must not stop the report or reject; the console still gets both.\n console.error('[Cloud] Writing a log line failed:', failure, error)\n }\n await send?.(error, context)\n }\n}\n\n/** Without a reporter, errors are still logged, as lines of JSON. */\nconst logOnly = createLoggingErrorReporter(writeJSONLine)\n\n/** Logs a caught error and reports it, through the runtime's reporter. */\nexport function reportCloudError(\n reporter: CloudErrorReporter | undefined,\n message: string,\n error: unknown,\n context: CloudErrorContext\n): Promise<void> {\n return (reporter ?? logOnly)(error, { ...context, message })\n}\n\n/**\n * Path parameters that name a record by its ID. Others are left out: an invitation's or a\n * continuation's ID is the link that grants it, and an OAuth callback's names a provider.\n */\nconst RECORD_PARAMETERS = [\n 'documentId',\n 'workspaceId',\n 'threadId',\n 'commentId',\n 'versionId',\n 'revisionId',\n 'shareId',\n 'uploadId'\n] as const\n\nconst validatedParametersSchema = v.record(v.string(), v.unknown())\n\n/**\n * The record IDs the request's path named, as its route's parameter validator accepted them: a\n * path no validator checked names none, so what a caller typed never reaches a report.\n */\nfunction requestResources(context: Context): Record<string, string> {\n const validated = v.safeParse(validatedParametersSchema, context.req.valid('param' as never))\n if (!validated.success) return {}\n return Object.fromEntries(\n RECORD_PARAMETERS.flatMap((name) => {\n const id = validated.output[name]\n return typeof id === 'string' ? [[name, id]] : []\n })\n )\n}\n\nfunction requestContext(context: Context): CloudErrorContext {\n const requestId: unknown = context.get('requestId')\n const actor: unknown = context.get('actor')\n const resources = requestResources(context)\n const userId =\n actor && typeof actor === 'object' && 'userId' in actor && typeof actor.userId === 'string'\n ? actor.userId\n : undefined\n return {\n source: 'request',\n method: context.req.method,\n route: routePath(context),\n ...(Object.keys(resources).length > 0 && { resources }),\n ...(typeof requestId === 'string' && { requestId }),\n ...(userId && { userId })\n }\n}\n\n/**\n * The app's last error handler, as Hono's default: an `HTTPException` answers with its response,\n * anything else is logged, reported, and answered with a 500 naming the request's `X-Request-Id`.\n */\nexport function cloudErrorHandler(reporter: CloudErrorReporter | undefined): ErrorHandler {\n return (error, context) => {\n if (error instanceof HTTPException) return error.getResponse()\n void reportCloudError(reporter, 'Request failed', error, requestContext(context))\n return context.text('Internal Server Error', 500)\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ExpressionBuilder } from 'kysely'\n\n/**\n * No revision refers to the stored file any more, no workspace keeps it as an image, and no\n * collaboration room keeps it as its snapshot, so it can leave the object store.\n */\nexport function unreferencedObject(expression: ExpressionBuilder<CloudDatabase, 'storageObject'>) {\n return expression.and([\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision')\n .select('documentRevision.id')\n .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceImage')\n .select('workspaceImage.checksum')\n .whereRef('workspaceImage.storageObjectId', '=', 'storageObject.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRoomSnapshot')\n .select('documentRoomSnapshot.documentId')\n .whereRef('documentRoomSnapshot.snapshotObjectId', '=', 'storageObject.id')\n )\n )\n ])\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { reportCloudError, type CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { omit } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely, Transaction } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\nexport type DocumentCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n /** How long a document stays in Trash before cleanup destroys it. */\n retentionMs: number\n /** How long a document deleted forever keeps its files before cleanup destroys it; 0 is at once. */\n purgeGraceMs: number\n now?: Date\n}\n\nexport type DocumentCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n objectsDeleted: number\n bytesReclaimed: number\n}\n\nexport type DocumentCleanupService = {\n cleanupDeletedDocuments(options: DocumentCleanupOptions): Promise<DocumentCleanupResult>\n /**\n * Destroys one document deleted forever now, as cleanup would once its grace passed. False when\n * it isn't deleted forever, is being cleaned already, or has a save in flight; it then waits for\n * the next pass. Throws, with the failure as its cause, when destroying it failed; the failure\n * is reported, and the next pass tries again.\n */\n destroyPurgedDocument(\n documentId: string,\n options: { leaseDurationMs: number; now?: Date }\n ): Promise<boolean>\n}\n\nexport type DocumentCleanupServiceOptions = {\n /** Where each document cleanup couldn't destroy is reported; a pass carries on with the rest. */\n reportError?: CloudErrorReporter\n}\n\ntype ClaimedDocument = {\n id: string\n workspaceId: string\n purgedBytes: number\n}\n\ntype StoredRevisionObject = {\n id: string\n objectKey: string\n byteSize: number\n}\n\n/**\n * Which deleted documents a pass claims: those in Trash deleted by `deletedBefore`, and those\n * deleted forever by `purgedBefore`, or only one of them.\n */\ntype ClaimFilter = {\n batchSize: number\n deletedBefore: Date\n purgedBefore: Date\n staleBefore: Date\n now: Date\n claimId: string\n documentId?: string\n}\n\n/** A deleted document whose time is up: past retention in Trash, or past grace deleted forever. */\nfunction due(deletedBefore: Date, purgedBefore: Date) {\n return (expression: ExpressionBuilder<CloudDatabase, 'document'>) =>\n expression.or([\n expression.and([\n expression('purgedAt', 'is', null),\n expression('deletedAt', 'is not', null),\n expression('deletedAt', '<=', deletedBefore)\n ]),\n expression('purgedAt', '<=', purgedBefore)\n ])\n}\n\nexport function createDocumentCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: DocumentCleanupServiceOptions = {}\n): DocumentCleanupService {\n async function clean(\n filter: ClaimFilter\n ): Promise<DocumentCleanupResult & { failures: unknown[] }> {\n const documents = await claimDocuments(database, filter)\n const result = {\n claimed: documents.length,\n cleaned: 0,\n failed: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0,\n failures: [] as unknown[]\n }\n for (const document of documents) {\n try {\n const revisionObjects = await documentObjects(database, document.id)\n for (const object of revisionObjects) await objects.delete(object.objectKey)\n const reclaimed = await removeDocumentMetadata(database, document, revisionObjects, filter)\n if (!reclaimed) continue\n result.cleaned++\n result.objectsDeleted += reclaimed.objectsDeleted\n result.bytesReclaimed += reclaimed.bytesReclaimed\n } catch (error) {\n result.failed++\n result.failures.push(error)\n // Only the document's and its workspace's IDs: its name and the people on it stay out.\n await reportCloudError(\n options.reportError,\n `Cleaning up document ${document.id} failed`,\n error,\n {\n source: 'cleanup',\n resources: { documentId: document.id, workspaceId: document.workspaceId }\n }\n )\n // Out of Trash already, a document whose files are partly gone is never restorable; the\n // next pass tries again.\n await releaseClaim(database, document.id, filter.claimId)\n }\n }\n return result\n }\n\n return {\n async cleanupDeletedDocuments(input) {\n const now = input.now ?? new Date()\n const result = await clean({\n batchSize: input.batchSize,\n deletedBefore: new Date(now.getTime() - input.retentionMs),\n purgedBefore: new Date(now.getTime() - input.purgeGraceMs),\n staleBefore: new Date(now.getTime() - input.leaseDurationMs),\n now,\n claimId: crypto.randomUUID()\n })\n return omit(result, ['failures'])\n },\n\n async destroyPurgedDocument(documentId, input) {\n const now = input.now ?? new Date()\n const result = await clean({\n batchSize: 1,\n // Only a document deleted forever, never one still in Trash.\n deletedBefore: new Date(0),\n purgedBefore: now,\n staleBefore: new Date(now.getTime() - input.leaseDurationMs),\n now,\n claimId: crypto.randomUUID(),\n documentId\n })\n if (result.failures.length > 0) {\n throw new Error(`Document ${documentId} could not be destroyed`, {\n cause: result.failures[0]\n })\n }\n return result.cleaned > 0\n }\n }\n}\n\nasync function claimDocuments(\n database: Kysely<CloudDatabase>,\n { batchSize, deletedBefore, purgedBefore, staleBefore, now, claimId, documentId }: ClaimFilter\n): Promise<ClaimedDocument[]> {\n return database.transaction().execute(async (transaction) => {\n let candidates = transaction\n .selectFrom('document')\n .select(['id', 'workspaceId', 'purgedBytes'])\n .where(due(deletedBefore, purgedBefore))\n if (documentId !== undefined) candidates = candidates.where('id', '=', documentId)\n const rows = await candidates\n .where((expression) =>\n expression.or([\n expression('cleanupClaimId', 'is', null),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('upload')\n .select('upload.id')\n .whereRef('upload.documentId', '=', 'document.id')\n .where('upload.status', 'in', ['pending', 'cleaning'])\n )\n )\n )\n .orderBy('deletedAt')\n .limit(batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (rows.length === 0) return []\n await transaction\n .updateTable('document')\n .set({ cleanupClaimId: claimId, cleanupClaimedAt: now })\n .where(\n 'id',\n 'in',\n rows.map((document) => document.id)\n )\n .execute()\n return rows.map((row) => ({ ...row, purgedBytes: Number(row.purgedBytes) }))\n })\n}\n\n/** The files only this document's revisions hold, which destroying it frees. */\nexport async function documentObjects(\n database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n documentId: string\n): Promise<StoredRevisionObject[]> {\n const rows = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select(['storageObject.id', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('documentRevision.documentId', '=', documentId)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision as otherRevision')\n .select('otherRevision.id')\n .whereRef('otherRevision.storageObjectId', '=', 'storageObject.id')\n .where('otherRevision.documentId', '!=', documentId)\n )\n )\n )\n .execute()\n return rows.map((row) => ({ ...row, byteSize: Number(row.byteSize) }))\n}\n\nasync function removeDocumentMetadata(\n database: Kysely<CloudDatabase>,\n document: ClaimedDocument,\n objects: StoredRevisionObject[],\n { deletedBefore, purgedBefore, claimId }: ClaimFilter\n): Promise<{ objectsDeleted: number; bytesReclaimed: number } | null> {\n return database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select('id')\n .where('id', '=', document.id)\n .where(due(deletedBefore, purgedBefore))\n .where('cleanupClaimId', '=', claimId)\n .forUpdate()\n .executeTakeFirst()\n if (!locked) return null\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: null })\n .where('id', '=', document.id)\n .execute()\n await transaction.deleteFrom('documentRevision').where('documentId', '=', document.id).execute()\n let objectsDeleted = 0\n let bytesReclaimed = 0\n for (const object of objects) {\n const deleted = await transaction\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .executeTakeFirst()\n if (Number(deleted.numDeletedRows) > 0) {\n objectsDeleted++\n bytesReclaimed += object.byteSize\n }\n }\n // Deleting it forever already took its files off the workspace's usage.\n const released = Math.max(0, bytesReclaimed - document.purgedBytes)\n if (released > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', released),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', document.workspaceId)\n .execute()\n }\n await transaction.deleteFrom('document').where('id', '=', document.id).execute()\n // A workspace whose account was deleted waits, with nobody in it, for its last document.\n await transaction\n .deleteFrom('workspace')\n .where('id', '=', document.workspaceId)\n .where((expression) =>\n expression.and([\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'workspace.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('document')\n .select('document.id')\n .whereRef('document.workspaceId', '=', 'workspace.id')\n )\n )\n ])\n )\n .execute()\n return { objectsDeleted, bytesReclaimed }\n })\n}\n\nasync function releaseClaim(\n database: Kysely<CloudDatabase>,\n documentId: string,\n claimId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ cleanupClaimId: null, cleanupClaimedAt: null })\n .where('id', '=', documentId)\n .where('cleanupClaimId', '=', claimId)\n .execute()\n}\n","import { documentObjects } from '#cloud/server/cleanup/documents'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { sumBy } from 'es-toolkit'\nimport type { Transaction } from 'kysely'\n\n/**\n * Deleting forever: deleted documents leave everyone's sight, Trash included, and the files only\n * they hold come off their workspaces' usage at once. Their files and rows stay through the\n * deployment's grace, so a server administrator can still bring them back, then cleanup destroys\n * them and takes off only what this did not. `purgedBy` is empty for an account's deletion.\n */\nexport async function markPurged(\n transaction: Transaction<CloudDatabase>,\n documentIds: readonly string[],\n purgedBy: string | null,\n now: Date\n): Promise<void> {\n for (const documentId of documentIds) {\n const document = await transaction\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', documentId)\n .where('purgedAt', 'is', null)\n .executeTakeFirst()\n if (!document) continue\n const bytes = sumBy(await documentObjects(transaction, documentId), (object) => object.byteSize)\n await transaction\n .updateTable('document')\n .set({ purgedAt: now, purgedBy, purgedBytes: bytes })\n .where('id', '=', documentId)\n .execute()\n if (bytes > 0) await changeUsage(transaction, document.workspaceId, -bytes)\n }\n}\n\n/**\n * Brings a document deleted forever back to life in its workspace: it is live again, and the\n * storage deleting it took off counts again.\n */\nexport async function unmarkPurged(\n transaction: Transaction<CloudDatabase>,\n document: { id: string; workspaceId: string; purgedBytes: number }\n): Promise<void> {\n await transaction\n .updateTable('document')\n // Changed now, so devices that deleted it stop hiding it.\n .set({\n deletedAt: null,\n deletedBy: null,\n purgedAt: null,\n purgedBy: null,\n purgedBytes: 0,\n updatedAt: new Date()\n })\n .where('id', '=', document.id)\n .execute()\n if (document.purgedBytes > 0) {\n await changeUsage(transaction, document.workspaceId, document.purgedBytes)\n }\n}\n\nasync function changeUsage(\n transaction: Transaction<CloudDatabase>,\n workspaceId: string,\n bytes: number\n): Promise<void> {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '+', bytes),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', workspaceId)\n .execute()\n}\n","import type { DocumentPermission, WorkspaceRole } from '#cloud/contract'\nimport { createAccessControl } from 'better-auth/plugins/access'\n\nexport const accessStatements = {\n workspace: ['read', 'update', 'delete', 'invite', 'manage-members'],\n /**\n * `delete` moves a document to Trash and back; `purge` deletes it from Trash for good.\n * `comment` writes comments, which everyone who can read may; `moderate` deletes anyone's.\n */\n document: ['create', 'read', 'comment', 'edit', 'moderate', 'share', 'delete', 'purge']\n} as const\n\ntype AccessStatements = typeof accessStatements\n\n/** Actions a check asks for, by resource; every listed action must be allowed. */\nexport type AccessRequest = {\n [Resource in keyof AccessStatements]?: AccessStatements[Resource][number][]\n}\n\nexport const accessControl = createAccessControl(accessStatements)\n\n/**\n * What a workspace member may do there, by role. Together with `documentRoles` this is the whole\n * permission policy: every check goes through `workspaceRoleCan` or `documentRoleCan`.\n */\nexport const workspaceRoles = {\n admin: accessControl.newRole({\n workspace: ['read', 'update', 'delete', 'invite', 'manage-members'],\n document: ['create', 'read', 'comment', 'edit', 'moderate', 'share', 'delete', 'purge']\n }),\n editor: accessControl.newRole({\n workspace: ['read'],\n document: ['create', 'read', 'comment', 'edit', 'moderate', 'share', 'delete']\n }),\n viewer: accessControl.newRole({\n workspace: ['read'],\n document: ['read', 'comment']\n })\n} satisfies Record<WorkspaceRole, unknown>\n\n/**\n * What someone may do with one document through something other than workspace membership: being\n * its owner, or a grant made to them. A grant lets its holder edit and share, never delete the\n * owner's document. Deleting from Trash for good is for the owner and workspace administrators.\n */\nexport const documentRoles = {\n owner: accessControl.newRole({\n document: ['read', 'comment', 'edit', 'moderate', 'share', 'delete', 'purge']\n }),\n editor: accessControl.newRole({ document: ['read', 'comment', 'edit', 'moderate', 'share'] }),\n viewer: accessControl.newRole({ document: ['read', 'comment'] })\n}\n\nexport type DocumentRole = keyof typeof documentRoles\n\n/** The document role a direct grant of this permission gives. */\nexport const GRANT_DOCUMENT_ROLE: Record<DocumentPermission, DocumentRole> = {\n view: 'viewer',\n edit: 'editor'\n}\n\nexport function workspaceRoleCan(role: WorkspaceRole, request: AccessRequest): boolean {\n return workspaceRoles[role].authorize(request).success\n}\n\nexport function documentRoleCan(role: DocumentRole, request: AccessRequest): boolean {\n return documentRoles[role].authorize(request).success\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { lockForTransaction } from '#cloud/server/db/expressions'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport class StorageQuotaExceededError extends Error {\n override readonly name = 'StorageQuotaExceededError'\n}\n\nexport type StorageQuotaSnapshot = {\n committedBytes: number\n reservedBytes: number\n}\n\ntype StorageDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/**\n * Takes the lock an owner's storage allowance is checked under, until the transaction ends.\n * Reservations hold it while they count and reserve; an ownership transfer holds it for both\n * owners, so no reservation counts a workspace under an owner it is leaving or joining.\n */\nexport function lockStorageAllowance(\n transaction: Transaction<CloudDatabase>,\n ownerId: string\n): Promise<void> {\n return lockForTransaction(transaction, `storage-quota:${ownerId}`)\n}\n\nexport function createStorageQuotaService(database: Kysely<CloudDatabase>) {\n async function ownerOf(executor: StorageDatabase, workspaceId: string): Promise<string | null> {\n const workspace = await executor\n .selectFrom('workspace')\n .select('ownerId')\n .where('id', '=', workspaceId)\n .executeTakeFirst()\n return workspace?.ownerId ?? null\n }\n\n /**\n * What `ownerId` holds and has reserved across every workspace they own, which all draw from\n * the owner's one allowance. Both totals come from one statement, so an upload committing\n * meanwhile counts once, as committed or as reserved.\n */\n async function usage(\n executor: StorageDatabase,\n ownerId: string,\n now = new Date()\n ): Promise<StorageQuotaSnapshot> {\n const owned = executor.selectFrom('workspace').select('id').where('ownerId', '=', ownerId)\n const row = await executor\n .selectNoFrom((expression) => [\n expression\n .selectFrom('workspaceStorageUsage')\n .select((sum) =>\n sum.fn.coalesce(sum.fn.sum('committedBytes'), sum.val(0)).as('committedBytes')\n )\n .where('workspaceId', 'in', owned)\n .as('committedBytes'),\n expression\n .selectFrom('uploadStorageReservation')\n .select((sum) => sum.fn.coalesce(sum.fn.sum('bytes'), sum.val(0)).as('reservedBytes'))\n .where('workspaceId', 'in', owned)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .where('expiresAt', '>', now)\n .as('reservedBytes')\n ])\n .executeTakeFirstOrThrow()\n return {\n committedBytes: Number(row.committedBytes ?? 0),\n reservedBytes: Number(row.reservedBytes ?? 0)\n }\n }\n\n async function reserve(\n executor: Transaction<CloudDatabase>,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n // The allowance spans the owner's workspaces, so the owner is what reservations queue on.\n // An ownership transfer holds the same lock, so the owner read once it is held stays put.\n let ownerId = await ownerOf(executor, input.workspaceId)\n for (;;) {\n if (ownerId === null) throw new Error('Workspace not found')\n await lockStorageAllowance(executor, ownerId)\n const current = await ownerOf(executor, input.workspaceId)\n if (current === ownerId) break\n ownerId = current\n }\n await executor\n .insertInto('workspaceStorageUsage')\n .values({ workspaceId: input.workspaceId, committedBytes: 0 })\n .onConflict((conflict) => conflict.column('workspaceId').doNothing())\n .execute()\n const held = await usage(executor, ownerId)\n if (\n input.maximumBytes !== null &&\n held.committedBytes + held.reservedBytes + input.bytes > input.maximumBytes\n ) {\n throw new StorageQuotaExceededError('Workspace storage quota exceeded')\n }\n await executor\n .insertInto('uploadStorageReservation')\n .values({\n id: crypto.randomUUID(),\n workspaceId: input.workspaceId,\n uploadId: input.uploadId,\n bytes: input.bytes,\n expiresAt: input.expiresAt,\n committedAt: null,\n releasedAt: null\n })\n .onConflict((conflict) => conflict.column('uploadId').doNothing())\n .execute()\n }\n\n async function commit(executor: StorageDatabase, uploadId: string): Promise<void> {\n const reservation = await executor\n .selectFrom('uploadStorageReservation')\n .select(['id', 'workspaceId', 'bytes', 'committedAt', 'releasedAt'])\n .where('uploadId', '=', uploadId)\n .forUpdate()\n .executeTakeFirst()\n if (!reservation || reservation.committedAt || reservation.releasedAt) return\n await executor\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) =>\n expression('committedBytes', '+', Number(reservation.bytes)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', reservation.workspaceId)\n .execute()\n await executor\n .updateTable('uploadStorageReservation')\n .set({ committedAt: new Date() })\n .where('id', '=', reservation.id)\n .execute()\n }\n\n async function release(executor: StorageDatabase, uploadId: string): Promise<void> {\n await executor\n .updateTable('uploadStorageReservation')\n .set({ releasedAt: new Date() })\n .where('uploadId', '=', uploadId)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .execute()\n }\n\n return {\n /** The pooled usage of the workspace's owner, or null when the workspace is gone. */\n async snapshot(workspaceId: string): Promise<StorageQuotaSnapshot | null> {\n const ownerId = await ownerOf(database, workspaceId)\n return ownerId === null ? null : usage(database, ownerId)\n },\n\n /** What `ownerId` holds and has reserved across every workspace they own. */\n async account(ownerId: string): Promise<StorageQuotaSnapshot> {\n return usage(database, ownerId)\n },\n\n async reserve(input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<void> {\n await database.transaction().execute((transaction) => reserve(transaction, input))\n },\n\n reserveInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n return reserve(transaction, input)\n },\n\n async commit(uploadId: string): Promise<void> {\n await database.transaction().execute((transaction) => commit(transaction, uploadId))\n },\n\n commitInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return commit(transaction, uploadId)\n },\n\n async release(uploadId: string): Promise<void> {\n await release(database, uploadId)\n },\n\n releaseInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return release(transaction, uploadId)\n }\n }\n}\n\nexport type StorageQuotaService = ReturnType<typeof createStorageQuotaService>\n","export class InvitationDeliveryError extends Error {\n override readonly name = 'InvitationDeliveryError'\n}\n\nexport class DocumentShareInvalidError extends Error {\n override readonly name = 'DocumentShareInvalidError'\n}\n\n/** A valid link this server opens only for people signed in to it. */\nexport class DocumentShareSignInRequiredError extends Error {\n override readonly name = 'DocumentShareSignInRequiredError'\n}\n","import { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\n\nconst CONTINUATION_SALT = utf8ToBytes('openpencil-cloud-invitation-continuation')\nconst CONTINUATION_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\n\nexport function hashCapability(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function capabilityHashMatches(stored: string, value: string): boolean {\n let expected: Uint8Array\n try {\n expected = hexToBytes(stored)\n } catch {\n return false\n }\n const actual = sha256(utf8ToBytes(value))\n if (expected.length !== actual.length) return false\n let difference = 0\n for (const [index, expectedByte] of expected.entries()) {\n difference |= expectedByte ^ (actual[index] ?? 0)\n }\n return difference === 0\n}\n\nfunction continuationKey(secret: string): Uint8Array {\n return hkdf(sha256, utf8ToBytes(secret), CONTINUATION_SALT, new Uint8Array(), 32)\n}\n\nexport async function encryptContinuationToken(secret: string, token: string): Promise<string> {\n return new CompactEncrypt(utf8ToBytes(token))\n .setProtectedHeader(CONTINUATION_HEADER)\n .encrypt(continuationKey(secret))\n}\n\nexport async function decryptContinuationToken(secret: string, value: string): Promise<string> {\n const { plaintext, protectedHeader } = await compactDecrypt(value, continuationKey(secret))\n if (\n protectedHeader.alg !== CONTINUATION_HEADER.alg ||\n protectedHeader.enc !== CONTINUATION_HEADER.enc\n ) {\n throw new Error('Unsupported invitation continuation encryption')\n }\n return new TextDecoder().decode(plaintext)\n}\n","import type { InvitationPreview } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentShareInvalidError } from '#cloud/server/sharing/errors'\nimport type { Kysely } from 'kysely'\n\nimport { capabilityHashMatches, decryptContinuationToken, encryptContinuationToken } from './crypto'\n\nconst CONTINUATION_LIFETIME_MS = 10 * 60_000\n\nexport type InvitationContinuationService = ReturnType<typeof createInvitationContinuationService>\n\nexport function createInvitationContinuationService(\n database: Kysely<CloudDatabase>,\n secret: string,\n validateInvitation: (invitationId: string, token: string) => Promise<InvitationPreview>\n) {\n return {\n async create(input: { invitationId: string; token: string }): Promise<{ id: string }> {\n await validateInvitation(input.invitationId, input.token)\n const id = crypto.randomUUID()\n await database\n .insertInto('invitationContinuation')\n .values({\n id,\n invitationId: input.invitationId,\n tokenEncrypted: await encryptContinuationToken(secret, input.token),\n expiresAt: new Date(Date.now() + CONTINUATION_LIFETIME_MS),\n consumedAt: null\n })\n .execute()\n return { id }\n },\n\n async consume(id: string): Promise<{ invitationId: string; token: string }> {\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .selectFrom('invitationContinuation')\n .select(['invitationId', 'tokenEncrypted', 'expiresAt', 'consumedAt'])\n .where('id', '=', id)\n .forUpdate()\n .executeTakeFirst()\n if (!row || row.consumedAt || new Date(row.expiresAt).getTime() <= Date.now()) {\n throw new DocumentShareInvalidError()\n }\n await transaction\n .updateTable('invitationContinuation')\n .set({ consumedAt: new Date() })\n .where('id', '=', id)\n .execute()\n return {\n invitationId: row.invitationId,\n token: await decryptContinuationToken(secret, row.tokenEncrypted)\n }\n })\n }\n }\n}\n\nexport function invitationTokenIsActive(\n invitation: {\n tokenHash: string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n revokedAt: Date | string | null\n },\n token: string\n): boolean {\n return (\n capabilityHashMatches(invitation.tokenHash, token) &&\n !invitation.acceptedAt &&\n !invitation.revokedAt &&\n new Date(invitation.expiresAt).getTime() > Date.now()\n )\n}\n\nexport function recipientHint(email: string): string {\n const [local = '', domain = ''] = email.split('@')\n const visible = local.slice(0, 2)\n return `${visible}${'*'.repeat(Math.max(3, local.length - visible.length))}@${domain}`\n}\n\nexport function invitationMatchesActor(actor: CloudActor, email: string): boolean {\n return email === actor.email.trim().toLowerCase()\n}\n","import type {\n DocumentGrant,\n DocumentInvitation,\n DocumentPermission,\n DocumentShare\n} from '#cloud/contract'\n\nexport function dateString(value: Date | string | null): string | null {\n if (value === null) return null\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function shareContract(row: {\n id: string\n documentId: string\n permission: DocumentPermission\n roomEpoch: number\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n expiresAt: Date | string | null\n revokedAt: Date | string | null\n lastUsedAt: Date | string | null\n}): DocumentShare {\n // Rows carry the secret's hash; responses name each field so it never goes out.\n return {\n id: row.id,\n documentId: row.documentId,\n permission: row.permission,\n roomEpoch: row.roomEpoch,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt),\n revokedAt: dateString(row.revokedAt),\n lastUsedAt: dateString(row.lastUsedAt)\n }\n}\n\nexport function grantContract(row: {\n id: string\n documentId: string\n userId: string\n permission: DocumentPermission\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n}): DocumentGrant {\n return {\n id: row.id,\n documentId: row.documentId,\n userId: row.userId,\n permission: row.permission,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? ''\n }\n}\n\nexport function invitationContract(row: {\n id: string\n documentId: string\n emailNormalized: string\n permission: DocumentPermission\n invitedBy: string\n invitedAt: Date | string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n}): DocumentInvitation {\n return {\n id: row.id,\n documentId: row.documentId,\n email: row.emailNormalized,\n permission: row.permission,\n invitedBy: row.invitedBy,\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? '',\n acceptedAt: dateString(row.acceptedAt)\n }\n}\n","import type { CreateWorkspaceInput, WorkspaceRole, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type WorkspaceDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nfunction summary(\n {\n ownerId,\n ...row\n }: Omit<WorkspaceSummary, 'owner' | 'createdAt' | 'updatedAt'> & {\n ownerId: string\n createdAt: Date | string\n updatedAt: Date | string\n },\n userId: string\n): WorkspaceSummary {\n return {\n ...row,\n owner: ownerId === userId,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n}\n\nexport async function listWorkspaces(\n database: WorkspaceDatabase,\n userId: string\n): Promise<WorkspaceSummary[]> {\n const rows = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspace.ownerId',\n 'workspaceMember.role'\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspace.updatedAt', 'desc')\n .execute()\n\n return rows.map((row) => summary(row, userId))\n}\n\nexport async function findWorkspace(\n database: WorkspaceDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceSummary | undefined> {\n const row = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspace.ownerId',\n 'workspaceMember.role'\n ])\n .where('workspace.id', '=', workspaceId)\n .where('workspaceMember.userId', '=', userId)\n .executeTakeFirst()\n return row ? summary(row, userId) : undefined\n}\n\nexport async function insertWorkspace(\n database: WorkspaceDatabase,\n actorId: string,\n input: CreateWorkspaceInput & { id: string; slug: string }\n): Promise<boolean> {\n const inserted = await database\n .insertInto('workspace')\n .values({\n id: input.id,\n name: input.name,\n slug: input.slug,\n createdBy: actorId,\n ownerId: actorId\n })\n .onConflict((conflict) => conflict.column('slug').doNothing())\n .returning('id')\n .executeTakeFirst()\n return inserted !== undefined\n}\n\nexport async function insertWorkspaceMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n userId: string,\n role: WorkspaceRole\n): Promise<void> {\n await database.insertInto('workspaceMember').values({ workspaceId, userId, role }).execute()\n}\n","import type {\n CreateWorkspaceInvitationInput,\n CreatedWorkspaceInvitation,\n InvitationPreview,\n WorkspaceInvitation,\n WorkspaceMembers,\n WorkspaceRole,\n WorkspaceSummary\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport { workspaceRoleCan, type AccessRequest } from '#cloud/server/auth/access-control'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email/types'\nimport {\n INVITATION_LIFETIME_MS,\n INVITATION_SECRET_BYTES,\n spendInvitationBudget\n} from '#cloud/server/invitations'\nimport { lockStorageAllowance } from '#cloud/server/quota/storage'\nimport {\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '#cloud/server/sharing/continuation'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { hashCapability } from '#cloud/server/sharing/crypto'\nimport { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'\nimport { compact, uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { randomHex } from '@open-pencil/std/random'\n\n/** The workspace does not exist, or the person is not a member of it. */\nexport class WorkspaceNotFoundError extends Error {\n constructor() {\n super('Workspace not found')\n this.name = 'WorkspaceNotFoundError'\n }\n}\n\n/** Only a workspace's administrators may do this. */\nexport class WorkspaceForbiddenError extends Error {\n constructor() {\n super('Workspace administrators only')\n this.name = 'WorkspaceForbiddenError'\n }\n}\n\n/** The change would leave a workspace with members but no administrator. */\nexport class WorkspaceLastAdminError extends Error {\n constructor() {\n super('A workspace needs an administrator')\n this.name = 'WorkspaceLastAdminError'\n }\n}\n\n/**\n * A workspace still holds documents: live ones, or deleted ones kept until cleanup removes their\n * files, which deleting the workspace now would leave behind in object storage.\n */\nexport class WorkspaceNotEmptyError extends Error {\n constructor(readonly reason: 'documents' | 'pending-cleanup') {\n super('Workspace still holds documents')\n this.name = 'WorkspaceNotEmptyError'\n }\n}\n\n/** The person invited already belongs to the workspace. */\nexport class WorkspaceAlreadyMemberError extends Error {\n constructor() {\n super('Already a member of this workspace')\n this.name = 'WorkspaceAlreadyMemberError'\n }\n}\n\n/** The invitation is unknown, used, withdrawn, expired, or meant for someone else. */\nexport class WorkspaceInvitationInvalidError extends Error {\n constructor() {\n super('Workspace invitation is not valid')\n this.name = 'WorkspaceInvitationInvalidError'\n }\n}\n\nexport type WorkspaceMemberServiceOptions = {\n email?: TransactionalEmailService\n publicURL: string\n /**\n * Told, after a change commits, the accounts whose seats it may have changed: the owner of the\n * workspace, and the one before when ownership passed on. Seats are the people who can edit\n * across the workspaces an account owns, which billing may charge for.\n */\n onSeatsChanged?: (accountIds: readonly string[]) => void\n}\n\nfunction invitationContract(row: {\n id: string\n emailNormalized: string\n role: WorkspaceRole\n invitedBy: string\n inviterName: string | null\n invitedAt: Date | string\n expiresAt: Date | string\n}): WorkspaceInvitation {\n return {\n id: row.id,\n email: row.emailNormalized,\n role: row.role,\n invitedBy: { id: row.invitedBy, name: row.inviterName },\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }\n}\n\n/**\n * Passes the workspace to its longest-standing other admin when its owner leaves or stops being\n * an admin, so its limits come from someone still running it. The last-admin guard keeps one.\n */\nexport async function handOverOwnership(\n database: Transaction<CloudDatabase>,\n workspaceId: string,\n leavingUserId: string\n): Promise<void> {\n const workspace = await database\n .selectFrom('workspace')\n .select('ownerId')\n .where('id', '=', workspaceId)\n // Changing the owner changes no key, so a reservation's foreign-key check on this row is\n // never kept waiting behind it while the transfer waits for that reservation's lock.\n .forNoKeyUpdate()\n .executeTakeFirstOrThrow()\n if (workspace.ownerId !== leavingUserId) return\n const successor = await database\n .selectFrom('workspaceMember')\n .select('userId')\n .where('workspaceId', '=', workspaceId)\n .where('role', '=', 'admin')\n .where('userId', '!=', leavingUserId)\n .orderBy('createdAt')\n .orderBy('userId')\n .executeTakeFirst()\n if (!successor) return\n // Reservations count this workspace under its owner's lock: hold both owners', in one order.\n for (const owner of [leavingUserId, successor.userId].toSorted()) {\n await lockStorageAllowance(database, owner)\n }\n await database\n .updateTable('workspace')\n .set({ ownerId: successor.userId, updatedAt: new Date() })\n .where('id', '=', workspaceId)\n .execute()\n}\n\nasync function adminCount(database: WorkspaceDatabase, workspaceId: string): Promise<number> {\n const rows = await database\n .selectFrom('workspaceMember')\n .select('userId')\n .where('workspaceId', '=', workspaceId)\n .where('role', '=', 'admin')\n .forUpdate()\n .execute()\n return rows.length\n}\n\n/** A member's row, locked until the transaction ends so roles change one at a time. */\nasync function lockedMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n memberId: string\n): Promise<{ role: WorkspaceRole }> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .forUpdate()\n .executeTakeFirst()\n if (!member) throw new WorkspaceNotFoundError()\n return member\n}\n\n/**\n * Who belongs to a workspace and who is invited to it. Administrators invite, change roles, and\n * remove people; anyone may leave. A workspace with members always keeps an administrator.\n */\nexport function createWorkspaceMemberService(\n database: Kysely<CloudDatabase>,\n options: WorkspaceMemberServiceOptions\n) {\n /** The workspace's owner as `database` sees it, inside the change's transaction. */\n async function ownerIn(database: WorkspaceDatabase, workspaceId: string): Promise<string | null> {\n const workspace = await database\n .selectFrom('workspace')\n .select('ownerId')\n .where('id', '=', workspaceId)\n .executeTakeFirst()\n return workspace?.ownerId ?? null\n }\n\n /**\n * Reports the owners whose seats a committed change touched, read inside its transaction, so\n * nothing after the commit can fail or see a later change.\n */\n function seatsChanged(owners: readonly (string | null)[]): void {\n const accountIds = uniq(compact(owners))\n if (accountIds.length > 0) options.onSeatsChanged?.(accountIds)\n }\n\n async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new WorkspaceNotFoundError()\n return workspace\n }\n\n async function requireAccess(\n userId: string,\n workspaceId: string,\n request: AccessRequest\n ): Promise<WorkspaceSummary> {\n const workspace = await membership(userId, workspaceId)\n if (!workspaceRoleCan(workspace.role, request)) throw new WorkspaceForbiddenError()\n return workspace\n }\n\n /** A workspace's members with their accounts; user ids are text in membership rows. */\n function memberUsers(workspaceId: string) {\n return database\n .selectFrom('workspaceMember')\n .innerJoin('user', (join) => join.onRef(userIdText, '=', 'workspaceMember.userId'))\n .where('workspaceMember.workspaceId', '=', workspaceId)\n }\n\n function acceptanceURL(invitationId: string, token: string): string {\n return cloudInvitationURL(options.publicURL, invitationId, token)\n }\n\n /** Invites someone by email; a newer invitation to the same address replaces the older. */\n async function invite(\n userId: string,\n workspaceId: string,\n input: CreateWorkspaceInvitationInput\n ): Promise<CreatedWorkspaceInvitation> {\n const workspace = await requireAccess(userId, workspaceId, { workspace: ['invite'] })\n const existing = await memberUsers(workspaceId)\n .select('workspaceMember.userId')\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)\n )\n .executeTakeFirst()\n if (existing) throw new WorkspaceAlreadyMemberError()\n const inviter = await database\n .selectFrom('user')\n .select(['name', 'locale'])\n .where('id', '=', userId)\n .executeTakeFirst()\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const url = acceptanceURL(id, token)\n const row = await database.transaction().execute(async (transaction) => {\n await spendInvitationBudget(transaction, { senderId: userId, email: input.email })\n await transaction\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('workspaceId', '=', workspaceId)\n .where('emailNormalized', '=', input.email)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .execute()\n const inserted = await transaction\n .insertInto('workspaceInvitation')\n .values({\n id,\n workspaceId,\n emailNormalized: input.email,\n role: input.role,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning(['id', 'emailNormalized', 'role', 'invitedBy', 'invitedAt', 'expiresAt'])\n .executeTakeFirstOrThrow()\n await options.email?.enqueue(\n {\n idempotencyKey: `workspace-invitation/${id}`,\n kind: 'workspace-invitation',\n recipientEmail: input.email,\n // Someone without an account yet reads the inviter's language.\n fallbackLocale: inviter?.locale,\n payload: {\n inviterName: inviter?.name ?? null,\n workspaceName: workspace.name,\n role: input.role,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL: url\n }\n },\n transaction\n )\n return inserted\n })\n return {\n invitation: invitationContract({ ...row, inviterName: inviter?.name ?? null }),\n acceptanceURL: url\n }\n }\n\n return {\n async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {\n await requireAccess(userId, workspaceId, { workspace: ['update'] })\n await database\n .updateTable('workspace')\n .set({ name, updatedAt: new Date() })\n .where('id', '=', workspaceId)\n .execute()\n return membership(userId, workspaceId)\n },\n\n async list(userId: string, workspaceId: string): Promise<WorkspaceMembers> {\n const workspace = await membership(userId, workspaceId)\n const members = await memberUsers(workspaceId)\n .select([\n 'workspaceMember.userId',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n 'user.name',\n 'user.email',\n 'user.image'\n ])\n .orderBy('workspaceMember.createdAt')\n .execute()\n const invitations = workspaceRoleCan(workspace.role, { workspace: ['invite'] })\n ? await database\n .selectFrom('workspaceInvitation')\n .leftJoin('user', (join) =>\n join.onRef(userIdText, '=', 'workspaceInvitation.invitedBy')\n )\n .select([\n 'workspaceInvitation.id',\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.invitedAt',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.invitedBy',\n 'user.name as inviterName'\n ])\n .where('workspaceInvitation.workspaceId', '=', workspaceId)\n .where('workspaceInvitation.acceptedAt', 'is', null)\n .where('workspaceInvitation.revokedAt', 'is', null)\n .where('workspaceInvitation.expiresAt', '>', new Date())\n .orderBy('workspaceInvitation.invitedAt')\n .execute()\n : []\n return {\n members: members.map((member) => ({\n userId: member.userId,\n name: member.name,\n email: member.email,\n image: member.image,\n role: member.role,\n joinedAt: dateString(member.createdAt) ?? ''\n })),\n invitations: invitations.map(invitationContract)\n }\n },\n\n invite,\n\n /** Sends a waiting invitation again with a new link; the old link stops working. */\n async resendInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<CreatedWorkspaceInvitation> {\n await requireAccess(userId, workspaceId, { workspace: ['invite'] })\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select(['emailNormalized', 'role'])\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!invitation) throw new WorkspaceNotFoundError()\n return invite(userId, workspaceId, {\n email: invitation.emailNormalized,\n role: invitation.role\n })\n },\n\n async revokeInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<void> {\n await requireAccess(userId, workspaceId, { workspace: ['invite'] })\n const result = await database\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new WorkspaceNotFoundError()\n },\n\n async updateRole(\n userId: string,\n workspaceId: string,\n memberId: string,\n role: WorkspaceRole\n ): Promise<void> {\n await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })\n const owners = await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n const before = await ownerIn(transaction, workspaceId)\n if (member.role === 'admin' && role !== 'admin') {\n if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()\n }\n await transaction\n .updateTable('workspaceMember')\n .set({ role })\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n if (role !== 'admin') await handOverOwnership(transaction, workspaceId, memberId)\n return [before, await ownerIn(transaction, workspaceId)]\n })\n seatsChanged(owners)\n },\n\n /** Deletes an empty workspace, with its members and invitations. */\n async delete(userId: string, workspaceId: string): Promise<void> {\n await requireAccess(userId, workspaceId, { workspace: ['delete'] })\n const owner = await database.transaction().execute(async (transaction) => {\n // Locked first, so a document created meanwhile waits and then finds no workspace.\n const workspace = await transaction\n .selectFrom('workspace')\n .select('ownerId')\n .where('id', '=', workspaceId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const documents = await transaction\n .selectFrom('document')\n .select(['deletedAt'])\n .where('workspaceId', '=', workspaceId)\n .execute()\n if (documents.some((document) => document.deletedAt === null)) {\n throw new WorkspaceNotEmptyError('documents')\n }\n if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')\n await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()\n return workspace.ownerId\n })\n seatsChanged([owner])\n },\n\n /**\n * Removes a member, or lets someone leave; the last administrator cannot go, and an owner who\n * goes leaves the workspace to the longest-standing other admin.\n */\n async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {\n if (memberId === userId) await membership(userId, workspaceId)\n else await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })\n const owners = await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n const before = await ownerIn(transaction, workspaceId)\n if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {\n throw new WorkspaceLastAdminError()\n }\n await transaction\n .deleteFrom('workspaceMember')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n await handOverOwnership(transaction, workspaceId, memberId)\n return [before, await ownerIn(transaction, workspaceId)]\n })\n seatsChanged(owners)\n },\n\n /** What a workspace invitation link offers, or null when the id is not one. */\n async preview(invitationId: string, token: string): Promise<InvitationPreview | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .innerJoin('workspace', 'workspace.id', 'workspaceInvitation.workspaceId')\n .select([\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.tokenHash',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.acceptedAt',\n 'workspaceInvitation.revokedAt',\n 'workspaceInvitation.invitedBy',\n 'workspace.name as workspaceName'\n ])\n .where('workspaceInvitation.id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (!invitationTokenIsActive(invitation, token)) throw new WorkspaceInvitationInvalidError()\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'workspace',\n workspaceName: invitation.workspaceName,\n role: invitation.role,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n },\n\n /**\n * Joins the workspace an invitation names, or returns null when the id is not a workspace\n * invitation. Someone already in it keeps the role they have.\n */\n async accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select([\n 'workspaceId',\n 'emailNormalized',\n 'role',\n 'tokenHash',\n 'expiresAt',\n 'acceptedAt',\n 'revokedAt'\n ])\n .where('id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, token)\n ) {\n throw new WorkspaceInvitationInvalidError()\n }\n const joined = await database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('workspaceMember')\n .values({\n workspaceId: invitation.workspaceId,\n userId: actor.userId,\n role: invitation.role\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'userId']).doNothing())\n .execute()\n await transaction\n .updateTable('workspaceInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n const member = await transaction\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', invitation.workspaceId)\n .where('userId', '=', actor.userId)\n .executeTakeFirstOrThrow()\n const owner = await ownerIn(transaction, invitation.workspaceId)\n return { joined: { workspaceId: invitation.workspaceId, role: member.role }, owner }\n })\n seatsChanged([joined.owner])\n return joined.joined\n }\n }\n}\n\nexport type WorkspaceMemberService = ReturnType<typeof createWorkspaceMemberService>\n","import type { CreateWorkspaceInput, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n findWorkspace,\n insertWorkspace,\n insertWorkspaceMember,\n listWorkspaces\n} from '#cloud/server/workspaces/repository'\nimport type { Kysely } from 'kysely'\n\nexport class WorkspaceSlugConflictError extends Error {\n constructor(readonly slug: string) {\n super(`Workspace slug is already in use: ${slug}`)\n this.name = 'WorkspaceSlugConflictError'\n }\n}\n\nfunction fallbackSlug(name: string): string {\n const normalized = name\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .slice(0, 48)\n return normalized.length >= 3 ? normalized : 'workspace'\n}\n\nfunction generatedSlug(name: string): string {\n return `${fallbackSlug(name)}-${crypto.randomUUID().slice(0, 8)}`\n}\n\nfunction personalWorkspaceName(name: string): string {\n const first = name.trim().split(/\\s+/)[0]\n return first ? `${first}’s workspace` : 'Personal workspace'\n}\n\nexport function createWorkspaceService(database: Kysely<CloudDatabase>) {\n return {\n list(userId: string): Promise<WorkspaceSummary[]> {\n return listWorkspaces(database, userId)\n },\n\n get(userId: string, workspaceId: string): Promise<WorkspaceSummary | undefined> {\n return findWorkspace(database, userId, workspaceId)\n },\n\n async create(userId: string, input: CreateWorkspaceInput): Promise<WorkspaceSummary> {\n const workspaceId = crypto.randomUUID()\n const slug = input.slug ?? generatedSlug(input.name)\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, userId, {\n ...input,\n id: workspaceId,\n slug\n })\n if (!inserted) throw new WorkspaceSlugConflictError(slug)\n await insertWorkspaceMember(transaction, workspaceId, userId, 'admin')\n })\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new Error('Created workspace could not be read')\n return workspace\n },\n\n /**\n * Gives an active account with no workspace one of its own, so it has somewhere to save. The\n * slug is fixed per person, so concurrent calls make one workspace and later calls none.\n */\n async ensurePersonal(user: { userId: string; name: string }): Promise<void> {\n if ((await listWorkspaces(database, user.userId)).length > 0) return\n const workspaceId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, user.userId, {\n id: workspaceId,\n name: personalWorkspaceName(user.name),\n slug: `personal-${user.userId}`\n })\n if (inserted) await insertWorkspaceMember(transaction, workspaceId, user.userId, 'admin')\n })\n }\n }\n}\n\nexport type WorkspaceService = ReturnType<typeof createWorkspaceService>\n","import {\n createWorkspaceSchema,\n createWorkspaceInvitationSchema,\n updateWorkspaceSchema,\n updateWorkspaceMemberSchema\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { InvitationLimitError } from '#cloud/server/invitations'\nimport {\n CLOUD_RATE_LIMITS,\n createRouteRateLimiter,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport {\n validatedJSON,\n workspaceInvitationParams,\n workspaceMemberParams,\n workspaceParams\n} from '#cloud/server/validation'\nimport {\n WorkspaceAlreadyMemberError,\n WorkspaceForbiddenError,\n WorkspaceLastAdminError,\n WorkspaceNotEmptyError,\n WorkspaceNotFoundError,\n type WorkspaceMemberService\n} from '#cloud/server/workspaces/members'\nimport type { WorkspaceService } from '#cloud/server/workspaces/service'\nimport { WorkspaceSlugConflictError } from '#cloud/server/workspaces/service'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type WorkspaceRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** Runs a membership action, answering its domain errors with their HTTP codes. */\nasync function memberRoute<T>(context: Context, action: () => Promise<T>): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n if (error instanceof WorkspaceNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof WorkspaceForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof WorkspaceLastAdminError) {\n return context.json({ error: { code: 'last_admin' as const } }, 409)\n }\n if (error instanceof WorkspaceNotEmptyError) {\n const code = error.reason === 'documents' ? 'not_empty' : 'cleanup_pending'\n return context.json({ error: { code } }, 409)\n }\n if (error instanceof WorkspaceAlreadyMemberError) {\n return context.json({ error: { code: 'already_member' as const } }, 409)\n }\n if (error instanceof InvitationLimitError) {\n return context.json({ error: { code: 'rate_limited' as const } }, 429)\n }\n throw error\n }\n}\n\nexport function createWorkspaceRoutes(\n service: WorkspaceService,\n members: WorkspaceMemberService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<WorkspaceRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.workspaceCreation,\n (context) => context.req.method !== 'POST'\n )\n )\n // Resending mails the invitation again, so it counts against the same budget as sending.\n router.use(\n '/:workspaceId/invitations/:invitationId/resend',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('workspaceId'),\n () => false\n )\n )\n router.use(\n '/:workspaceId/invitations',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('workspaceId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .get('/', async (context) => {\n const workspaces = await service.list(context.get('actor').userId)\n return context.json({ workspaces })\n })\n .post('/', validatedJSON(createWorkspaceSchema), async (context) => {\n try {\n const workspace = await service.create(\n context.get('actor').userId,\n context.req.valid('json')\n )\n return context.json({ workspace }, 201)\n } catch (error) {\n if (error instanceof WorkspaceSlugConflictError) {\n return context.json({ error: { code: 'slug_conflict' as const } }, 409)\n }\n throw error\n }\n })\n .get('/:workspaceId', workspaceParams, async (context) => {\n const workspace = await service.get(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ workspace })\n })\n .patch('/:workspaceId', workspaceParams, validatedJSON(updateWorkspaceSchema), (context) =>\n memberRoute(context, async () =>\n context.json({\n workspace: await members.rename(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json').name\n )\n })\n )\n )\n .delete('/:workspaceId', workspaceParams, (context) =>\n memberRoute(context, async () => {\n await members.delete(context.get('actor').userId, context.req.valid('param').workspaceId)\n return context.body(null, 204)\n })\n )\n .get('/:workspaceId/members', workspaceParams, (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.list(context.get('actor').userId, context.req.valid('param').workspaceId)\n )\n )\n )\n .post(\n '/:workspaceId/invitations',\n workspaceParams,\n validatedJSON(createWorkspaceInvitationSchema),\n (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.invite(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post('/:workspaceId/invitations/:invitationId/resend', workspaceInvitationParams, (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.resendInvitation(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').invitationId\n )\n )\n )\n )\n .delete('/:workspaceId/invitations/:invitationId', workspaceInvitationParams, (context) =>\n memberRoute(context, async () => {\n await members.revokeInvitation(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').invitationId\n )\n return context.body(null, 204)\n })\n )\n .patch(\n '/:workspaceId/members/:userId',\n workspaceMemberParams,\n validatedJSON(updateWorkspaceMemberSchema),\n (context) =>\n memberRoute(context, async () => {\n await members.updateRole(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').userId,\n context.req.valid('json').role\n )\n return context.body(null, 204)\n })\n )\n .delete('/:workspaceId/members/:userId', workspaceMemberParams, (context) =>\n memberRoute(context, async () => {\n await members.remove(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').userId\n )\n return context.body(null, 204)\n })\n )\n}\n","import { normalizeEnrollmentEmail } from '#cloud/admin/enrollment/service'\nimport type { CloudAccountDeletion } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { markPurged } from '#cloud/server/documents/purge'\nimport { handOverOwnership } from '#cloud/server/workspaces'\nimport { APIError } from 'better-auth'\nimport type { Kysely, Transaction } from 'kysely'\n\n/** Workspaces the account alone administers while others belong to them, which it must hand on. */\nexport class AccountDeletionBlockedError extends Error {\n constructor(readonly workspaces: CloudAccountDeletion['blockedBy']) {\n super('The account is the only administrator of workspaces with other members')\n this.name = 'AccountDeletionBlockedError'\n }\n}\n\n/** The account is the deployment's last administrator, so deleting it would lock the console. */\nexport class AccountLastAdministratorError extends Error {\n constructor() {\n super('Cannot delete the last deployment administrator')\n this.name = 'AccountLastAdministratorError'\n }\n}\n\n/**\n * Whether the account is an administrator of the deployment with no other active one, the\n * check the console makes before banning or demoting one (`src/admin/users/service.ts`).\n * Inside a transaction it locks the administrators' rows, so two of them can't both go at once.\n */\nasync function lastAdministrator(\n database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n userId: string,\n lock: boolean\n): Promise<boolean> {\n let query = database\n .selectFrom('user')\n .select(['id', 'banned'])\n .where('role', '=', 'admin')\n .orderBy('id')\n if (lock) query = query.forUpdate()\n const administrators = await query.execute()\n if (!administrators.some((row) => row.id === userId)) return false\n return !administrators.some((row) => row.id !== userId && row.banned !== true)\n}\n\ntype Membership = {\n workspaceId: string\n name: string\n role: string\n members: number\n admins: number\n}\n\n/** What happens to each workspace the account belongs to when it goes. */\nfunction classify(memberships: Membership[]) {\n const deletes: Membership[] = []\n const blockedBy: Membership[] = []\n const leaves: Membership[] = []\n for (const membership of memberships) {\n if (membership.members === 1) deletes.push(membership)\n else if (membership.role === 'admin' && membership.admins === 1) blockedBy.push(membership)\n else leaves.push(membership)\n }\n return { deletes, blockedBy, leaves }\n}\n\nasync function memberships(\n database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n userId: string\n): Promise<Membership[]> {\n return database\n .selectFrom('workspaceMember as own')\n .innerJoin('workspace', 'workspace.id', 'own.workspaceId')\n .innerJoin('workspaceMember as everyone', 'everyone.workspaceId', 'own.workspaceId')\n .select((expression) => [\n 'own.workspaceId',\n 'workspace.name',\n 'own.role',\n expression.fn.count<number>('everyone.userId').as('members'),\n expression.fn\n .count<number>('everyone.userId')\n .filterWhere('everyone.role', '=', 'admin')\n .as('admins')\n ])\n .where('own.userId', '=', userId)\n .groupBy(['own.workspaceId', 'workspace.name', 'own.role'])\n .orderBy('workspace.name')\n .orderBy('own.workspaceId')\n .execute()\n .then((rows) =>\n rows.map((row) => ({ ...row, members: Number(row.members), admins: Number(row.admins) }))\n )\n}\n\nconst workspaceSummary = (membership: Membership) => ({\n id: membership.workspaceId,\n name: membership.name\n})\n\n/**\n * Deleting an account: what it takes, and the Cloud side of taking it. Better Auth removes the\n * user with their sessions, sign-in methods, passkeys, and two-step secrets; this removes what\n * Cloud keeps about them. Workspaces only they belong to go with their documents, deleted\n * forever, which cleanup destroys once the deployment's grace passes; in workspaces others keep\n * they drop out, handing ownership, and so the plan the workspace draws on, to the\n * longest-standing other admin.\n */\nexport function createAccountDeletionService(database: Kysely<CloudDatabase>) {\n return {\n async plan(userId: string): Promise<CloudAccountDeletion> {\n const { deletes, blockedBy, leaves } = classify(await memberships(database, userId))\n const deleted = deletes.map((membership) => membership.workspaceId)\n const left = leaves.map((membership) => membership.workspaceId)\n const blocked = blockedBy.map((membership) => membership.workspaceId)\n // What the account can still download: everything in workspaces that go with it, and what\n // it created in workspaces it leaves, keeps an admin role in, or reaches only by a grant.\n const documents = await database\n .selectFrom('document')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select(['document.id', 'document.name', 'workspace.name as workspaceName'])\n .where('document.deletedAt', 'is', null)\n .where('document.disabledAt', 'is', null)\n .where((expression) =>\n expression.or([\n ...(deleted.length > 0 ? [expression('document.workspaceId', 'in', deleted)] : []),\n expression.and([\n expression('document.createdBy', '=', userId),\n expression.or([\n ...(left.length > 0 ? [expression('document.workspaceId', 'in', left)] : []),\n ...(blocked.length > 0 ? [expression('document.workspaceId', 'in', blocked)] : []),\n expression(\n 'document.id',\n 'in',\n expression\n .selectFrom('documentGrant')\n .select('documentGrant.documentId')\n .where('documentGrant.userId', '=', userId)\n .where('documentGrant.revokedAt', 'is', null)\n )\n ])\n ])\n ])\n )\n .orderBy('workspace.name')\n .orderBy('document.name')\n .orderBy('document.id')\n .execute()\n return {\n lastAdministrator: await lastAdministrator(database, userId, false),\n blockedBy: blockedBy.map(workspaceSummary),\n deletes: deletes.map(workspaceSummary),\n leaves: leaves.map(workspaceSummary),\n documents\n }\n },\n\n /**\n * Removes everything Cloud keeps about the account, in one transaction, or refuses with\n * `AccountDeletionBlockedError` and changes nothing. Its workspaces are locked first, so nobody\n * joins one, changes a role in one, or adds a document to one while it decides. `before` runs\n * first in that transaction, with the account's row locked and read again, as an\n * administrator's check and audit entry do; a throw from it changes nothing. The address is the\n * locked one, so a change that lands meanwhile cannot leave another address's request behind.\n */\n async remove(\n account: { id: string },\n options: {\n before?: (\n transaction: Transaction<CloudDatabase>,\n user: { id: string; email: string; name: string; role: string | null }\n ) => Promise<void>\n } = {}\n ): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n // The administrators' rows lock first, in one order for every deletion, so two\n // administrators deleting themselves at once wait for each other rather than deadlock.\n if (await lastAdministrator(transaction, account.id, true)) {\n throw new AccountLastAdministratorError()\n }\n const user = await transaction\n .selectFrom('user')\n .select(['id', 'email', 'name', 'role'])\n .where('id', '=', account.id)\n .forUpdate()\n .executeTakeFirstOrThrow()\n await options.before?.(transaction, user)\n const workspaceIds = await transaction\n .selectFrom('workspaceMember')\n .select('workspaceId')\n .where('userId', '=', user.id)\n .orderBy('workspaceId')\n .execute()\n for (const { workspaceId } of workspaceIds) {\n await transaction\n .selectFrom('workspace')\n .select('id')\n .where('id', '=', workspaceId)\n .forUpdate()\n .execute()\n }\n const { deletes, blockedBy, leaves } = classify(await memberships(transaction, user.id))\n if (blockedBy.length > 0) {\n throw new AccountDeletionBlockedError(blockedBy.map(workspaceSummary))\n }\n const now = new Date()\n for (const { workspaceId } of deletes) {\n await transaction\n .updateTable('document')\n .set({ deletedAt: now })\n .where('workspaceId', '=', workspaceId)\n .where('deletedAt', 'is', null)\n .execute()\n // Nobody is left to restore them, so they are deleted forever, Trash included: out of\n // sight now, and destroyed by cleanup once the deployment's grace passes.\n const documents = await transaction\n .selectFrom('document')\n .select('id')\n .where('workspaceId', '=', workspaceId)\n .where('purgedAt', 'is', null)\n .execute()\n await markPurged(\n transaction,\n documents.map((document) => document.id),\n null,\n now\n )\n await transaction\n .updateTable('workspaceInvitation')\n .set({ revokedAt: now })\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .execute()\n await transaction\n .deleteFrom('workspaceMember')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', user.id)\n .execute()\n // One with documents stays, member-less, until cleanup purges the last of them.\n await transaction\n .deleteFrom('workspace')\n .where('id', '=', workspaceId)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('document')\n .select('document.id')\n .whereRef('document.workspaceId', '=', 'workspace.id')\n )\n )\n )\n .execute()\n }\n for (const { workspaceId } of leaves) {\n await transaction\n .deleteFrom('workspaceMember')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', user.id)\n .execute()\n await handOverOwnership(transaction, workspaceId, user.id)\n }\n await transaction.deleteFrom('documentGrant').where('userId', '=', user.id).execute()\n for (const table of ['documentInvitation', 'workspaceInvitation'] as const) {\n await transaction\n .updateTable(table)\n .set({ revokedAt: now })\n .where('invitedBy', '=', user.id)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .execute()\n }\n await transaction.deleteFrom('invitationSend').where('senderId', '=', user.id).execute()\n for (const table of [\n 'accountEntitlement',\n 'termsAcceptance',\n 'userPicture',\n 'signIn',\n 'mfaAssurance',\n 'notificationSetting',\n 'commentRead',\n 'commentMention'\n ] as const) {\n await transaction.deleteFrom(table).where('userId', '=', user.id).execute()\n }\n // Comments the account wrote stay, nameless, in the threads others keep; what it was\n // emailed about them goes.\n await transaction\n .deleteFrom('commentEmail')\n .where((expression) =>\n expression.or([\n expression('senderId', '=', user.id),\n expression('recipientId', '=', user.id)\n ])\n )\n .execute()\n // Personal access tokens have no key to cascade from, since Cloud builds their table.\n await transaction.deleteFrom('apikey').where('referenceId', '=', user.id).execute()\n await transaction\n .deleteFrom('enrollment')\n .where('emailNormalized', '=', normalizeEnrollmentEmail(user.email))\n .execute()\n // The user row goes in the same transaction, with the sessions, sign-in methods, passkeys\n // and two-step secrets its keys cascade to, so a failure leaves the account whole and\n // signed in to try again. Better Auth's own deletes that follow then find nothing.\n await transaction.deleteFrom('user').where('id', '=', user.id).execute()\n })\n }\n }\n}\n\nexport type AccountDeletionService = ReturnType<typeof createAccountDeletionService>\n\n/**\n * Better Auth's `user.deleteUser` options: it checks the password, or that the session is fresh,\n * then runs `beforeDelete` outside any transaction of its own, so Cloud's may query. That\n * transaction deletes the user too; a refusal reaches the client as `account_sole_admin` or\n * `last_admin_required`.\n */\nexport function accountDeletionOptions(database: Kysely<CloudDatabase>) {\n const deletion = createAccountDeletionService(database)\n return {\n enabled: true,\n async beforeDelete(user: { id: string; email: string }) {\n try {\n await deletion.remove(user)\n } catch (error) {\n if (error instanceof AccountDeletionBlockedError) {\n throw APIError.from('CONFLICT', { code: 'ACCOUNT_SOLE_ADMIN', message: error.message })\n }\n if (error instanceof AccountLastAdministratorError) {\n throw APIError.from('CONFLICT', { code: 'LAST_ADMIN_REQUIRED', message: error.message })\n }\n throw error\n }\n }\n }\n}\n","import { CLOUD_SOCIAL_PROVIDERS, type CloudSocialProvider } from '#cloud/contract/account'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { BetterAuthOptions } from 'better-auth'\nimport { importPKCS8, SignJWT } from 'jose'\n\n/** The audience Apple's sign-in tokens carry, which the server also trusts as an origin. */\nexport const APPLE_AUDIENCE = 'https://appleid.apple.com'\nconst APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60\nasync function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {\n if (\n !config.appleClientId ||\n !config.appleTeamId ||\n !config.appleKeyId ||\n !config.applePrivateKey\n ) {\n throw new Error('Apple authentication is not configured')\n }\n const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\\\n', '\\n'), 'ES256')\n const issuedAt = Math.floor(Date.now() / 1000)\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })\n .setIssuer(config.appleTeamId)\n .setSubject(config.appleClientId)\n .setAudience(APPLE_AUDIENCE)\n .setIssuedAt(issuedAt)\n .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)\n .sign(privateKey)\n}\n\ntype ProviderOptions = NonNullable<BetterAuthOptions['socialProviders']>\n\n/**\n * Each provider as the server sets it up: its Better Auth options from the deployment's config, or\n * `undefined` where it is not configured, and whether its email may link to an existing account\n * whatever it says of that address (`trusted`). The one place a new provider's server side goes,\n * beside its config fields.\n */\nconst PROVIDERS: {\n [Provider in CloudSocialProvider]: {\n options: (config: CloudServerConfig) => ProviderOptions[Provider]\n trusted: boolean\n }\n} = {\n // Google only gives an address it has verified.\n google: {\n options: (config) =>\n config.googleClientId && config.googleClientSecret\n ? { clientId: config.googleClientId, clientSecret: config.googleClientSecret }\n : undefined,\n trusted: true\n },\n // Apple's addresses are verified, or relays it delivers itself. Its client secret is a token the\n // server signs, so it is made when Better Auth asks.\n apple: {\n options: (config) =>\n config.appleClientId\n ? async () => ({\n clientId: config.appleClientId ?? '',\n clientSecret: await generateAppleClientSecret(config),\n ...(config.appleAppBundleIdentifier && {\n appBundleIdentifier: config.appleAppBundleIdentifier\n })\n })\n : undefined,\n trusted: true\n },\n // GitHub can hand over an address it has not verified, such as an account's first listed email\n // when none is primary; untrusted, it links only when GitHub says the address is verified.\n github: {\n options: (config) =>\n config.githubClientId && config.githubClientSecret\n ? { clientId: config.githubClientId, clientSecret: config.githubClientSecret }\n : undefined,\n trusted: false\n }\n}\n\n/**\n * Providers whose sign-in links to the account with the same email even when it does not say the\n * address is verified. Better Auth links any other provider only when it does.\n */\nexport const TRUSTED_SOCIAL_PROVIDERS: CloudSocialProvider[] = CLOUD_SOCIAL_PROVIDERS.filter(\n (provider) => PROVIDERS[provider].trusted\n)\n\n/** The providers the deployment configures, in the order the editor shows them. */\nexport function configuredSocialProviders(config: CloudServerConfig): CloudSocialProvider[] {\n return CLOUD_SOCIAL_PROVIDERS.filter(\n (provider) => PROVIDERS[provider].options(config) !== undefined\n )\n}\n\n/** Better Auth's options for the providers the deployment configures. */\nexport function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {\n return Object.fromEntries(\n configuredSocialProviders(config).map((provider) => [\n provider,\n PROVIDERS[provider].options(config)\n ])\n )\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { APIError, type BetterAuthOptions } from 'better-auth'\nimport { getOAuthState } from 'better-auth/api'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { configuredSocialProviders } from './social-providers'\n\n/**\n * An administrator's removal of a Google or Apple identity is kept as one of Better Auth's\n * verification values: its database hooks read them inside the transaction that would create the\n * account, and the removal writes it in its own, so the two cannot come apart.\n */\nconst BLOCK_EXPIRES_AT = new Date(Date.UTC(9999, 11, 31))\nconst blockIdentifier = (userId: string, provider: string) =>\n `sign-in-method-block:${userId}:${provider}`\n\n/** Better Auth's store of keyed values, as its database hooks are handed it. */\nexport type SignInMethodBlockStore = {\n findVerificationValue(identifier: string): Promise<{ value: string } | null>\n deleteVerificationByIdentifier(identifier: string): Promise<void>\n}\n\n/**\n * The providers this server signs in with now, `credential` for a password. A method linked before\n * its provider was turned off stays on the account but no longer lets anyone in.\n */\nexport function signInProviders(config: CloudServerConfig): ReadonlySet<string> {\n const providers = new Set<string>(configuredSocialProviders(config))\n if (config.emailPasswordEnabled) providers.add('credential')\n return providers\n}\n\n/**\n * Whether `method` can come off an account holding `methods`: the account keeps at least one, and,\n * with `providers`, one whose provider is turned on. Taking away a provider that is off changes\n * nothing, so it can always go while another method remains.\n */\nexport function canRemoveSignInMethod(\n method: { id: string; providerId: string },\n methods: readonly { id: string; providerId: string }[],\n providers?: ReadonlySet<string>\n): boolean {\n const counts = (provider: string) => !providers || providers.has(provider)\n const others = methods.filter((candidate) => candidate.id !== method.id)\n if (others.length === 0) return false\n return !counts(method.providerId) || others.some((other) => counts(other.providerId))\n}\n\n/** The sign-in method a removal took away: its provider (`credential` for a password). */\nexport type RemovedSignInMethod = { provider: string }\n\n/**\n * Removes one of an account's sign-in methods, by its row. The account's row is locked first, so\n * its owner unlinking one while an administrator removes another cannot leave it with none. An\n * administrator's removal (`block`) also keeps that Google or Apple identity from linking itself\n * back by the account's email; `also` runs in the same transaction, as their audit entry does.\n * With `providers`, only methods whose provider is turned on count as a way still in.\n */\nexport async function removeSignInMethod(\n database: Kysely<CloudDatabase>,\n input: {\n userId: string\n methodId: string\n providers?: ReadonlySet<string>\n block?: boolean\n also?: (transaction: Transaction<CloudDatabase>, provider: string) => Promise<void>\n }\n): Promise<RemovedSignInMethod> {\n return database.transaction().execute(async (transaction) => {\n await transaction\n .selectFrom('user')\n .select('id')\n .where('id', '=', input.userId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const methods = await transaction\n .selectFrom('account')\n .select(['id', 'providerId', 'accountId'])\n .where('userId', '=', input.userId)\n .execute()\n const method = methods.find((candidate) => candidate.id === input.methodId)\n if (!method) {\n throw APIError.from('NOT_FOUND', { code: 'ACCOUNT_NOT_FOUND', message: 'No such method' })\n }\n if (!canRemoveSignInMethod(method, methods, input.providers)) {\n // Better Auth's own word, which the account routes already answer for.\n throw APIError.from('BAD_REQUEST', {\n code: 'FAILED_TO_UNLINK_LAST_ACCOUNT',\n message: 'An account keeps at least one way to sign in'\n })\n }\n await transaction.deleteFrom('account').where('id', '=', method.id).execute()\n if (input.block && method.providerId !== 'credential') {\n const identifier = blockIdentifier(input.userId, method.providerId)\n await transaction.deleteFrom('verification').where('identifier', '=', identifier).execute()\n await transaction\n .insertInto('verification')\n .values({\n id: crypto.randomUUID(),\n identifier,\n value: method.accountId,\n expiresAt: BLOCK_EXPIRES_AT,\n createdAt: new Date(),\n updatedAt: new Date()\n })\n .execute()\n }\n await input.also?.(transaction, method.providerId)\n return { provider: method.providerId }\n })\n}\n\n/**\n * Whether a sign-in may create `account`: not an identity an administrator removed from that\n * person, unless that person is linking it again from their own security page (`linkingUserId`,\n * which Better Auth carries from the request that started the link).\n */\nexport async function signInMethodAllowed(\n store: SignInMethodBlockStore,\n account: { userId: string; providerId: string; accountId: string },\n linkingUserId: () => Promise<string | null>\n): Promise<boolean> {\n const block = await store.findVerificationValue(\n blockIdentifier(account.userId, account.providerId)\n )\n if (block?.value !== account.accountId) return true\n return (await linkingUserId()) === account.userId\n}\n\n/** The person a provider callback links an identity to, when it is a link they started. */\nasync function linkingUserId(): Promise<string | null> {\n // Outside a provider callback there is no sign-in state, and nothing is being linked.\n const state = await getOAuthState().catch(() => null)\n return state?.link?.userId ?? null\n}\n\n/**\n * Refuses to create an identity an administrator removed, however a sign-in tries to, and lifts\n * the block once its owner has linked it again.\n */\nexport const signInMethodHooks: NonNullable<BetterAuthOptions['databaseHooks']> = {\n account: {\n create: {\n async before(account, context) {\n const store = context?.context.internalAdapter\n // `undefined` lets Better Auth create the account as it is; `false` refuses it.\n return store && !(await signInMethodAllowed(store, account, linkingUserId))\n ? false\n : undefined\n },\n async after(account, context) {\n const store = context?.context.internalAdapter\n if (store && (await linkingUserId()) === account.userId) {\n await store.deleteVerificationByIdentifier(\n blockIdentifier(account.userId, account.providerId)\n )\n }\n }\n }\n }\n}\n","import {\n isKnownAuthenticationProvider,\n type CloudAuthenticationMethod,\n type CloudSocialProvider\n} from '#cloud/contract/account'\nimport type { CloudServerConfig } from '#cloud/server/config'\n\nimport type { CloudAuthAdapter, SocialLinkStart } from './adapter'\nimport { canRemoveSignInMethod, signInProviders } from './methods'\nimport { configuredSocialProviders } from './social-providers'\n\nexport function createAccountAuthenticationService(\n auth: CloudAuthAdapter,\n config: CloudServerConfig\n) {\n const providers = signInProviders(config)\n return {\n async methods(headers: Headers) {\n const accounts = await auth.listAuthenticationMethods(headers)\n const methods = accounts.flatMap((account): CloudAuthenticationMethod[] => {\n if (!isKnownAuthenticationProvider(account.providerId)) return []\n return [\n {\n id: account.id,\n provider: account.providerId,\n createdAt: account.createdAt.toISOString(),\n canUnlink: canRemoveSignInMethod(account, accounts, providers)\n }\n ]\n })\n return {\n methods,\n availableSocialProviders: configuredSocialProviders(config).filter(\n (provider) => !methods.some((method) => method.provider === provider)\n )\n }\n },\n async changePassword(\n headers: Headers,\n input: { currentPassword: string; newPassword: string }\n ): Promise<void> {\n await auth.changePassword(headers, input)\n },\n async startSocialLink(\n headers: Headers,\n input: { provider: CloudSocialProvider; callbackURL: string }\n ): Promise<SocialLinkStart> {\n if (!configuredSocialProviders(config).includes(input.provider)) {\n throw new Error('Authentication provider is unavailable')\n }\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Authentication callback origin is unavailable')\n }\n return auth.startSocialLink(headers, { ...input, callbackURL: callback.href })\n },\n async unlink(headers: Headers, methodId: string): Promise<void> {\n await auth.unlinkAuthenticationMethod(headers, methodId)\n },\n /** Asks for a new address; the link that confirms it comes back to this server's pages. */\n async changeEmail(\n headers: Headers,\n input: { newEmail: string; callbackURL: string }\n ): Promise<void> {\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Email change callback origin is unavailable')\n }\n await auth.changeEmail(headers, { ...input, callbackURL: callback.href })\n }\n }\n}\n\nexport type AccountAuthenticationService = ReturnType<typeof createAccountAuthenticationService>\n","import type * as BetterAuthEndpoints from 'better-auth/api'\n\n/** Where Better Auth answers under the Cloud server. */\nexport const AUTH_BASE_PATH = '/api/auth'\n\n/** The path an endpoint declares, whether the library exports it built or as a factory. */\ntype PathOf<Endpoint> = Endpoint extends { path: infer Path extends string }\n ? Path\n : Endpoint extends (...args: never) => { path: infer Path extends string }\n ? Path\n : never\ntype CorePaths<Names extends keyof typeof BetterAuthEndpoints> = {\n readonly [Name in Names]: PathOf<(typeof BetterAuthEndpoints)[Name]>\n}\n\n/**\n * The core endpoints whose paths Better Auth's own options need before it is built: rate limits,\n * captcha, disabled paths, and the hooks that record sign-ins. Plugin endpoints come from the plugin objects and\n * the rest from `auth.api`; these few are written out, and the type check holds each to the path\n * the library declares, so a renamed endpoint fails to compile.\n */\nexport const CORE_AUTH_PATHS: CorePaths<\n | 'callbackOAuth'\n | 'deleteUser'\n | 'deleteUserCallback'\n | 'linkSocialAccount'\n | 'requestPasswordReset'\n | 'sendVerificationEmail'\n | 'signInEmail'\n | 'signUpEmail'\n | 'unlinkAccount'\n | 'verifyEmail'\n> = {\n callbackOAuth: '/callback/:id',\n deleteUser: '/delete-user',\n deleteUserCallback: '/delete-user/callback',\n linkSocialAccount: '/link-social',\n unlinkAccount: '/unlink-account',\n requestPasswordReset: '/request-password-reset',\n sendVerificationEmail: '/send-verification-email',\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n verifyEmail: '/verify-email'\n}\n\n/**\n * Whether `path`, as a hook context or request has it, is the endpoint at `endpoint`. Hooks see the\n * declared pattern or the concrete path, so a `:param` segment matches any one segment.\n */\nexport function isAuthEndpoint(path: string | undefined, endpoint: string): boolean {\n if (!path) return false\n const actual = path.split('/')\n const expected = endpoint.split('/')\n return (\n actual.length === expected.length &&\n expected.every((segment, index) =>\n segment.startsWith(':') ? Boolean(actual[index]) : segment === actual[index]\n )\n )\n}\n\n/** The path a request for the endpoint at `endpoint` arrives at on the Cloud server. */\nexport function authRequestPath(endpoint: string): string {\n return `${AUTH_BASE_PATH}${endpoint}`\n}\n","import Bowser from 'bowser'\nimport { compact } from 'es-toolkit'\n\n/** The browser and system a user agent names, as words for a person: `Chrome 141`, `macOS`. */\nexport function describeUserAgent(userAgent: string | null | undefined): {\n browser: string | null\n system: string | null\n} {\n if (!userAgent) return { browser: null, system: null }\n const { browser, os } = Bowser.parse(userAgent)\n const version = browser.version?.split('.', 1)[0]\n return {\n browser: browser.name ? compact([browser.name, version]).join(' ') : null,\n system: os.name || null\n }\n}\n","import {\n isKnownSocialProvider,\n type CloudAccountSession,\n type CloudSignIn,\n type CloudSignInMethod\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport type { BetterAuthPlugin } from 'better-auth'\nimport { createAuthMiddleware, isAPIError } from 'better-auth/api'\nimport type { Kysely } from 'kysely'\n\nimport type { AuthenticationEmailService } from './email'\nimport { CORE_AUTH_PATHS, isAuthEndpoint } from './endpoints'\nimport { describeUserAgent } from './user-agent'\n\n/** The newest sign-ins an account's history shows. */\nconst SIGN_IN_HISTORY_LIMIT = 50\n\ntype Endpoint = { path: string }\n\n/** The plugin endpoints that sign someone in, as the server's plugins declare them. */\nexport type SignInPluginEndpoints = {\n twoStep: { verifyTOTP: Endpoint; verifyBackupCode: Endpoint }\n passkeys: { verifyPasskeyAuthentication: Endpoint; verifyPasskeyRegistration: Endpoint }\n devices: { deviceToken: Endpoint }\n}\n\n/** The Better Auth endpoints that sign someone in, and the method each one is. */\nexport type SignInEndpoints = readonly (readonly [path: string, method: CloudSignInMethod])[]\n\n/** The sign-in endpoints of the core and of the server's plugins, from their own paths. */\nexport function signInEndpoints(plugins: SignInPluginEndpoints): SignInEndpoints {\n return [\n [CORE_AUTH_PATHS.signInEmail, 'password'],\n [plugins.passkeys.verifyPasskeyAuthentication.path, 'passkey'],\n [plugins.twoStep.verifyTOTP.path, 'two-step'],\n [plugins.twoStep.verifyBackupCode.path, 'two-step'],\n [CORE_AUTH_PATHS.verifyEmail, 'email-link'],\n [plugins.devices.deviceToken.path, 'desktop']\n ]\n}\n\n/**\n * How an endpoint signed someone in, or null when it signs nobody in, such as one that refreshes\n * a session. A provider's callback names the provider, as Better Auth's own `lastLoginMethod`\n * reads it.\n */\nexport function signInMethod(\n endpoint: { path?: string; params?: Record<string, string | undefined> },\n methods: SignInEndpoints\n): CloudSignInMethod | null {\n if (isAuthEndpoint(endpoint.path, CORE_AUTH_PATHS.callbackOAuth)) {\n const provider = endpoint.params?.id\n return provider && isKnownSocialProvider(provider) ? provider : 'other'\n }\n return methods.find(([path]) => isAuthEndpoint(endpoint.path, path))?.[1] ?? null\n}\n\n/**\n * Where an account signs in from. Each new session is written down with how it was made, so the\n * account's owner can read its sign-ins and sessions, and a sign-in from an address the account\n * never used before is told to its email; the first sign-in an account makes is not.\n */\nexport function createSignInActivity(\n database: Kysely<CloudDatabase>,\n email?: AuthenticationEmailService\n) {\n return {\n /** Writes down a session an endpoint just issued, and mails a sign-in from a new address. */\n async record(\n issued: {\n session: {\n id: string\n userId: string\n ipAddress?: string | null\n userAgent?: string | null\n }\n user: { email: string; name: string }\n },\n method: CloudSignInMethod\n ): Promise<void> {\n const { session, user } = issued\n // Confirming a new email address issues the session it was confirmed in again.\n const recorded = await database\n .selectFrom('signIn')\n .select('id')\n .where('sessionId', '=', session.id)\n .executeTakeFirst()\n if (recorded) return\n const ipAddress = session.ipAddress || null\n const [known, earlier] = await Promise.all([\n ipAddress\n ? database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .where('ipAddress', '=', ipAddress)\n .executeTakeFirst()\n : undefined,\n database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .executeTakeFirst()\n ])\n const id = crypto.randomUUID()\n const signedInAt = new Date()\n await database\n .insertInto('signIn')\n .values({\n id,\n userId: session.userId,\n sessionId: session.id,\n method,\n ipAddress,\n userAgent: session.userAgent || null,\n createdAt: signedInAt\n })\n .execute()\n if (!email || !earlier || known || !ipAddress) return\n await email.sendNewSignIn({\n email: user.email,\n name: user.name,\n signInId: id,\n signedInAt,\n ipAddress,\n ...describeUserAgent(session.userAgent),\n desktop: method === 'desktop'\n })\n },\n\n /** The account's sessions that have not expired, newest activity first. */\n async sessions(userId: string, currentSessionId: string): Promise<CloudAccountSession[]> {\n const rows = await database\n .selectFrom('session')\n .leftJoin('signIn', 'signIn.sessionId', 'session.id')\n .select([\n 'session.id',\n 'session.ipAddress',\n 'session.userAgent',\n 'session.createdAt',\n 'session.updatedAt',\n 'session.expiresAt',\n 'signIn.method'\n ])\n .where('session.userId', '=', userId)\n .where('session.expiresAt', '>', new Date())\n .orderBy('session.updatedAt', 'desc')\n .execute()\n return rows.map((row) => ({\n id: row.id,\n current: row.id === currentSessionId,\n method: row.method ?? null,\n ipAddress: row.ipAddress || null,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? '',\n lastActiveAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }))\n },\n\n async signIns(userId: string, limit = SIGN_IN_HISTORY_LIMIT): Promise<CloudSignIn[]> {\n const rows = await database\n .selectFrom('signIn')\n .select(['id', 'method', 'ipAddress', 'userAgent', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt', 'desc')\n .limit(limit)\n .execute()\n return rows.map((row) => ({\n id: row.id,\n method: row.method,\n ipAddress: row.ipAddress,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? ''\n }))\n }\n }\n}\n\nexport type SignInActivity = ReturnType<typeof createSignInActivity>\n\n/**\n * Better Auth's side of account activity. After an endpoint issues a session, Better Auth hands\n * it to hooks as `newSession`; two-step sign-in clears it until the second step, so only\n * sessions someone can use are written down. Adding a passkey is told to its owner.\n */\nexport function accountActivity(\n activity: SignInActivity,\n plugins: SignInPluginEndpoints,\n onPasskeyAdded: (user: { id: string; email: string; name: string }) => Promise<void>\n): BetterAuthPlugin {\n const methods = signInEndpoints(plugins)\n return {\n id: 'openpencil-account-activity',\n hooks: {\n after: [\n {\n matcher: (context) => signInMethod(context, methods) !== null,\n handler: createAuthMiddleware(async (context) => {\n const issued = context.context.newSession\n const method = signInMethod(context, methods)\n if (issued && method) await activity.record(issued, method)\n })\n },\n {\n matcher: (context) =>\n isAuthEndpoint(context.path, plugins.passkeys.verifyPasskeyRegistration.path),\n handler: createAuthMiddleware(async (context) => {\n const user = context.context.session?.user\n if (user && !isAPIError(context.context.returned)) await onPasskeyAdded(user)\n })\n }\n ]\n }\n }\n}\n","import type { EmailLocale, TwoStepChange } from '#cloud/email'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport type { Transaction } from 'kysely'\n\nexport type AuthenticationEmailService = {\n sendVerification(input: {\n email: string\n name: string\n url: string\n token: string\n purpose?: 'account' | 'change'\n /** The account's own language, or null for none; nothing is looked up, as sign-up needs. */\n locale?: EmailLocale | null\n }): Promise<void>\n sendPasswordReset(input: {\n email: string\n name: string\n url: string\n token: string\n }): Promise<void>\n sendPasswordChanged(input: {\n email: string\n name: string\n userId: string\n url: string\n }): Promise<void>\n /** Tells the address being replaced which address is taking over, before it confirms. */\n sendEmailChangeRequested(input: {\n email: string\n name: string\n userId: string\n newEmail: string\n }): Promise<void>\n sendNewSignIn(input: {\n email: string\n name: string\n signInId: string\n signedInAt: Date\n ipAddress: string | null\n browser: string | null\n system: string | null\n desktop: boolean\n }): Promise<void>\n sendTwoStepChanged(\n input: {\n email: string\n name: string\n userId: string\n change: TwoStepChange\n /** For a removed sign-in method, which one. */\n method?: string\n },\n transaction?: Transaction<CloudDatabase>\n ): Promise<void>\n}\n\nfunction tokenHash(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function createAuthenticationEmailService(\n email: TransactionalEmailService,\n publicURL: string\n): AuthenticationEmailService {\n return {\n async sendVerification(input) {\n await email.enqueue({\n idempotencyKey: `email-verification/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'email-verification',\n recipientEmail: input.email,\n recipientLocale: input.locale ?? null,\n payload: { name: input.name, actionURL: input.url, purpose: input.purpose }\n })\n },\n async sendPasswordReset(input) {\n await email.enqueue({\n idempotencyKey: `password-reset/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'password-reset',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: input.url }\n })\n },\n async sendPasswordChanged(input) {\n await email.enqueue({\n idempotencyKey: `password-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'password-changed',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', publicURL).href }\n })\n },\n async sendEmailChangeRequested(input) {\n await email.enqueue({\n idempotencyKey: `email-change-requested/${input.userId}/${crypto.randomUUID()}`,\n kind: 'email-change-requested',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n newEmail: input.newEmail,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n async sendNewSignIn(input) {\n await email.enqueue({\n idempotencyKey: `new-sign-in/${input.signInId}`,\n kind: 'new-sign-in',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n signedInAt: input.signedInAt.toISOString(),\n ipAddress: input.ipAddress,\n browser: input.browser,\n system: input.system,\n desktop: input.desktop,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n // Queued in the transaction that made the change, so the change and its notice commit together.\n async sendTwoStepChanged(input, transaction) {\n await email.enqueue(\n {\n idempotencyKey: `two-step-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'two-step-changed',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n change: input.change,\n ...(input.method && { method: input.method }),\n actionURL: new URL('/account/security', publicURL).href\n }\n },\n transaction\n )\n }\n }\n}\n","import type { CloudMFAStatus } from '#cloud/server/auth/adapter'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase, MFAAssuranceMethod } from '#cloud/server/db'\nimport { APIError } from 'better-auth'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport { authRequestPath } from './endpoints'\n\nconst ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000\n\nexport function createMFAAssuranceService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n return {\n async record(input: {\n sessionId: string\n userId: string\n method: MFAAssuranceMethod\n }): Promise<void> {\n await database\n .insertInto('mfaAssurance')\n .values({ ...input, verifiedAt: new Date() })\n .onConflict((conflict) =>\n conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })\n )\n .execute()\n },\n /**\n * Whether a session may act as its account. One whose account has an authenticator or a\n * passkey must have proved it, at sign-in or since; a sign-in through a linked account such\n * as Google never asks for it. Unlike `status().assured`, the proof does not age.\n */\n async confirmed(input: {\n sessionId: string\n userId: string\n twoFactorEnabled: boolean\n }): Promise<boolean> {\n const row = await database\n .selectNoFrom((expression) => [\n expression\n .exists(\n expression\n .selectFrom('mfaAssurance')\n .select('mfaAssurance.sessionId')\n .where('mfaAssurance.sessionId', '=', input.sessionId)\n .where('mfaAssurance.userId', '=', input.userId)\n )\n .as('assured'),\n expression\n .exists(\n expression\n .selectFrom('passkey')\n .select('passkey.id')\n .where('passkey.userId', '=', input.userId)\n )\n .as('passkey')\n ])\n .executeTakeFirstOrThrow()\n if (row.assured) return true\n return !input.twoFactorEnabled && !row.passkey\n },\n async status(input: {\n sessionId: string\n userId: string\n deploymentRole?: 'user' | 'admin'\n twoFactorEnabled: boolean\n passkeyCount: number\n }): Promise<CloudMFAStatus> {\n const assurance = await database\n .selectFrom('mfaAssurance')\n .select('verifiedAt')\n .where('sessionId', '=', input.sessionId)\n .where('userId', '=', input.userId)\n .executeTakeFirst()\n const assured = Boolean(\n assurance && new Date(assurance.verifiedAt).getTime() > Date.now() - ASSURANCE_MAX_AGE_MS\n )\n return {\n required: config.deploymentAdminMFARequired && input.deploymentRole === 'admin' && !assured,\n enabled: input.twoFactorEnabled || input.passkeyCount > 0,\n totpEnabled: input.twoFactorEnabled,\n assured,\n totpAvailable: config.totpEnabled,\n passkeysAvailable: config.passkeysEnabled,\n recoveryCodesAvailable: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n }\n}\n\nexport type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>\n\n/**\n * Records the second step a response just signed in with, against the session it started; false\n * when it started none.\n */\nexport async function recordResponseAssurance(\n response: Response,\n method: MFAAssuranceMethod,\n database: Kysely<CloudDatabase>,\n assurance: MFAAssuranceService\n): Promise<boolean> {\n const signedToken = response.headers.get('set-auth-token')\n const token = signedToken?.split('.', 1)[0]\n if (!token) return false\n const session = await database\n .selectFrom('session')\n .select(['id', 'userId'])\n .where('token', '=', token)\n .executeTakeFirst()\n if (!session) return false\n await assurance.record({ sessionId: session.id, userId: session.userId, method })\n return true\n}\n\nconst deviceTokenSchema = v.pipe(v.string(), v.parseJson(), v.object({ access_token: v.string() }))\n\n/** Records a desktop app's new session from a device sign-in, whose approval proved the step. */\nexport async function recordDeviceAssurance(\n response: Response,\n database: Kysely<CloudDatabase>,\n assurance: MFAAssuranceService\n): Promise<void> {\n const body = v.safeParse(deviceTokenSchema, await response.clone().text())\n if (!body.success) return\n const session = await database\n .selectFrom('session')\n .select(['id', 'userId'])\n .where('token', '=', body.output.access_token)\n .executeTakeFirst()\n if (session) {\n await assurance.record({ sessionId: session.id, userId: session.userId, method: 'device' })\n }\n}\n\n/** The auth endpoints whose success proves a second step, by their request paths. */\nexport type ProofPaths = {\n totp: string\n recoveryCode: string\n passkeySignIn: string\n passkeyRegistration: string\n deviceToken: string\n}\n\n/**\n * Records what a successful auth response proved. Signing in with a code, a recovery code, or a\n * passkey proves it for the session it starts; a device sign-in proves it for the app's session,\n * since only a proved session may approve one; registering a passkey proves it for the session\n * that added it, maybe the account's first second step, so that session is not then held.\n */\nexport function createProofRecorder(\n database: Kysely<CloudDatabase>,\n assurance: MFAAssuranceService,\n paths: ProofPaths\n) {\n const signIns = new Map<string, MFAAssuranceMethod>([\n [paths.totp, 'totp'],\n [paths.recoveryCode, 'recovery-code'],\n [paths.passkeySignIn, 'passkey']\n ])\n return async (\n path: string,\n response: Response,\n /** The session the request came from, read only when the step is proved for it. */\n current: () => Promise<{ session: { id: string }; user: { id: string } } | null>\n ): Promise<void> => {\n const method = signIns.get(path)\n if (method) {\n const recorded = await recordResponseAssurance(response, method, database, assurance)\n // A code checked for a session whose account already has the step does not replace the\n // session, so it proves it for that one; a passkey sign-in always starts a session.\n const session = !recorded && method !== 'passkey' ? await current() : null\n if (session) {\n await assurance.record({ sessionId: session.session.id, userId: session.user.id, method })\n }\n } else if (path === paths.deviceToken)\n await recordDeviceAssurance(response, database, assurance)\n else if (path === paths.passkeyRegistration) {\n const session = await current()\n if (session) {\n await assurance.record({\n sessionId: session.session.id,\n userId: session.user.id,\n method: 'passkey'\n })\n }\n }\n }\n}\n\n/** Better Auth's words for a code that does not match. */\nconst WRONG_CODES = new Set(['INVALID_CODE', 'INVALID_TWO_FACTOR_CODE', 'INVALID_BACKUP_CODE'])\nconst authErrorSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.object({ code: v.optional(v.string()) })\n)\n\n/**\n * Checks a second-step code through the two-step plugin's own endpoint, and records the session's\n * assurance when it passes.\n */\nexport async function verifySecondFactor(\n auth: { handler(request: Request): Promise<Response> },\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n assurance: MFAAssuranceService,\n headers: Headers,\n code: string,\n method: 'totp' | 'recovery-code',\n /** The two-step plugin's endpoint that checks this kind of code. */\n endpoint: { path: string },\n /** The session the code is checked for, which proves the step when it is not replaced. */\n current: { id: string; userId: string } | null\n): Promise<Response> {\n const response = await auth.handler(\n new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {\n method: 'POST',\n headers: new Headers({\n ...Object.fromEntries(headers),\n 'Content-Type': 'application/json'\n }),\n body: JSON.stringify({ code, trustDevice: false })\n })\n )\n if (!response.ok) {\n // A wrong code is the person's mistake, not a session to renew: say so, as a 400.\n const answer = v.safeParse(authErrorSchema, await response.clone().text())\n if (answer.success && WRONG_CODES.has(answer.output.code ?? '')) {\n throw new APIError('BAD_REQUEST', { code: 'INVALID_CODE' })\n }\n throw APIError.fromStatus(response.status as 401)\n }\n // A session whose account already has the step proves it without being replaced: it is the one\n // that proved it. Turning an authenticator on replaces the session, and the new one is recorded.\n const recorded = await recordResponseAssurance(response, method, database, assurance)\n if (!recorded && current) {\n await assurance.record({ sessionId: current.id, userId: current.userId, method })\n }\n return response\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\n/** Whether an account accepted the deployment's current terms, and recording that it did. */\nexport type TermsService = {\n /** The version accounts accept, when the deployment requires acceptance. */\n readonly requiredVersion: string | undefined\n /** True when nothing is required, or the account accepted the current version. */\n hasAccepted(userId: string): Promise<boolean>\n /** Records acceptance of the current version; false when `version` is not the current one. */\n accept(userId: string, version: string): Promise<boolean>\n}\n\nexport function createTermsService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n): TermsService {\n const requiredVersion = config.legal?.requireAcceptance ? config.legal.termsVersion : undefined\n return {\n requiredVersion,\n async hasAccepted(userId) {\n if (!requiredVersion) return true\n const row = await database\n .selectFrom('termsAcceptance')\n .select('userId')\n .where('userId', '=', userId)\n .where('version', '=', requiredVersion)\n .executeTakeFirst()\n return row !== undefined\n },\n async accept(userId, version) {\n if (!requiredVersion || version !== requiredVersion) return false\n await database\n .insertInto('termsAcceptance')\n .values({ userId, version, acceptedAt: new Date() })\n .onConflict((conflict) => conflict.columns(['userId', 'version']).doNothing())\n .execute()\n return true\n }\n }\n}\n","import type { BetterAuthPlugin } from 'better-auth'\nimport { decodeJwt } from 'jose'\nimport * as v from 'valibot'\n\nimport type { UserPictureService } from './service'\n\n/** The providers whose ID token names the person's picture. */\nconst PICTURE_PROVIDERS = new Set(['google'])\nconst pictureClaimSchema = v.object({ picture: v.pipe(v.string(), v.url()) })\n\n/**\n * The picture a linked account's provider names in the ID token Better Auth keeps on its account\n * row, or null. The token came to Better Auth from the provider during its sign-in flow, which no\n * client can write to the row.\n */\nexport function providerPicture(account: { providerId: string; idToken?: string | null }) {\n if (!PICTURE_PROVIDERS.has(account.providerId) || !account.idToken) return null\n try {\n const claims = v.safeParse(pictureClaimSchema, decodeJwt(account.idToken))\n return claims.success ? claims.output.picture : null\n } catch {\n return null\n }\n}\n\n/**\n * Keeps the picture a Google account names, so pages show the server's copy and never load it\n * from Google. Better Auth writes the account's ID token when it is linked and at each sign-in\n * with it, so accounts made before the server kept pictures move over the next time they sign in\n * this way. Better Auth also takes an `image` on sign-up and user updates; none of those reach the\n * account, since the server writes the addresses of the pictures it keeps itself.\n */\nexport function providerPictures(pictures: UserPictureService): BetterAuthPlugin {\n const keep = async (account: { userId: string; providerId: string; idToken?: string | null }) => {\n const picture = providerPicture(account)\n if (picture) await pictures.copyFromProvider(account.userId, picture)\n }\n return {\n id: 'openpencil-provider-pictures',\n init: () => ({\n options: {\n databaseHooks: {\n user: {\n create: {\n before: async (user) => ({ data: { ...user, image: null } })\n },\n update: {\n // Better Auth merges what a hook returns into the update, so `image` is unset.\n before: async (user) =>\n user.image === undefined ? true : { data: { image: undefined } }\n }\n },\n account: {\n create: { after: keep },\n update: { after: keep }\n }\n }\n }\n })\n }\n}\n","import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'\nimport type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize } from 'image-size'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport { DEADLINE_MS } from '@open-pencil/std/timing'\n\n/** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */\nexport const PICTURE_PATH = '/api/pictures'\n/** The longest side a stored picture may have; pages send 256 pixels. */\nconst PICTURE_MAX_SIDE = 1024\n/** How many hex digits of the checksum name a picture in its address. */\nconst PICTURE_VERSION_LENGTH = 16\n/** How long a linked account's picture may take to fetch before sign-in goes on without it. */\nconst PROVIDER_PICTURE_TIMEOUT_MS = DEADLINE_MS.request\n/** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */\nconst PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']\nconst PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }\nconst userIdSchema = v.pipe(v.string(), v.uuid())\n\n/** The bytes are not a PNG or JPEG picture the server keeps. */\nexport class PictureInvalidError extends Error {\n constructor() {\n super('The picture must be a PNG or JPEG image of at most 1024 by 1024 pixels')\n this.name = 'PictureInvalidError'\n }\n}\n\n/** The format of a picture the server keeps, read from its bytes; anything else is null. */\nexport function pictureFormat(bytes: Uint8Array): UserPictureFormat | null {\n if (bytes.byteLength === 0 || bytes.byteLength > CLOUD_PICTURE_MAX_BYTES) return null\n try {\n const size = imageSize(bytes)\n const format = size.type ? PICTURE_FORMATS[size.type] : undefined\n if (!format || size.width < 1 || size.height < 1) return null\n if (size.width > PICTURE_MAX_SIDE || size.height > PICTURE_MAX_SIDE) return null\n return format\n } catch {\n return null\n }\n}\n\n/** Whether `url` is an HTTPS address on a host a linked account's picture comes from. */\nfunction providerPicture(url: URL): boolean {\n return (\n url.protocol === 'https:' &&\n PROVIDER_PICTURE_HOSTS.some(\n (host) => url.hostname === host || url.hostname.endsWith(`.${host}`)\n )\n )\n}\n\n/** Reads at most `limit` bytes of a response body, or null when it holds more. */\nasync function boundedBody(response: Response, limit: number): Promise<Uint8Array | null> {\n if (!response.body) return null\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n length += value.byteLength\n if (length > limit) {\n await reader.cancel()\n return null\n }\n chunks.push(value)\n }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return bytes\n}\n\ntype AccountPicture = { image: string | null; updatedAt: Date }\n\nfunction samePicture(current: AccountPicture | undefined, seen: AccountPicture | undefined) {\n return (\n current?.image === seen?.image && current?.updatedAt.getTime() === seen?.updatedAt.getTime()\n )\n}\n\nexport type UserPictureOptions = {\n publicURL: string\n /** Fetches a linked account's picture; tests pass their own. */\n fetch?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * The picture each account shows. The server keeps the bytes and serves them itself, so a page\n * that shows a person never asks another service for them; `user.image` holds their address.\n */\nexport function createUserPictures(database: Kysely<CloudDatabase>, options: UserPictureOptions) {\n const fetchPicture = options.fetch ?? ((url, init) => fetch(url, init))\n const origin = new URL(options.publicURL).origin\n\n function address(userId: string, checksum: string): string {\n return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`\n }\n\n /** The address `bytes` are served from as the account's picture. */\n function pictureAddress(userId: string, bytes: Uint8Array): string {\n return address(userId, bytesToHex(sha256(bytes)))\n }\n\n /** Whether `image` is a picture this server serves, rather than another service's. */\n function served(image: string): boolean {\n return image.startsWith(`${origin}${PICTURE_PATH}/`)\n }\n\n /**\n * Keeps `bytes` as the account's picture. A provider's picture is kept only while the account is\n * unchanged since `seen`, read before the picture was fetched: every upload and removal moves\n * `updatedAt`, so one made meanwhile stands, even one that left the image as it was. Returns\n * whether the picture was kept.\n */\n async function save(\n userId: string,\n bytes: Uint8Array,\n source: { from: 'upload' } | { from: 'provider'; seen: AccountPicture | undefined }\n ): Promise<boolean> {\n const format = pictureFormat(bytes)\n if (!format) throw new PictureInvalidError()\n const checksum = bytesToHex(sha256(bytes))\n const image = pictureAddress(userId, bytes)\n const createdAt = new Date()\n return database.transaction().execute(async (transaction) => {\n // Saves and removals lock the account first, so they take turns.\n const current = await transaction\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirst()\n if (source.from === 'provider' && !samePicture(current, source.seen)) return false\n await transaction\n .insertInto('userPicture')\n .values({ userId, bytes, format, checksum, source: source.from, createdAt })\n .onConflict((conflict) =>\n conflict\n .column('userId')\n .doUpdateSet({ bytes, format, checksum, source: source.from, createdAt })\n )\n .execute()\n await transaction\n .updateTable('user')\n .set({ image, updatedAt: createdAt })\n .where('id', '=', userId)\n .execute()\n return true\n })\n }\n\n async function remove(userId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n // The account first, in the same order saves lock, so the two never wait on each other.\n await transaction\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .forUpdate()\n .execute()\n await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n })\n }\n\n return {\n served,\n\n /** Keeps a picture the account's owner uploaded and shows it from now on. */\n async upload(userId: string, bytes: Uint8Array): Promise<string> {\n await save(userId, bytes, { from: 'upload' })\n return pictureAddress(userId, bytes)\n },\n\n /** Goes back to initials. */\n remove,\n\n /** The picture at `/api/pictures/:userId/:version`, or null for any other address. */\n async read(userId: string, version: string) {\n if (!v.is(userIdSchema, userId) || version.length !== PICTURE_VERSION_LENGTH) return null\n const picture = await database\n .selectFrom('userPicture')\n .select(['bytes', 'format', 'checksum'])\n .where('userId', '=', userId)\n .executeTakeFirst()\n return picture?.checksum.startsWith(version) ? picture : null\n },\n\n /**\n * Keeps the picture a linked account named in `image` and shows it instead, so pages never\n * load it from that service. A picture that cannot be fetched or is not one the server keeps\n * leaves initials in its place. An uploaded picture stays.\n */\n async copyFromProvider(userId: string, image: string): Promise<void> {\n if (served(image)) return\n // A picture the account already shows from this server, uploaded or kept before, stays.\n const current = await database\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .executeTakeFirst()\n if (current?.image && served(current.image)) return\n try {\n if (!providerPicture(new URL(image))) throw new PictureInvalidError()\n const response = await fetchPicture(image, {\n redirect: 'error',\n signal: AbortSignal.timeout(PROVIDER_PICTURE_TIMEOUT_MS)\n })\n const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null\n if (!bytes) throw new PictureInvalidError()\n await save(userId, bytes, { from: 'provider', seen: current })\n } catch (error) {\n logCloud('warn', 'Keeping a linked account picture failed', { error: loggedError(error) })\n await database\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .where('image', '=', image)\n .execute()\n }\n }\n }\n}\n\nexport type UserPictureService = ReturnType<typeof createUserPictures>\n","import { pictureParams } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { PICTURE_PATH, type UserPictureService } from './service'\n\n/**\n * Account pictures, for anyone with a picture's address: pages show people to those they share\n * documents and workspaces with, and the desktop app shows them from another origin.\n */\nexport function createPictureRoutes(pictures: UserPictureService) {\n return new Hono().get(`${PICTURE_PATH}/:userId/:version`, pictureParams, async (context) => {\n const { userId, version } = context.req.valid('param')\n const picture = await pictures.read(userId, version)\n if (!picture) return context.json({ error: { code: 'not_found' as const } }, 404)\n // The address changes with the picture, but a removed one must stop showing within a day.\n context.header('Cache-Control', 'public, max-age=86400')\n context.header('Content-Type', `image/${picture.format}`)\n context.header('X-Content-Type-Options', 'nosniff')\n context.header('Content-Security-Policy', \"default-src 'none'; sandbox\")\n context.header('Cross-Origin-Resource-Policy', 'cross-origin')\n return context.body(new Uint8Array(picture.bytes))\n })\n}\n","import type { EnrollmentService } from '#cloud/admin/enrollment/service'\nimport { CLOUD_ACCESS_TOKEN_PREFIX, type CloudAccessToken } from '#cloud/contract'\nimport type { TermsService } from '#cloud/server/account/terms'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\n/** The personal access token in `Authorization: Bearer`, when the header carries one of Cloud's. */\nexport function bearerAccessToken(headers: Headers): string | null {\n const key = headers.get('authorization')?.match(/^Bearer\\s+(\\S+)$/i)?.[1]\n return key?.startsWith(CLOUD_ACCESS_TOKEN_PREFIX) ? key : null\n}\n\n/**\n * The account a verified token belongs to, held to what a session would be: not banned, approved,\n * and with the current terms accepted.\n */\nexport async function accessTokenAccount(\n {\n database,\n config,\n enrollment,\n terms\n }: {\n database: Kysely<CloudDatabase>\n config: CloudServerConfig\n enrollment: EnrollmentService\n terms: TermsService\n },\n userId: string\n) {\n const user = await database\n .selectFrom('user')\n .select(['id', 'email', 'name', 'image', 'role', 'banned', 'banExpires'])\n .where('id', '=', userId)\n .executeTakeFirst()\n if (!user) return null\n const banExpires = user.banExpires ? new Date(user.banExpires).getTime() : null\n if (user.banned && (banExpires === null || banExpires > Date.now())) return null\n if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(user.email))) {\n return null\n }\n if (!(await terms.hasAccepted(user.id))) return null\n return user\n}\n\n/** A stored token as the account's token list shows it, without the secret. */\nexport const toAccessToken = (key: {\n id: string\n name: string | null\n start: string | null\n createdAt: Date\n expiresAt: Date | null\n lastRequest: Date | null\n}): CloudAccessToken => ({\n id: key.id,\n name: key.name ?? '',\n start: key.start,\n createdAt: new Date(key.createdAt).toISOString(),\n expiresAt: key.expiresAt ? new Date(key.expiresAt).toISOString() : null,\n lastUsedAt: key.lastRequest ? new Date(key.lastRequest).toISOString() : null\n})\n","import type { EnrollmentService } from '#cloud/admin/enrollment/service'\nimport { cloudLanguageTagSchema } from '#cloud/contract'\nimport { acceptedLocale, emailLocale, isEmailLocale, type EmailLocale } from '#cloud/email'\nimport { accountDeletionOptions } from '#cloud/server/account/deletion'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { BetterAuthOptions } from 'better-auth'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport type { AuthenticationEmailService } from './email'\n\n/** The language an account writes in, which Better Auth's types don't know it has. */\nfunction accountLocale(user: object): EmailLocale | null {\n return 'locale' in user && isEmailLocale(user.locale) ? user.locale : null\n}\n\n/** The language tag the app sent, if any, before it's matched to one Cloud writes in. */\nfunction languageTag(user: object): string | null {\n return 'locale' in user && typeof user.locale === 'string' ? user.locale : null\n}\n\n/**\n * Who may join and when an account counts as enrolled: addresses are verified before an account\n * asks for approval or binds an approved invitation, and a closed deployment creates no accounts.\n */\nexport function enrollmentOptions(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n enrollment: EnrollmentService,\n authenticationEmail: AuthenticationEmailService | undefined,\n emailChangeAvailable: boolean\n) {\n async function enroll(user: { id: string; email: string; name: string }) {\n if (config.enrollmentMode === 'approval') {\n await enrollment.request({ email: user.email, name: user.name })\n }\n await enrollment.bindApprovedUser(user.email, user.id)\n }\n\n return {\n emailVerification:\n config.emailPasswordEnabled && authenticationEmail\n ? {\n expiresIn: config.emailVerificationExpiresIn,\n sendOnSignUp: true,\n // Signing in unverified only says so; people ask for another link with Send again.\n sendOnSignIn: false,\n autoSignInAfterVerification: true,\n // A change of address sends the link to the new address as `user.email`, on the\n // account it already confirmed; a new account has not confirmed one yet. This runs\n // inside sign-up's transaction, so it must not query the database itself.\n sendVerificationEmail: ({ user, url, token }) =>\n authenticationEmail.sendVerification({\n email: user.email,\n name: user.name,\n url,\n token,\n purpose: user.emailVerified ? 'change' : 'account',\n // The account carries its language, so nothing is looked up in the transaction.\n locale: accountLocale(user)\n }),\n afterEmailVerification: async (user) => {\n await enrollment.followEmailChange(user.id, user.email)\n await enroll(user)\n }\n }\n : undefined,\n user: {\n additionalFields: {\n // The language Cloud writes to the account in: the app's, sent when signing up and\n // whenever the person changes it, as the nearest language Cloud has (the hooks below).\n locale: {\n type: 'string' as const,\n required: false,\n input: true,\n validator: { input: v.nullish(cloudLanguageTagSchema) }\n }\n },\n changeEmail: { enabled: emailChangeAvailable },\n deleteUser: accountDeletionOptions(database),\n validateUserInfo: ({ source }) => {\n if (source.action === 'create-user' && config.enrollmentMode === 'closed') {\n return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }\n }\n return undefined\n }\n },\n databaseHooks: {\n user: {\n create: {\n // The app's language, or for an account it didn't name one for, as one made through\n // Google or Apple, the browser's. A language Cloud doesn't write in reads English.\n before: async (user, context) => {\n const tag = languageTag(user)\n const locale = tag\n ? emailLocale([tag])\n : acceptedLocale(context?.headers?.get('accept-language'))\n return { data: { ...user, locale } }\n },\n after: async (user) => {\n if (user.emailVerified) await enroll(user)\n }\n },\n update: {\n // Whoever changes it, Cloud keeps the nearest language it writes in, or English.\n before: async (user) => {\n if (!('locale' in user)) return undefined\n const tag = languageTag(user)\n return { data: { ...user, locale: emailLocale(tag ? [tag] : []) } }\n }\n }\n }\n }\n } satisfies Pick<BetterAuthOptions, 'emailVerification' | 'user' | 'databaseHooks'>\n}\n","import { writeJSONLine } from '#cloud/server/logging'\nimport type { BetterAuthOptions } from 'better-auth'\n\n/** What the API-key plugin logs, as an error, for a token that is wrong, expired, or revoked. */\nconst REFUSED_TOKEN = 'Failed to validate API key'\n\n/**\n * Better Auth's log lines as Cloud's JSON lines. A refused personal access token is the caller's\n * mistake, which the request answers with 401, so it is not logged as the server's error; nor is\n * anything a log line's arguments carry beyond an error's name and message.\n */\nexport const betterAuthLogger: NonNullable<BetterAuthOptions['logger']> = {\n log(level, message, ...args) {\n if (level === 'debug' || message.startsWith(REFUSED_TOKEN)) return\n const error = args.find((arg): arg is Error => arg instanceof Error)\n writeJSONLine({\n level,\n message,\n source: 'better-auth',\n ...(error && { error: { name: error.name, message: error.message } })\n })\n }\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { BetterAuthOptions } from 'better-auth'\n\nimport type { AuthenticationEmailService } from './email'\n\n/**\n * Signing in with an email and password, when the deployment allows it: a verified address, the\n * configured password lengths, and mail about resets when the deployment sends email.\n */\nexport function passwordOptions(\n config: CloudServerConfig,\n authenticationEmail: AuthenticationEmailService | undefined\n): BetterAuthOptions['emailAndPassword'] {\n if (!config.emailPasswordEnabled) return undefined\n return {\n enabled: true,\n disableSignUp: !config.emailPasswordSignUpEnabled,\n requireEmailVerification: true,\n minPasswordLength: config.emailPasswordMinimumLength,\n maxPasswordLength: config.emailPasswordMaximumLength,\n autoSignIn: false,\n resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,\n revokeSessionsOnPasswordReset: true,\n sendResetPassword: authenticationEmail\n ? ({ user, url, token }) =>\n authenticationEmail.sendPasswordReset({\n email: user.email,\n name: user.name,\n url,\n token\n })\n : undefined,\n onPasswordReset: authenticationEmail\n ? ({ user }) =>\n authenticationEmail.sendPasswordChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n url: config.publicURL\n })\n : undefined\n }\n}\n","import type { deviceAuthorization } from 'better-auth/plugins'\n\nimport { CORE_AUTH_PATHS } from './endpoints'\n\ntype DeviceEndpoints = ReturnType<typeof deviceAuthorization>['endpoints']\n\n/**\n * Better Auth's request budgets, counted per client IP in the database: a general one, and tighter\n * ones for steps that send email, check passwords, or hand out desktop sign-in codes.\n */\nexport function authRateLimit(devices: DeviceEndpoints) {\n return {\n enabled: true,\n storage: 'database' as const,\n window: 60,\n max: 100,\n customRules: {\n [devices.deviceCode.path]: { window: 60, max: 10 },\n [devices.deviceToken.path]: { window: 60, max: 60 },\n // The plugin's own budget is 5 lookups per code lifetime (30 minutes), so reopening the\n // sign-in page a few times turned away every new code for half an hour.\n [devices.deviceVerify.path]: { window: 60, max: 20 },\n [devices.deviceApprove.path]: { window: 60, max: 10 },\n [devices.deviceDeny.path]: { window: 60, max: 10 },\n [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },\n [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }\n }\n }\n}\n","import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'\nimport {\n CLOUD_ACCESS_TOKEN_MAX_DAYS,\n CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH,\n CLOUD_ACCESS_TOKEN_PREFIX\n} from '#cloud/contract'\nimport { createTermsService } from '#cloud/server/account/terms'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createUserPictures, providerPictures } from '#cloud/server/pictures'\nimport { apiKey } from '@better-auth/api-key'\nimport { passkey } from '@better-auth/passkey'\nimport { APIError, betterAuth } from 'better-auth'\nimport { getMigrations } from 'better-auth/db/migration'\nimport {\n admin,\n bearer,\n captcha,\n deviceAuthorization,\n haveIBeenPwned,\n twoFactor\n} from 'better-auth/plugins'\nimport type { Kysely } from 'kysely'\n\nimport { accessTokenAccount, bearerAccessToken, toAccessToken } from './access-tokens'\nimport { accountActivity, createSignInActivity } from './activity'\nimport type { CloudAuthAdapter } from './adapter'\nimport type { AuthenticationEmailService } from './email'\nimport { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'\nimport { enrollmentOptions } from './enrollment'\nimport { betterAuthLogger } from './logger'\nimport { removeSignInMethod, signInMethodHooks, signInProviders } from './methods'\nimport { createMFAAssuranceService, createProofRecorder, verifySecondFactor } from './mfa-assurance'\nimport { passwordOptions } from './passwords'\nimport { authRateLimit } from './rate-limit'\nimport { APPLE_AUDIENCE, socialProviders, TRUSTED_SOCIAL_PROVIDERS } from './social-providers'\n\nconst BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'\nconst DAY_SECONDS = 24 * 60 * 60\nconst ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60\n\nexport type CloudAuthRuntimeOptions = {\n email?: AuthenticationEmailService\n runInBackground?: (promise: Promise<unknown>) => void\n /**\n * Whether Better Auth checks the database schema when it starts, off unless asked for. The check\n * runs in the background and nothing waits for it, so an adapter made briefly, as for one\n * request, for migrating, or in a test, would leave it querying a database being closed;\n * `migrateCloudDatabase` has already checked the recorded version. A server's long-lived\n * adapter turns it on.\n */\n validateSchema?: boolean\n}\n\nexport function createBetterAuthAdapter(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n enrollment: EnrollmentService = createEnrollmentService(database),\n runtime: CloudAuthRuntimeOptions = {}\n): CloudAuthAdapter {\n const authenticationEmail = runtime.email\n const assurance = createMFAAssuranceService(database, config)\n const terms = createTermsService(database, config)\n const activity = createSignInActivity(database, authenticationEmail)\n // A new address is confirmed through a link sent to it, so changing one needs email delivery.\n const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)\n const providers = signInProviders(config)\n // The plugins are built first, so the options below name their endpoints by the paths they declare.\n const twoStep = twoFactor({\n issuer: 'OpenPencil Cloud',\n trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,\n allowPasswordless: true,\n totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },\n backupCodeOptions: {\n disable: !config.totpEnabled || !config.recoveryCodesEnabled,\n storeBackupCodes: 'encrypted'\n }\n })\n const passkeys = passkey({\n rpID: new URL(config.publicURL).hostname,\n rpName: config.passkeyRPName,\n origin: new URL(config.publicURL).origin\n })\n const devices = deviceAuthorization({\n verificationUri: new URL('/auth/device', config.publicURL).href,\n validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')\n })\n const administration = admin()\n // Personal access tokens. Cloud reads them itself (`resolveAccessToken`), for the document API\n // alone, so they never become sessions; Cloud's own limiters count their requests.\n const accessTokens = apiKey({\n defaultPrefix: CLOUD_ACCESS_TOKEN_PREFIX,\n requireName: true,\n maximumNameLength: CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH,\n startingCharactersConfig: { charactersLength: CLOUD_ACCESS_TOKEN_PREFIX.length + 4 },\n keyExpiration: { minExpiresIn: 1, maxExpiresIn: CLOUD_ACCESS_TOKEN_MAX_DAYS },\n rateLimit: { enabled: false },\n enableSessionForAPIKeys: false\n })\n const joining = enrollmentOptions(\n config,\n database,\n enrollment,\n authenticationEmail,\n emailChangeAvailable\n )\n const auth = betterAuth({\n appName: 'OpenPencil Cloud',\n logger: betterAuthLogger,\n baseURL: config.publicURL,\n basePath: AUTH_BASE_PATH,\n // Clients never reach Better Auth's administration, which `/api/admin` replaces with its own\n // checks, nor the endpoints Cloud's account routes manage; the server still calls them itself.\n disabledPaths: [\n ...Object.values(administration.endpoints).map((endpoint) => endpoint.path),\n // Tokens are made, listed, and revoked through `/api/account/tokens`, with a fresh session.\n ...Object.values(accessTokens.endpoints).map((endpoint) => endpoint.path),\n passkeys.endpoints.deletePasskey.path,\n twoStep.endpoints.disableTwoFactor.path,\n // Accounts are deleted through `/api/account/delete`, closed to accounts awaiting approval.\n CORE_AUTH_PATHS.deleteUser,\n CORE_AUTH_PATHS.deleteUserCallback,\n // Linking and unlinking go through `/api/account/authentication`, with a fresh session.\n CORE_AUTH_PATHS.linkSocialAccount,\n CORE_AUTH_PATHS.unlinkAccount\n ],\n secret: config.authSecret,\n database: {\n db: database,\n type: 'postgres',\n casing: 'camel',\n transaction: true\n },\n account: {\n accountLinking: {\n enabled: true,\n disableImplicitLinking: false,\n trustedProviders: TRUSTED_SOCIAL_PROVIDERS,\n allowDifferentEmails: false,\n allowUnlinkingAll: false,\n requireLocalEmailVerified: true\n }\n },\n session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },\n advanced: {\n database: { generateId: 'uuid', validateSchema: runtime.validateSchema ?? false },\n ipAddress: {\n ipAddressHeaders: config.authTrustedIPHeaders,\n trustedProxies: config.authTrustedProxies\n },\n ...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})\n },\n rateLimit: authRateLimit(devices.endpoints),\n emailAndPassword: passwordOptions(config, authenticationEmail),\n ...joining,\n plugins: [\n ...(config.captchaProvider && config.captchaSecretKey\n ? [\n captcha({\n provider: config.captchaProvider,\n secretKey: config.captchaSecretKey,\n allowedHostnames: config.captchaAllowedHostnames,\n endpoints: [\n CORE_AUTH_PATHS.signUpEmail,\n CORE_AUTH_PATHS.signInEmail,\n CORE_AUTH_PATHS.requestPasswordReset\n ]\n })\n ]\n : []),\n ...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),\n twoStep,\n passkeys,\n administration,\n // Device authorization returns opaque database session tokens, not signed cookies.\n bearer(),\n devices,\n // After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.\n accountActivity(\n activity,\n { twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },\n (user) => notifyTwoStep(user, 'passkey-added')\n ),\n providerPictures(createUserPictures(database, { publicURL: config.publicURL })),\n accessTokens\n ],\n socialProviders: socialProviders(config),\n databaseHooks: { ...joining.databaseHooks, ...signInMethodHooks },\n trustedOrigins: [\n config.publicURL,\n ...config.trustedOrigins,\n ...(config.appleClientId ? [APPLE_AUDIENCE] : [])\n ]\n })\n\n // Administrators are granted only through the `admin` command or by another administrator.\n const deploymentRole = (user: { id: string; role?: string | null }) =>\n user.role === 'admin' ? ('admin' as const) : ('user' as const)\n\n /** The signed-in person, and the session they are signed in with. */\n async function signedIn(headers: Headers) {\n const session = await auth.api.getSession({ headers })\n if (!session) return null\n return {\n identity: {\n userId: session.user.id,\n email: session.user.email,\n name: session.user.name,\n image: session.user.image ?? null,\n deploymentRole: deploymentRole(session.user)\n },\n sessionId: session.session.id,\n twoFactorEnabled: 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true\n }\n }\n\n const resolveIdentity = async (headers: Headers) => (await signedIn(headers))?.identity ?? null\n\n async function twoStepConfirmed(headers: Headers): Promise<boolean> {\n const signed = await signedIn(headers)\n if (!signed) return false\n return assurance.confirmed({\n sessionId: signed.sessionId,\n userId: signed.identity.userId,\n twoFactorEnabled: signed.twoFactorEnabled\n })\n }\n\n /** The signed-in person, read past the cookie cache, for changes about their own account. */\n const currentSession = (headers: Headers) =>\n auth.api.getSession({ headers, query: { disableCookieCache: true } })\n\n /** The current session when it signed in recently enough to change how the account is reached. */\n async function freshSession(headers: Headers) {\n const session = await currentSession(headers)\n const createdAt = session?.session.createdAt\n if (\n !session ||\n !createdAt ||\n Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000\n ) {\n throw APIError.from('FORBIDDEN', {\n code: 'SESSION_NOT_FRESH',\n message: 'Session is not fresh'\n })\n }\n return session\n }\n\n async function notifyTwoStep(\n user: { id: string; email: string; name: string },\n change: Parameters<AuthenticationEmailService['sendTwoStepChanged']>[0]['change']\n ): Promise<void> {\n await authenticationEmail?.sendTwoStepChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n change\n })\n }\n\n /**\n * The signed-in person while their account may use the server: not while it awaits approval, nor\n * before it accepted the deployment's current terms when those are required.\n */\n async function resolveSession(headers: Headers) {\n const identity = await resolveAccountSession(headers)\n if (!identity || !(await terms.hasAccepted(identity.userId))) return null\n return identity\n }\n\n /**\n * The signed-in person while their account is approved and their session proved its second step,\n * before or after accepting the terms.\n */\n async function resolveAccountSession(headers: Headers) {\n const signed = await signedIn(headers)\n if (!signed) return null\n const { identity } = signed\n if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {\n return null\n }\n const confirmed = await assurance.confirmed({\n sessionId: signed.sessionId,\n userId: identity.userId,\n twoFactorEnabled: signed.twoFactorEnabled\n })\n return confirmed ? identity : null\n }\n\n /** The account a personal access token in `Authorization: Bearer` stands for. */\n async function resolveAccessToken(headers: Headers) {\n const key = bearerAccessToken(headers)\n if (!key) return null\n const verified = await auth.api.verifyApiKey({ body: { key } })\n if (!verified.valid || !verified.key) return null\n const context = { database, config, enrollment, terms }\n const user = await accessTokenAccount(context, verified.key.referenceId)\n if (!user) return null\n return {\n userId: user.id,\n email: user.email,\n name: user.name,\n deploymentRole: deploymentRole(user),\n credential: 'token' as const\n }\n }\n\n /**\n * The endpoints that read or change an account, which only an account that may use the server\n * reaches; one awaiting approval still signs in and out. Better Auth checks the session inside\n * most of these endpoints rather than declaring it, so they are listed by their own objects.\n */\n const activeAccountPaths = new Set(\n [\n // The desktop session it grants counts as two-step proved; only a proved session may grant one.\n auth.api.deviceApprove,\n auth.api.deviceDeny,\n auth.api.generatePasskeyRegistrationOptions,\n auth.api.listPasskeys,\n auth.api.updatePasskey,\n auth.api.verifyPasskeyRegistration,\n auth.api.enableTwoFactor,\n auth.api.generateBackupCodes,\n auth.api.getTOTPURI,\n auth.api.accountInfo,\n auth.api.changeEmail,\n auth.api.changePassword,\n auth.api.deleteUser,\n auth.api.getAccessToken,\n auth.api.linkSocialAccount,\n auth.api.listUserAccounts,\n auth.api.listSessions,\n auth.api.refreshToken,\n auth.api.revokeOtherSessions,\n auth.api.revokeSession,\n auth.api.revokeSessions,\n auth.api.unlinkAccount\n ].map((endpoint) => authRequestPath(endpoint.path))\n )\n const recordProof = createProofRecorder(database, assurance, {\n totp: authRequestPath(twoStep.endpoints.verifyTOTP.path),\n recoveryCode: authRequestPath(twoStep.endpoints.verifyBackupCode.path),\n passkeySignIn: authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path),\n passkeyRegistration: authRequestPath(passkeys.endpoints.verifyPasskeyRegistration.path),\n deviceToken: authRequestPath(devices.endpoints.deviceToken.path)\n })\n\n return {\n handler: async (request) => {\n const path = new URL(request.url).pathname\n if (activeAccountPaths.has(path) && !(await resolveSession(request.headers))) {\n return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })\n }\n const response = await auth.handler(request)\n if (response.ok) await recordProof(path, response, () => currentSession(request.headers))\n return response\n },\n resolveIdentity,\n resolveSession,\n resolveAccountSession,\n twoStepConfirmed,\n resolveAccessToken,\n async listAccessTokens(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n const { apiKeys } = await auth.api.listApiKeys({ headers })\n return apiKeys.map(toAccessToken)\n },\n async createAccessToken(headers, input) {\n // A token outlives the session that makes it, so making one needs a recent sign-in.\n const session = await freshSession(headers)\n const created = await auth.api.createApiKey({\n body: {\n name: input.name,\n expiresIn: input.expiresInDays * DAY_SECONDS,\n userId: session.user.id\n }\n })\n return { token: created.key, accessToken: toAccessToken(created) }\n },\n async revokeAccessToken(headers, id) {\n await auth.api.deleteApiKey({ headers, body: { keyId: id } })\n },\n async listAuthenticationMethods(headers) {\n const accounts = await auth.api.listUserAccounts({ headers })\n return accounts.map((account) => ({\n id: account.id,\n providerId: account.providerId,\n createdAt: account.createdAt\n }))\n },\n async changePassword(headers, input) {\n const session = authenticationEmail ? await auth.api.getSession({ headers }) : null\n await auth.api.changePassword({\n headers,\n body: { ...input, revokeOtherSessions: false }\n })\n await auth.api.revokeOtherSessions({ headers })\n if (authenticationEmail && session) {\n await authenticationEmail.sendPasswordChanged({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n url: config.publicURL\n })\n }\n },\n async startSocialLink(headers, input) {\n await freshSession(headers)\n const body = { ...input, errorCallbackURL: input.callbackURL, disableRedirect: true }\n const link = await auth.api.linkSocialAccount({ headers, body, returnHeaders: true })\n return { url: link.response.url, headers: link.headers }\n },\n async unlinkAuthenticationMethod(headers, methodId) {\n const session = await freshSession(headers)\n await removeSignInMethod(database, { userId: session.user.id, methodId, providers })\n },\n async deleteAccount(headers, password) {\n const { headers: answer } = await auth.api.deleteUser({\n headers,\n body: password ? { password } : {},\n returnHeaders: true\n })\n return answer\n },\n async banUser(headers, userId, reason) {\n await auth.api.banUser({ headers, body: { userId, banReason: reason } })\n },\n async unbanUser(headers, userId) {\n await auth.api.unbanUser({ headers, body: { userId } })\n },\n async revokeUserSessions(headers, userId) {\n await auth.api.revokeUserSessions({ headers, body: { userId } })\n },\n async setRole(headers, userId, role) {\n await auth.api.setRole({ headers, body: { userId, role } })\n },\n async mfaStatus(headers) {\n const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })\n if (!session) return null\n const passkeys = await auth.api.listPasskeys({ headers })\n return assurance.status({\n sessionId: session.session.id,\n userId: session.user.id,\n deploymentRole: deploymentRole(session.user),\n twoFactorEnabled:\n 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true,\n passkeyCount: passkeys.length\n })\n },\n async enableTOTP(headers, password) {\n const response = await auth.api.enableTwoFactor({\n headers,\n body: { password, method: 'totp' }\n })\n if (response.method !== 'totp') throw new Error('TOTP setup was unavailable')\n return { totpURI: response.totpURI, backupCodes: response.backupCodes }\n },\n async verifyTOTP(headers, code) {\n const before = await currentSession(headers)\n const response = await verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'totp',\n twoStep.endpoints.verifyTOTP,\n before ? { id: before.session.id, userId: before.user.id } : null\n )\n // The first code from a new authenticator is what turns it on.\n if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {\n await notifyTwoStep(before.user, 'authenticator-on')\n }\n return response\n },\n async verifyRecoveryCode(headers, code) {\n const current = await currentSession(headers)\n return verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'recovery-code',\n twoStep.endpoints.verifyBackupCode,\n current ? { id: current.session.id, userId: current.user.id } : null\n )\n },\n async generateRecoveryCodes(headers, password) {\n return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes\n },\n async disableTOTP(headers, password) {\n await auth.api.disableTwoFactor({ headers, body: { password } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'authenticator-off')\n },\n async listPasskeys(headers) {\n return (await auth.api.listPasskeys({ headers })).map((item) => ({\n id: item.id,\n name: item.name,\n createdAt: item.createdAt\n }))\n },\n async deletePasskey(headers, id) {\n await auth.api.deletePasskey({ headers, body: { id } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'passkey-removed')\n },\n emailChangeAvailable,\n async profile(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return {\n id: session.user.id,\n name: session.user.name,\n email: session.user.email,\n image: session.user.image ?? null,\n createdAt: new Date(session.user.createdAt)\n }\n },\n async updateProfile(headers, input) {\n await auth.api.updateUser({ headers, body: { name: input.name } })\n },\n async setLocale(headers, locale) {\n await auth.api.updateUser({ headers, body: { locale } })\n },\n async changeEmail(headers, input) {\n const session = await freshSession(headers)\n if (session.user.email === input.newEmail) {\n throw APIError.from('BAD_REQUEST', {\n code: 'EMAIL_UNCHANGED',\n message: 'Email is the same'\n })\n }\n await auth.api.changeEmail({ headers, body: input })\n await authenticationEmail?.sendEmailChangeRequested({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n newEmail: input.newEmail\n })\n },\n async sessions(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return activity.sessions(session.user.id, session.session.id)\n },\n async revokeSession(headers, sessionId) {\n const session = await currentSession(headers)\n if (!session) throw APIError.fromStatus('UNAUTHORIZED')\n if (session.session.id === sessionId) {\n throw APIError.from('BAD_REQUEST', {\n code: 'CURRENT_SESSION',\n message: 'Sign out to end this session'\n })\n }\n const target = await database\n .selectFrom('session')\n .select('token')\n .where('id', '=', sessionId)\n .where('userId', '=', session.user.id)\n .executeTakeFirst()\n if (target) await auth.api.revokeSession({ headers, body: { token: target.token } })\n },\n async revokeOtherSessions(headers) {\n await auth.api.revokeOtherSessions({ headers })\n },\n async signIns(headers) {\n const session = await currentSession(headers)\n return session ? activity.signIns(session.user.id) : null\n },\n schemaVersion: BETTER_AUTH_SCHEMA_VERSION,\n async migrate() {\n // The access token table is Cloud's migration `009_access_tokens`, built before this runs.\n const migrations = await getMigrations({\n ...auth.options,\n plugins: auth.options.plugins.filter((plugin) => plugin.id !== accessTokens.id)\n })\n await migrations.runMigrations()\n }\n }\n}\n","import type { EnrollmentEmailOptions } from '#cloud/admin/enrollment/email'\nimport { createEnrollmentService } from '#cloud/admin/enrollment/service'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\nimport { createAuthenticationEmailService } from './email'\nimport { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'\n\n/**\n * What the enrollment service tells people, from the server's settings: where its links go, who\n * hears about new requests, and whether approvals may carry the official deployment's letter.\n * Every place that builds the service takes it from here, so none of them disagrees.\n */\nexport function enrollmentEmailOptions(\n config: CloudServerConfig,\n email: TransactionalEmailService | undefined\n): EnrollmentEmailOptions {\n return {\n publicURL: config.publicURL,\n adminRecipients: config.enrollmentAdminNotificationEmails,\n email,\n invitations: config.deployment === 'official'\n }\n}\n\nexport function createCloudAuthenticationRuntime(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n email: TransactionalEmailService,\n options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}\n) {\n const enrollment = createEnrollmentService(database, enrollmentEmailOptions(config, email))\n const auth = createBetterAuthAdapter(config, database, enrollment, {\n email: createAuthenticationEmailService(email, config.publicURL),\n ...options\n })\n return { auth, enrollment }\n}\n","import type { CloudAuthAdapter, CloudIdentity } from '#cloud/server/auth/adapter'\n\nexport type CloudActor = {\n userId: string\n email: string\n name: string\n deploymentRole?: 'user' | 'admin'\n /** How the request proved who it is: a signed-in session, or a personal access token. */\n credential?: 'session' | 'token'\n}\n\nexport type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>\nexport type CloudSessionResolver = (request: Request) => Promise<CloudActor | null>\n\nexport function createCloudIdentityResolver(auth: CloudAuthAdapter): CloudIdentityResolver {\n return (request) => auth.resolveIdentity(request.headers)\n}\n\nexport function createCloudSessionResolver(auth: CloudAuthAdapter): CloudSessionResolver {\n return (request) => auth.resolveSession(request.headers)\n}\n","import { normalizeEnrollmentEmail } from '#cloud/admin/enrollment/service'\nimport { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport {\n cloudAdminUserFilterSchema,\n type CloudAdminUser,\n type CloudAdminUserDetail,\n type CloudAdminUserFilter,\n type CloudAdminUserMethod\n} from '#cloud/contract'\nimport { createAccountDeletionService } from '#cloud/server/account/deletion'\nimport {\n createSignInActivity,\n type AuthenticationEmailService,\n type CloudAuthAdapter\n} from '#cloud/server/auth'\nimport { canRemoveSignInMethod, removeSignInMethod } from '#cloud/server/auth/methods'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { UserPictureService } from '#cloud/server/pictures'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { APIError } from 'better-auth'\nimport { countBy, groupBy, keyBy } from 'es-toolkit'\nimport { NoResultError, type ExpressionBuilder, type Kysely } from 'kysely'\n\n/** The sign-ins a person's page lists. */\nconst DETAIL_SIGN_INS = 20\n\ntype UserExpression = ExpressionBuilder<CloudDatabase, 'user'>\n\n/** The accounts that sign in with a provider: `credential` is a password. */\nfunction signsInWith(provider: string) {\n return (expression: UserExpression) =>\n expression.exists(\n expression\n .selectFrom('account')\n .select('account.id')\n .whereRef('account.userId', '=', 'user.id')\n .where('account.providerId', '=', provider)\n )\n}\n\n/** A search for part of a name or email, matched literally and without case. */\nfunction searchCondition(search: string) {\n const pattern = containsPattern(search)\n return (expression: UserExpression) =>\n expression.or([\n expression('user.email', 'ilike', pattern),\n expression('user.name', 'ilike', pattern)\n ])\n}\n\nconst FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {\n all: (expression) => expression.lit(true),\n administrators: (expression) => expression('user.role', '=', 'admin'),\n suspended: (expression) => expression('user.banned', '=', true),\n 'without-two-step': (expression) =>\n expression.and([\n // Better Auth leaves the flag unset on accounts that never turned it on.\n expression('user.twoFactorEnabled', 'is not', true),\n expression.not(\n expression.exists(\n expression\n .selectFrom('passkey')\n .select('passkey.id')\n .whereRef('passkey.userId', '=', 'user.id')\n )\n )\n ])\n}\n\n/** The provider a sign-in method a list is narrowed to is stored as: a password is `credential`. */\nconst methodProvider = (method: CloudAdminUserMethod) =>\n method === 'password' ? 'credential' : method\n\nexport type AdminUserQuery = AdminListQuery<CloudAdminUserFilter> & {\n method?: CloudAdminUserMethod\n}\n\ntype UserRow = {\n id: string\n name: string\n email: string\n image: string | null\n role: string | null\n banned: boolean | null\n banReason: string | null\n twoFactorEnabled: boolean | null\n createdAt: Date | string\n}\n\nexport function createAdminUserService(\n database: Kysely<CloudDatabase>,\n auth: CloudAuthAdapter,\n options: {\n requireMFA?: boolean\n notify?: AuthenticationEmailService\n /** Takes down a person's picture; without it, `removePicture` refuses. */\n pictures?: UserPictureService\n /** People join only once approved, so the list says where each account's request stands. */\n approval?: boolean\n /** The providers the server signs in with now; without it, every linked method is a way in. */\n signInProviders?: ReadonlySet<string>\n } = {}\n) {\n const activity = createSignInActivity(database)\n\n async function audit(\n actorId: string,\n action: string,\n userId: string,\n metadata: Record<string, unknown> = {}\n ): Promise<void> {\n await database\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action,\n subjectType: 'user',\n subjectId: userId,\n metadata\n })\n .execute()\n }\n\n const deletion = createAccountDeletionService(database)\n\n function refuseSelf(actorId: string, userId: string, action: string): void {\n if (actorId === userId) {\n throw new AdminDomainError(\n 'self_admin_action_forbidden',\n `Administrators cannot ${action} themselves`\n )\n }\n }\n\n async function requireSafeTarget(\n actorId: string,\n userId: string,\n action: 'ban' | 'demote'\n ): Promise<void> {\n refuseSelf(actorId, userId, action)\n const target = await database\n .selectFrom('user')\n .select('role')\n .where('id', '=', userId)\n .executeTakeFirst()\n if (target?.role !== 'admin') return\n const count = await database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('role', '=', 'admin')\n .where((expression) =>\n expression.or([expression('banned', '=', false), expression('banned', 'is', null)])\n )\n .executeTakeFirstOrThrow()\n if (Number(count.count) <= 1) {\n throw new AdminDomainError(\n 'last_admin_required',\n 'Cannot remove the last deployment administrator'\n )\n }\n }\n\n /** What the list shows about each account beyond its own row. */\n async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {\n const ids = rows.map((row) => row.id)\n if (ids.length === 0) return []\n const [passkeys, accounts, sessions, memberships, requests] = await Promise.all([\n database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),\n database\n .selectFrom('account')\n .select(['userId', 'providerId'])\n .where('userId', 'in', ids)\n .orderBy('createdAt')\n .execute(),\n database\n .selectFrom('session')\n .select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])\n .where('session.userId', 'in', ids)\n .where('session.expiresAt', '>', new Date())\n .groupBy('session.userId')\n .execute(),\n database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute(),\n options.approval\n ? database\n .selectFrom('enrollment')\n .select(['emailNormalized', 'status'])\n .where(\n 'emailNormalized',\n 'in',\n rows.map((row) => normalizeEnrollmentEmail(row.email))\n )\n .execute()\n : []\n ])\n const requestStatus = keyBy(requests, (request) => request.emailNormalized)\n const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))\n const lastActive = keyBy(sessions, (session) => session.userId)\n const workspaceCounts = countBy(memberships, (membership) => membership.userId)\n const methods = groupBy(accounts, (account) => account.userId)\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n email: row.email,\n image: row.image,\n role: row.role ?? undefined,\n banned: row.banned,\n banReason: row.banReason,\n createdAt: dateString(row.createdAt) ?? '',\n twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),\n lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),\n workspaceCount: workspaceCounts[row.id] ?? 0,\n methods: (methods[row.id] ?? []).map((account) => account.providerId),\n ...(options.approval && {\n request: requestStatus[normalizeEnrollmentEmail(row.email)]?.status ?? null\n })\n }))\n }\n\n const userColumns = [\n 'user.id',\n 'user.name',\n 'user.email',\n 'user.image',\n 'user.role',\n 'user.banned',\n 'user.banReason',\n 'user.twoFactorEnabled',\n 'user.emailVerified',\n 'user.createdAt'\n ] as const\n\n return {\n /** A page of accounts in sign-up order, with how many match the search under each filter. */\n async list(query: AdminUserQuery = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('user')\n if (search) searched = searched.where(searchCondition(search))\n if (query.method) searched = searched.where(signsInWith(methodProvider(query.method)))\n const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select(userColumns)\n .orderBy('user.createdAt')\n .orderBy('user.id')\n .limit(limit)\n .offset(offset)\n .execute()\n return { users: await accountSummaries(rows), total: counts[filter], counts }\n },\n\n /** Everything an administrator reads about one account; null when there is none. */\n async detail(userId: string): Promise<CloudAdminUserDetail | null> {\n const row = await database\n .selectFrom('user')\n .select(userColumns)\n .where('user.id', '=', userId)\n .executeTakeFirst()\n if (!row) return null\n const [[summary], methods, passkeys, sessions, signIns, workspaces] = await Promise.all([\n accountSummaries([row]),\n database\n .selectFrom('account')\n .select(['id', 'providerId', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt')\n .execute(),\n database\n .selectFrom('passkey')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('userId', '=', userId)\n .executeTakeFirstOrThrow(),\n activity.sessions(userId, ''),\n activity.signIns(userId, DETAIL_SIGN_INS),\n database\n .selectFrom('workspaceMember')\n .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')\n .select((expression) => [\n 'workspace.id',\n 'workspace.name',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n expression\n .selectFrom('workspaceMember as member')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .whereRef('member.workspaceId', '=', 'workspace.id')\n .as('memberCount')\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspaceMember.createdAt')\n .execute()\n ])\n if (!summary) return null\n return {\n user: { ...summary, emailVerified: row.emailVerified },\n methods: methods.map((method) => ({\n id: method.id,\n provider: method.providerId,\n createdAt: dateString(method.createdAt) ?? '',\n canRemove: canRemoveSignInMethod(method, methods, options.signInProviders)\n })),\n authenticator: row.twoFactorEnabled === true,\n passkeyCount: Number(passkeys.count),\n sessions,\n signIns,\n workspaces: workspaces.map((workspace) => ({\n id: workspace.id,\n name: workspace.name,\n role: workspace.role,\n memberCount: Number(workspace.memberCount ?? 0),\n joinedAt: dateString(workspace.createdAt) ?? ''\n }))\n }\n },\n\n async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {\n await requireSafeTarget(actorId, userId, 'ban')\n await auth.banUser(headers, userId, reason)\n await audit(actorId, 'user.banned', userId, reason ? { reason } : {})\n },\n async unban(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.unbanUser(headers, userId)\n await audit(actorId, 'user.unbanned', userId)\n },\n async revokeSessions(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.revokeUserSessions(headers, userId)\n await audit(actorId, 'user.sessions-revoked', userId)\n },\n async setAdmin(\n headers: Headers,\n actorId: string,\n userId: string,\n enabled: boolean\n ): Promise<void> {\n if (!enabled) await requireSafeTarget(actorId, userId, 'demote')\n if (enabled && options.requireMFA) {\n const user = await database\n .selectFrom('user')\n .select('twoFactorEnabled')\n .where('id', '=', userId)\n .executeTakeFirst()\n const passkey = await database\n .selectFrom('passkey')\n .select('id')\n .where('userId', '=', userId)\n .executeTakeFirst()\n if (!user?.twoFactorEnabled && !passkey) {\n throw new AdminDomainError(\n 'mfa_required',\n 'Users must enroll MFA before becoming deployment administrators'\n )\n }\n }\n await auth.setRole(headers, userId, enabled ? 'admin' : 'user')\n await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)\n },\n\n /**\n * Removes an account's authenticator app, recovery codes, and passkeys, for someone who lost\n * them; they sign in with their password or a linked account and set them up again.\n */\n async resetTwoStep(actorId: string, userId: string): Promise<void> {\n refuseSelf(actorId, userId, 'reset two-step sign-in for')\n await database.transaction().execute(async (transaction) => {\n const target = await transaction\n .selectFrom('user')\n .select(['id', 'email', 'name'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n await transaction.deleteFrom('twoFactor').where('userId', '=', userId).execute()\n await transaction.deleteFrom('passkey').where('userId', '=', userId).execute()\n await transaction.deleteFrom('mfaAssurance').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ twoFactorEnabled: false, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'user.two-step-reset',\n subjectType: 'user',\n subjectId: userId,\n metadata: {}\n })\n .execute()\n await options.notify?.sendTwoStepChanged(\n { email: target.email, name: target.name, userId, change: 'reset-by-administrator' },\n transaction\n )\n })\n },\n\n /**\n * Removes one way an account signs in, such as a Google account its owner lost control of.\n * The account keeps at least one; sessions already signed in stay until revoked.\n */\n async removeSignInMethod(actorId: string, userId: string, methodId: string): Promise<void> {\n refuseSelf(actorId, userId, 'remove a sign-in method from')\n await removeSignInMethod(database, {\n userId,\n methodId,\n providers: options.signInProviders,\n block: true,\n // The audit entry and the notice commit with the removal, or not at all.\n async also(transaction, removed) {\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'user.sign-in-method-removed',\n subjectType: 'user',\n subjectId: userId,\n metadata: { provider: removed }\n })\n .execute()\n const user = await transaction\n .selectFrom('user')\n .select(['email', 'name'])\n .where('id', '=', userId)\n .executeTakeFirstOrThrow()\n await options.notify?.sendTwoStepChanged(\n { ...user, userId, change: 'sign-in-method-removed', method: removed },\n transaction\n )\n }\n }).catch((error: unknown) => {\n if (!(error instanceof APIError)) throw error\n if (error.body?.code === 'FAILED_TO_UNLINK_LAST_ACCOUNT') {\n throw new AdminDomainError(\n 'last_authentication_method',\n 'Cannot remove an account’s last sign-in method'\n )\n }\n // A method of another account, or none, names nothing here, as an unknown person does.\n throw new NoResultError(database.selectFrom('account').toOperationNode())\n })\n },\n\n /**\n * Deletes an account that never got in: its request to join is still waiting or was declined,\n * as with someone who signed up again behind Apple's hidden email. It goes as its owner's own\n * deletion does, sessions and sign-in methods with it; the audit entry keeps who it was. An\n * account that was approved, or an administrator, is refused: those leave by their own hand.\n */\n async deleteUnapproved(actorId: string, userId: string): Promise<void> {\n refuseSelf(actorId, userId, 'delete')\n await deletion.remove(\n { id: userId },\n {\n // Under the account's and the request's locks, with the account as locked, so neither a\n // promotion, an address change, nor an approval can land between the check and the delete.\n async before(transaction, user) {\n const request = await transaction\n .selectFrom('enrollment')\n .select(['id', 'status', 'approvedUserId'])\n .where('emailNormalized', '=', normalizeEnrollmentEmail(user.email))\n .forUpdate()\n .executeTakeFirst()\n // A request that is waiting again may have been approved before and removed: that account\n // got in, and leaves only by its owner's hand.\n const approvedBefore =\n request !== undefined &&\n (request.approvedUserId !== null ||\n (await transaction\n .selectFrom('adminAuditEvent')\n .select('id')\n .where('action', '=', 'enrollment.approved')\n .where('subjectType', '=', 'enrollment')\n .where('subjectId', '=', request.id)\n .executeTakeFirst()) !== undefined)\n if (\n user.role === 'admin' ||\n approvedBefore ||\n (request?.status !== 'pending' && request?.status !== 'rejected')\n ) {\n throw new AdminDomainError(\n 'account_approved',\n 'Only an account whose request was never approved can be deleted'\n )\n }\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'user.deleted',\n subjectType: 'user',\n subjectId: userId,\n metadata: { name: user.name, email: user.email }\n })\n .execute()\n }\n }\n )\n },\n\n /** Takes down a person's picture, such as one that should not be shown; initials replace it. */\n async removePicture(actorId: string, userId: string): Promise<void> {\n if (!options.pictures) throw new Error('Pictures are not available')\n await database\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .executeTakeFirstOrThrow()\n await options.pictures.remove(userId)\n await audit(actorId, 'user.picture-removed', userId)\n }\n }\n}\n\nexport type AdminUserService = ReturnType<typeof createAdminUserService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Transaction } from 'kysely'\n\n/** How reporters hear back: through email, with the deployment's abuse address to disagree. */\nexport type ReportReplies = {\n email?: TransactionalEmailService\n /** Where a reporter writes to disagree with a decision: the deployment's abuse address. */\n contactEmail?: string\n}\n\n/**\n * Tells each reporter who left an address what the administrators decided about their report:\n * the document blocked, the report acted on some other way, or the document left as it was. Only\n * a block says `blocked`, so a reporter is never told of one that didn't happen. Each report is answered once, in the transaction that\n * decides it, so a decision that rolls back tells nobody.\n */\nexport async function tellReporters(\n transaction: Transaction<CloudDatabase>,\n replies: ReportReplies,\n reportIds: readonly string[],\n outcome: 'blocked' | 'actioned' | 'dismissed'\n): Promise<void> {\n const { email } = replies\n if (!email || reportIds.length === 0) return\n const reports = await transaction\n .selectFrom('documentReport')\n .innerJoin('document', 'document.id', 'documentReport.documentId')\n .select([\n 'documentReport.id',\n 'documentReport.replyEmail',\n 'documentReport.replyLocale',\n 'document.name'\n ])\n .where('documentReport.id', 'in', reportIds)\n .where('documentReport.replyEmail', 'is not', null)\n .execute()\n for (const report of reports) {\n if (!report.replyEmail) continue\n await email.enqueue(\n {\n idempotencyKey: `document-report-decided/${report.id}`,\n kind: 'document-report-decided',\n recipientEmail: report.replyEmail,\n fallbackLocale: report.replyLocale,\n payload: {\n documentName: report.name,\n outcome,\n contactEmail: replies.contactEmail ?? null\n }\n },\n transaction\n )\n }\n}\n","import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\n\n/**\n * Who follows a link: the person signed in to the server, if any, whom the server lets in where\n * it turns guests away.\n */\nexport async function shareActor(\n request: Request,\n resolveSession?: CloudSessionResolver\n): Promise<CloudActor | undefined> {\n return resolveSession ? ((await resolveSession(request)) ?? undefined) : undefined\n}\n","import type { DocumentAccess, DocumentAccessSource, DocumentPermission } from '#cloud/contract'\nimport {\n documentRoleCan,\n GRANT_DOCUMENT_ROLE,\n workspaceRoleCan,\n type AccessRequest\n} from '#cloud/server/auth/access-control'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type AccessDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\ntype DocumentAccessGrant = {\n source: DocumentAccessSource\n can: (request: AccessRequest) => boolean\n}\n\n/**\n * Everything that gives a user access to a document, each checked against its role table: a live\n * document, or one in Trash.\n */\nasync function documentAccessGrants(\n database: AccessDatabase,\n userId: string,\n documentId: string,\n place: 'live' | 'trash' = 'live'\n): Promise<DocumentAccessGrant[]> {\n const document = await database\n .selectFrom('document')\n .leftJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .leftJoin('documentGrant', (join) =>\n join\n .onRef('documentGrant.documentId', '=', 'document.id')\n .on('documentGrant.userId', '=', userId)\n .on('documentGrant.revokedAt', 'is', null)\n )\n .select([\n 'document.createdBy',\n 'workspaceMember.role as workspaceRole',\n 'documentGrant.permission as grantPermission'\n ])\n .where('document.id', '=', documentId)\n .where('document.deletedAt', place === 'live' ? 'is' : 'is not', null)\n // A document an administrator took down is out of reach for everyone, its owner included.\n .where('document.disabledAt', 'is', null)\n .executeTakeFirst()\n if (!document) return []\n\n const grants: DocumentAccessGrant[] = []\n // Making a document gives access only while its maker is in the workspace: someone removed\n // from it keeps no way back in.\n if (document.createdBy === userId && document.workspaceRole !== null) {\n grants.push({ source: 'owner', can: (request) => documentRoleCan('owner', request) })\n }\n const { workspaceRole, grantPermission } = document\n if (workspaceRole) {\n grants.push({ source: 'workspace', can: (request) => workspaceRoleCan(workspaceRole, request) })\n }\n if (grantPermission) {\n const role = GRANT_DOCUMENT_ROLE[grantPermission]\n grants.push({ source: 'direct-grant', can: (request) => documentRoleCan(role, request) })\n }\n return grants\n}\n\nfunction grantsAllow(grants: DocumentAccessGrant[], request: AccessRequest): boolean {\n return grants.some((grant) => grant.can(request))\n}\n\nexport async function resolveDocumentAccess(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<DocumentAccess | undefined> {\n const grants = await documentAccessGrants(database, userId, documentId)\n if (!grantsAllow(grants, { document: ['read'] })) return undefined\n const permission: DocumentPermission = grantsAllow(grants, { document: ['edit'] })\n ? 'edit'\n : 'view'\n return {\n permission,\n canManageSharing: grantsAllow(grants, { document: ['share'] }),\n sources: grants.map((grant) => grant.source)\n }\n}\n\n/**\n * What the user may do with a live document's comments, or undefined when they may not read it:\n * everyone who can read may comment, and those who can edit may delete anyone's comments.\n */\nexport async function resolveDocumentCommentAccess(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<{ canComment: boolean; canModerate: boolean } | undefined> {\n const grants = await documentAccessGrants(database, userId, documentId)\n if (!grantsAllow(grants, { document: ['read'] })) return undefined\n return {\n canComment: grantsAllow(grants, { document: ['comment'] }),\n canModerate: grantsAllow(grants, { document: ['moderate'] })\n }\n}\n\nexport function canEditDocument(access: DocumentAccess): boolean {\n return access.permission === 'edit'\n}\n\n/** Whether the user may delete the document; `documentRoles` and `workspaceRoles` decide who. */\nexport async function canDeleteDocument(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<boolean> {\n const grants = await documentAccessGrants(database, userId, documentId)\n return grantsAllow(grants, { document: ['delete'] })\n}\n\n/** Whether the user may restore the document from Trash, or delete it there for good. */\nexport async function trashedDocumentAllows(\n database: AccessDatabase,\n userId: string,\n documentId: string,\n action: 'delete' | 'purge'\n): Promise<boolean> {\n const grants = await documentAccessGrants(database, userId, documentId, 'trash')\n return grantsAllow(grants, { document: [action] })\n}\n","export const CLOUD_FEATURE_KEYS = {\n links: 'cloud.sharing.links',\n guestView: 'cloud.sharing.guest-view',\n guestEdit: 'cloud.sharing.guest-edit',\n guestPresence: 'cloud.sharing.guest-presence',\n collaboration: 'cloud.collaboration.enabled',\n serverEnforcedWrites: 'cloud.collaboration.server-enforced-writes',\n revisionHistory: 'cloud.documents.revision-history',\n maximumFileBytes: 'cloud.documents.maximum-file-bytes',\n maximumStorageBytes: 'cloud.storage.maximum-bytes',\n maximumParticipants: 'cloud.collaboration.maximum-participants',\n cloudServices: 'cloud.services.enabled',\n monthlyCreditAllowance: 'cloud.services.monthly-credit-allowance'\n} as const\n\nexport type CloudPolicyContext = {\n /** Whose entitlements apply: an account by default for a workspace, its owner's. */\n targetingKey: string\n /** Required, so an account ID never reads as a workspace's and falls back to defaults. */\n subjectType: 'workspace' | 'user' | 'organization' | 'deployment'\n actorId?: string\n workspaceId?: string\n organizationId?: string\n documentId?: string\n deploymentMode: 'official' | 'self-hosted'\n}\n","import { CLOUD_ACCOUNT_PLAN_PATH } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nexport type StorageLimitNoticeResult = {\n /** Accounts told this pass that their storage is full. */\n notified: number\n /** Accounts back under their plan, which are told again if they fill it again. */\n cleared: number\n}\n\nexport type StorageLimitNoticeOptions = {\n policy: CloudPolicy\n email: TransactionalEmailService\n publicURL: string\n /** Whether the server sells plans, so the email offers more storage. */\n upgradable: boolean\n deploymentMode: 'official' | 'self-hosted'\n}\n\n/**\n * Emails each account once when it holds all the storage its plan allows, which makes its\n * workspaces read-only (`storageLimitReached`), whether it filled its plan or its plan shrank below\n * what it holds, as when a subscription lapses. A pass compares every owner's committed storage\n * with their plan, so it reaches both however the plan changed.\n */\nexport function createStorageLimitNoticeService(\n database: Kysely<CloudDatabase>,\n options: StorageLimitNoticeOptions\n) {\n /**\n * Each account's limit: a number, null when its plan sets none, or undefined when the policy\n * failed to answer, which decides nothing either way until a pass where it answers.\n */\n async function limit(userId: string): Promise<number | null | undefined> {\n const maximum = await options.policy.numberResolution(\n CLOUD_FEATURE_KEYS.maximumStorageBytes,\n Number.MAX_SAFE_INTEGER,\n { targetingKey: userId, subjectType: 'user', deploymentMode: options.deploymentMode }\n )\n if (maximum.failed) return undefined\n return maximum.value === Number.MAX_SAFE_INTEGER ? null : maximum.value\n }\n\n async function notify(userId: string, usedBytes: number, limitBytes: number): Promise<boolean> {\n return database.transaction().execute(async (transaction) => {\n const notice = await transaction\n .insertInto('storageLimitNotice')\n .values({ userId })\n .onConflict((conflict) => conflict.column('userId').doNothing())\n .returning('notifiedAt')\n .executeTakeFirst()\n if (!notice) return false\n const user = await transaction\n .selectFrom('user')\n .select(['name', 'email'])\n .where('id', '=', userId)\n .executeTakeFirst()\n if (!user) return false\n await options.email.enqueue(\n {\n idempotencyKey: `storage-limit-reached/${userId}/${new Date(notice.notifiedAt).getTime()}`,\n kind: 'storage-limit-reached',\n recipientEmail: user.email,\n payload: {\n name: user.name,\n usedBytes,\n limitBytes,\n upgradable: options.upgradable,\n actionURL: new URL(\n options.upgradable ? CLOUD_ACCOUNT_PLAN_PATH : '/',\n options.publicURL\n ).href\n }\n },\n transaction\n )\n return true\n })\n }\n\n return {\n async notifyStorageLimits(): Promise<StorageLimitNoticeResult> {\n const [owners, notices] = await Promise.all([\n database\n .selectFrom('workspace')\n .innerJoin('workspaceStorageUsage', 'workspaceStorageUsage.workspaceId', 'workspace.id')\n .select((expression) => [\n 'workspace.ownerId',\n expression.fn.sum<string | number>('workspaceStorageUsage.committedBytes').as('bytes')\n ])\n .groupBy('workspace.ownerId')\n .execute(),\n database.selectFrom('storageLimitNotice').select('userId').execute()\n ])\n const usage = new Map(owners.map((owner) => [owner.ownerId, Number(owner.bytes)]))\n const result: StorageLimitNoticeResult = { notified: 0, cleared: 0 }\n for (const [userId, usedBytes] of usage) {\n const limitBytes = await limit(userId)\n if (typeof limitBytes === 'number' && usedBytes >= limitBytes) {\n if (await notify(userId, usedBytes, limitBytes)) result.notified++\n }\n }\n // A notice whose account holds less than its plan allows again, or nothing at all, is done.\n for (const { userId } of notices) {\n const usedBytes = usage.get(userId) ?? 0\n const limitBytes = await limit(userId)\n if (limitBytes === undefined) continue\n if (limitBytes !== null && usedBytes >= limitBytes) continue\n await database.deleteFrom('storageLimitNotice').where('userId', '=', userId).execute()\n result.cleared++\n }\n return result\n }\n }\n}\n\nexport type StorageLimitNoticeService = ReturnType<typeof createStorageLimitNoticeService>\n","import {\n commitImageUploadsSchema,\n commitUploadSchema,\n createDocumentSchema,\n createUploadSchema,\n requestImageLinksSchema,\n requestImageUploadsSchema\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n DocumentPurgeFailedError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport type { DocumentService } from '#cloud/server/documents/service'\nimport { StorageQuotaExceededError } from '#cloud/server/quota'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport {\n documentParams,\n uploadParams,\n validatedJSON,\n workspaceParams\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type DocumentRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** The response a document domain error stands for, or null for any other error. */\nexport function documentDomainError(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof DocumentConflictError) {\n return context.json({ error: { code: 'revision_conflict' as const } }, 409)\n }\n if (error instanceof StorageQuotaExceededError) {\n return context.json({ error: { code: 'storage_quota_exceeded' as const } }, 409)\n }\n // Reported where cleanup failed, so the request handler doesn't report it again.\n if (error instanceof DocumentPurgeFailedError) {\n return context.json({ error: { code: 'purge_failed' as const } }, 503)\n }\n if (error instanceof UploadInvalidError) {\n return context.json({ error: { code: 'invalid_upload' as const } }, 422)\n }\n return null\n}\n\n/** Answers with what `respond` gives, or with the response a document domain error stands for. */\nasync function documentResponse<T extends Response>(\n context: Context,\n respond: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await respond()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\nexport function createDocumentRoutes(\n service: DocumentService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<DocumentRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/workspaces/:workspaceId/documents',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.documentCreation,\n routeParamResource('workspaceId'),\n (context) => context.req.method !== 'POST'\n )\n )\n router.use(\n '/documents/:documentId/images',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n router.use(\n '/documents/:documentId/uploads',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .get('/shared-documents', async (context) =>\n context.json({ documents: await service.listShared(context.get('actor').userId) })\n )\n .get('/trash', async (context) =>\n context.json({ documents: await service.trash.list(context.get('actor').userId) })\n )\n .post('/trash/:documentId/restore', documentParams, (context) =>\n documentResponse(context, async () => {\n await service.trash.restore(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n return context.body(null, 204)\n })\n )\n .delete('/trash/:documentId', documentParams, (context) =>\n documentResponse(context, async () => {\n await service.trash.purge(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n return context.body(null, 204)\n })\n )\n .get('/workspaces/:workspaceId/documents', workspaceParams, async (context) => {\n const documents = await service.list(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n if (!documents) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ documents })\n })\n .get('/workspaces/:workspaceId/usage', workspaceParams, async (context) => {\n try {\n return context.json({\n usage: await service.usage(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .post(\n '/workspaces/:workspaceId/documents',\n workspaceParams,\n validatedJSON(createDocumentSchema),\n async (context) => {\n try {\n const document = await service.create(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json')\n )\n return context.json({ document }, 201)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n }\n )\n .delete('/documents/:documentId', documentParams, async (context) => {\n try {\n await service.remove(context.get('actor').userId, context.req.valid('param').documentId)\n return context.body(null, 204)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .get('/documents/:documentId/access', documentParams, (context) =>\n documentResponse(context, async () =>\n context.json({\n access: await service.access(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .get('/documents/:documentId', documentParams, (context) =>\n documentResponse(context, async () =>\n context.json({\n document: await service.download(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/uploads',\n documentParams,\n validatedJSON(createUploadSchema),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.createUpload(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/documents/:documentId/images/commit',\n documentParams,\n validatedJSON(commitImageUploadsSchema),\n (context) =>\n documentResponse(context, async () => {\n await service.commitImageUploads(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json').uploads\n )\n return context.body(null, 204)\n })\n )\n .post(\n '/documents/:documentId/images/links',\n documentParams,\n validatedJSON(requestImageLinksSchema),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.imageLinks(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json').checksums\n )\n )\n )\n )\n .post(\n '/documents/:documentId/images',\n documentParams,\n validatedJSON(requestImageUploadsSchema),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.requestImageUploads(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/uploads/:uploadId/commit',\n uploadParams,\n validatedJSON(commitUploadSchema),\n async (context) => {\n try {\n const document = await service.commitUpload(\n context.get('actor').userId,\n context.req.valid('param').uploadId,\n context.req.valid('json')\n )\n return context.json({ document })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n","import type {\n CommitUploadInput,\n DocumentImageDownload,\n DocumentImageLink,\n ImageUploadOffer,\n RequestImageUploadsInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { StorageQuotaService } from '#cloud/server/quota'\nimport { uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { DAY_MS, MINUTE_MS } from '@open-pencil/std/timing'\n\n/** Images are stored as the bytes their file holds, whatever format those are. */\nexport const IMAGE_CONTENT_TYPE = 'application/octet-stream'\n\ntype Executor = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/** An image no revision has used for this long may be released; a save uploads first. */\nexport const IMAGE_RELEASE_GRACE_MS = DAY_MS\n\n/** How long a link to download a revision or its images works. */\nexport const DOWNLOAD_LIFETIME_MS = 5 * MINUTE_MS\n\n/**\n * The images a workspace's documents use, each stored once under the SHA-256 the object store\n * verified, and which of them each stored revision uses under the names its file gives them.\n */\nexport function createDocumentImages(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n quota: StorageQuotaService\n) {\n /**\n * Gives up uploads a request reserved when it could not offer them all, so a retry is not\n * refused for space they hold. A multipart upload the store began is aborted first; one that\n * cannot be stays pending for cleanup, which aborts it once it expires.\n */\n async function abandonUploads(\n uploads: readonly { uploadId: string; objectKey: string }[],\n offers: readonly ImageUploadOffer[]\n ): Promise<void> {\n const begun = new Map(offers.map((offer) => [offer.uploadId, offer.upload]))\n for (const { uploadId, objectKey } of uploads) {\n try {\n const upload = begun.get(uploadId)\n if (upload?.kind === 'multipart') {\n await objects.abortUpload({ key: objectKey, uploadId: upload.uploadId })\n }\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .where('status', '=', 'pending')\n .execute()\n } catch (error) {\n // Cleanup releases it once it expires.\n logCloud('warn', 'Giving up an image upload failed', { error: loggedError(error) })\n }\n }\n }\n\n return {\n /**\n * Uploads for the images of `input` the workspace lacks, each with its own object key and\n * reservation, so an abandoned one is cleaned up like any other upload. Images it holds\n * already need nothing.\n */\n async requestUploads(input: {\n userId: string\n documentId: string\n workspaceId: string\n images: RequestImageUploadsInput['images']\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<ImageUploadOffer[]> {\n const requested = uniqBy(input.images, (image) => image.checksum)\n // Held images are renewed, so none is released before the save that asked commits.\n const held = new Set(\n (\n await database\n .updateTable('workspaceImage')\n .set({ touchedAt: new Date() })\n .where('workspaceId', '=', input.workspaceId)\n .where(\n 'checksum',\n 'in',\n requested.map((image) => image.checksum)\n )\n .returning('checksum')\n .execute()\n ).map((row) => row.checksum)\n )\n const missing = requested\n .filter((image) => !held.has(image.checksum))\n .map((image) => {\n const uploadId = crypto.randomUUID()\n return {\n ...image,\n uploadId,\n objectKey: `documents/${input.workspaceId}/images/${uploadId}`\n }\n })\n if (missing.length === 0) return []\n await database.transaction().execute(async (transaction) => {\n for (const image of missing) {\n await transaction\n .insertInto('upload')\n .values({\n id: image.uploadId,\n kind: 'image',\n documentId: input.documentId,\n baseRevisionId: null,\n objectKey: image.objectKey,\n checksum: image.checksum,\n byteSize: image.byteSize,\n contentType: IMAGE_CONTENT_TYPE,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: input.userId,\n expiresAt: input.expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: input.workspaceId,\n uploadId: image.uploadId,\n bytes: image.byteSize,\n expiresAt: input.expiresAt,\n maximumBytes: input.maximumBytes\n })\n }\n })\n const offers: ImageUploadOffer[] = []\n try {\n for (const image of missing) {\n const upload = await objects.createUpload({\n key: image.objectKey,\n byteSize: image.byteSize,\n checksum: image.checksum,\n contentType: IMAGE_CONTENT_TYPE,\n expiresAt: input.expiresAt\n })\n offers.push({ checksum: image.checksum, uploadId: image.uploadId, upload })\n if (upload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: upload.uploadId })\n .where('id', '=', image.uploadId)\n .execute()\n }\n }\n } catch (error) {\n await abandonUploads(missing, offers)\n throw error\n }\n return offers\n },\n\n /**\n * Stores a verified image upload as the workspace's copy of that image. When another upload of\n * the same bytes got there first, this one's file is left unreferenced for cleanup to delete\n * and its reservation is released rather than counted twice.\n */\n async landInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n uploadId: string\n workspaceId: string\n objectKey: string\n stored: { checksum: string; byteSize: number; contentType: string }\n }\n ): Promise<void> {\n const storageObjectId = crypto.randomUUID()\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: input.objectKey,\n checksum: input.stored.checksum,\n byteSize: input.stored.byteSize,\n contentType: input.stored.contentType\n })\n .execute()\n const landed = await transaction\n .insertInto('workspaceImage')\n .values({\n workspaceId: input.workspaceId,\n checksum: input.stored.checksum,\n storageObjectId\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'checksum']).doNothing())\n .returning('checksum')\n .executeTakeFirst()\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', input.uploadId)\n .execute()\n if (landed) await quota.commitInTransaction(transaction, input.uploadId)\n else await quota.releaseInTransaction(transaction, input.uploadId)\n },\n\n /**\n * Records the images a new revision uses. Each must be the workspace's already; holding them\n * until the revision refers to them keeps a release of an unused image from racing the save.\n * Whether every image was there.\n */\n async attachInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: { workspaceId: string; revisionId: string; images: CommitUploadInput['images'] }\n ): Promise<boolean> {\n const images = uniqBy(input.images, (image) => image.name)\n if (images.length === 0) return true\n const checksums = uniq(images.map((image) => image.checksum))\n const held = await transaction\n .selectFrom('workspaceImage')\n .select('checksum')\n .where('workspaceId', '=', input.workspaceId)\n .where('checksum', 'in', checksums)\n .forShare()\n .execute()\n if (held.length !== checksums.length) return false\n await transaction\n .insertInto('revisionImage')\n .values(\n images.map((image) => ({\n revisionId: input.revisionId,\n name: image.name,\n workspaceId: input.workspaceId,\n checksum: image.checksum\n }))\n )\n .execute()\n return true\n }\n }\n}\n\nexport type DocumentImages = ReturnType<typeof createDocumentImages>\n\n/** Gives a revision made from another, by a restore or a duplicate, the same images. */\nexport async function copyRevisionImages(\n transaction: Transaction<CloudDatabase>,\n fromRevisionId: string,\n toRevisionId: string\n): Promise<void> {\n await transaction\n .insertInto('revisionImage')\n .columns(['revisionId', 'name', 'workspaceId', 'checksum'])\n .expression((expression) =>\n expression\n .selectFrom('revisionImage')\n .select((select) => [\n select.val(toRevisionId).as('revisionId'),\n 'name',\n 'workspaceId',\n 'checksum'\n ])\n .where('revisionId', '=', fromRevisionId)\n )\n .execute()\n}\n\n/** Where to download each image a revision uses, under its name in the file. */\nexport async function revisionImageDownloads(\n executor: Executor,\n objects: ObjectStore,\n revisionId: string,\n expiresAt: Date\n): Promise<DocumentImageDownload[]> {\n const rows = await executor\n .selectFrom('revisionImage')\n .innerJoin('workspaceImage', (join) =>\n join\n .onRef('workspaceImage.workspaceId', '=', 'revisionImage.workspaceId')\n .onRef('workspaceImage.checksum', '=', 'revisionImage.checksum')\n )\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select([\n 'revisionImage.name',\n 'revisionImage.checksum',\n 'storageObject.objectKey',\n 'storageObject.byteSize'\n ])\n .where('revisionImage.revisionId', '=', revisionId)\n .orderBy('revisionImage.name')\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n name: row.name,\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt })\n }))\n )\n}\n\n/**\n * Releases up to `batchSize` images no revision uses that no save has asked for since `before`:\n * their bytes go back to the workspace's usage, and their files, no longer anyone's, are left for\n * the object sweep. A save holds the images it refers to, so it either lands first and keeps them\n * or finds them gone and uploads them again. How many were released and their bytes.\n */\nexport async function releaseUnusedImages(\n database: Kysely<CloudDatabase>,\n before: Date,\n batchSize: number\n): Promise<{ released: number; bytes: number }> {\n return database.transaction().execute(async (transaction) => {\n const unused = await transaction\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.workspaceId', 'workspaceImage.checksum', 'storageObject.byteSize'])\n .where('workspaceImage.touchedAt', '<', before)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n )\n )\n )\n .limit(batchSize)\n .forUpdate('workspaceImage')\n .skipLocked()\n .execute()\n let bytes = 0\n for (const image of unused) {\n await transaction\n .deleteFrom('workspaceImage')\n .where('workspaceId', '=', image.workspaceId)\n .where('checksum', '=', image.checksum)\n .execute()\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', Number(image.byteSize)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', image.workspaceId)\n .execute()\n bytes += Number(image.byteSize)\n }\n return { released: unused.length, bytes }\n })\n}\n\n/**\n * Where to download the images of `checksums` the document's workspace holds, for someone who may\n * view the document. A live room names images by checksum before any save does, and an editor\n * whose image the workspace already holds through another document uploads nothing for this one,\n * so the workspace, not the document, is what an image belongs to. Asking needs the image's\n * SHA-256, which only someone with its bytes has.\n */\nexport async function documentImageLinks(\n executor: Executor,\n objects: ObjectStore,\n input: { documentId: string; checksums: string[]; expiresAt: Date }\n): Promise<DocumentImageLink[]> {\n const rows = await executor\n .selectFrom('workspaceImage')\n .innerJoin('document', 'document.workspaceId', 'workspaceImage.workspaceId')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.checksum', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('document.id', '=', input.documentId)\n .where('workspaceImage.checksum', 'in', uniq(input.checksums))\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt: input.expiresAt })\n }))\n )\n}\n\n/** The images the workspace's current revisions use, each counted once however many use it. */\nexport async function currentImageUsage(\n executor: Executor,\n workspaceId: string\n): Promise<{ objectCount: number; bytesUsed: number }> {\n const usage = await executor\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select((expression) => [\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('workspaceImage.workspaceId', '=', workspaceId)\n .where((expression) =>\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .innerJoin('document', 'document.currentRevisionId', 'revisionImage.revisionId')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n .where('document.deletedAt', 'is', null)\n )\n )\n .executeTakeFirstOrThrow()\n return { objectCount: Number(usage.objectCount), bytesUsed: Number(usage.bytesUsed) }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport type { CloudPolicyContext } from './keys'\n\ntype WorkspacePolicyTarget = { workspaceId: string } | { documentId: string }\n\n/** A policy context for a workspace, which names it. */\ntype WorkspacePolicyContext = CloudPolicyContext & { workspaceId: string }\n\n/**\n * The policy context for a workspace, or for a document by its workspace: its owner's plan, which\n * every workspace they own takes, so creating more workspaces adds no allowance. Null when the\n * workspace or document is gone.\n */\nexport async function workspacePolicyContext(\n database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n target: WorkspacePolicyTarget,\n context: Pick<CloudPolicyContext, 'actorId' | 'deploymentMode'>\n): Promise<WorkspacePolicyContext | null> {\n const row =\n 'documentId' in target\n ? await database\n .selectFrom('document')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select(['workspace.id as workspaceId', 'workspace.ownerId'])\n .where('document.id', '=', target.documentId)\n .executeTakeFirst()\n : await database\n .selectFrom('workspace')\n .select(['id as workspaceId', 'ownerId'])\n .where('id', '=', target.workspaceId)\n .executeTakeFirst()\n if (!row) return null\n const policyContext: WorkspacePolicyContext = {\n targetingKey: row.ownerId,\n subjectType: 'user',\n workspaceId: row.workspaceId,\n deploymentMode: context.deploymentMode\n }\n if (context.actorId) policyContext.actorId = context.actorId\n if ('documentId' in target) policyContext.documentId = target.documentId\n return policyContext\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport type { Kysely } from 'kysely'\n\n/** How far back a workspace without full revision history keeps its versions. */\nexport const LIMITED_HISTORY_DAYS = 30\n\n/**\n * The oldest moment a workspace's history reaches, or null when it keeps everything: with the\n * `revisionHistory` entitlement off, only the last 30 days, as on a free plan.\n */\nexport async function historyStart(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy | undefined,\n deploymentMode: CloudPolicyContext['deploymentMode'],\n workspaceId: string,\n now: Date\n): Promise<Date | null> {\n const context = policy\n ? await workspacePolicyContext(database, { workspaceId }, { deploymentMode })\n : null\n const full =\n policy && context\n ? await policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, true, context)\n : true\n return full ? null : new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { IMAGE_RELEASE_GRACE_MS, releaseUnusedImages } from '#cloud/server/documents/images'\nimport { historyStart, LIMITED_HISTORY_DAYS } from '#cloud/server/documents/versions/history'\nimport { reportCloudError, type CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { groupBy, sumBy, uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\n/** How long a save between versions is kept before compaction may delete it. */\nexport const REVISION_COMPACTION_GRACE_MS = 24 * 60 * 60_000\n/**\n * How long a stored file nothing refers to is left alone: a collaboration room records its next\n * snapshot's file before writing it and points the room at it moments later.\n */\nexport const OBJECT_SWEEP_GRACE_MS = 15 * 60_000\n\nexport type RevisionCompactionOptions = {\n batchSize: number\n /** How long a save stays before it can be compacted, so recent work is never lost to it. */\n graceMs: number\n now?: Date\n}\n\nexport type RevisionCompactionResult = {\n versionsPruned: number\n /** Images no revision used any more, released after their grace period. */\n imagesReleased: number\n revisionsDeleted: number\n objectsDeleted: number\n bytesReclaimed: number\n failed: number\n}\n\nexport type RevisionCompactionService = {\n compactRevisions(options: RevisionCompactionOptions): Promise<RevisionCompactionResult>\n}\n\n/**\n * Keeps a document's stored history to its versions. A save that is neither the document's\n * current state nor kept by a version is deleted once it is older than the grace period, and its\n * file with it when nothing else uses it; a workspace without full history first loses the\n * versions older than its 30 days.\n */\nexport function createRevisionCompactionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: {\n policy?: CloudPolicy\n deploymentMode?: CloudPolicyContext['deploymentMode']\n /** Where each step compaction couldn't finish is reported; a pass carries on with the rest. */\n reportError?: CloudErrorReporter\n } = {}\n): RevisionCompactionService {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n const report = (message: string, error: unknown, resources?: Record<string, string>) =>\n reportCloudError(options.reportError, message, error, { source: 'cleanup', resources })\n async function pruneVersions(now: Date, batchSize: number): Promise<number> {\n if (!options.policy) return 0\n const limitedBefore = new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n const workspaces = await database\n .selectFrom('documentVersion')\n .innerJoin('document', 'document.id', 'documentVersion.documentId')\n .select('document.workspaceId')\n .distinct()\n .where('documentVersion.createdAt', '<', limitedBefore)\n .execute()\n let pruned = 0\n for (const { workspaceId } of workspaces) {\n const start = await historyStart(database, options.policy, deploymentMode, workspaceId, now)\n if (!start) continue\n const deleted = await database\n .deleteFrom('documentVersion')\n .where('id', 'in', (query) =>\n query\n .selectFrom('documentVersion as version')\n .innerJoin('document', 'document.id', 'version.documentId')\n .select('version.id')\n .where('document.workspaceId', '=', workspaceId)\n .where('version.createdAt', '<', start)\n // The document's current state stays listed however old it is.\n .whereRef('version.revisionId', '!=', 'document.currentRevisionId')\n .limit(batchSize)\n )\n .executeTakeFirst()\n pruned += Number(deleted.numDeletedRows)\n }\n return pruned\n }\n\n /** Saves that may go: old, unversioned, not current, in a document that is not deleted. */\n function compactable(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>, before: Date) {\n return source\n .selectFrom('documentRevision')\n .innerJoin('document', 'document.id', 'documentRevision.documentId')\n .where('documentRevision.createdAt', '<', before)\n .where('document.deletedAt', 'is', null)\n .where((expression) =>\n expression.or([\n expression('document.currentRevisionId', 'is', null),\n expression('document.currentRevisionId', '!=', expression.ref('documentRevision.id'))\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentVersion')\n .select('documentVersion.id')\n .whereRef('documentVersion.revisionId', '=', 'documentRevision.id')\n )\n )\n )\n }\n\n /** A file no revision refers to: freed by compaction, waiting for the object store. */\n function unreferencedObjects(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>) {\n return source.selectFrom('storageObject').where(unreferencedObject)\n }\n\n /**\n * Deletes up to `limit` compactable saves of one document and returns the bytes of files nothing\n * refers to any more to the workspace's usage. Their rows stay until the files are gone, so a\n * delete that fails is tried again on the next pass.\n */\n async function compactDocument(\n documentId: string,\n workspaceId: string,\n before: Date,\n limit: number\n ) {\n return database.transaction().execute(async (transaction) => {\n // Saves and restores lock the document too, so none can keep a revision deleted here.\n await transaction\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n const revisions = await compactable(transaction, before)\n .select(['documentRevision.id', 'documentRevision.storageObjectId'])\n .where('documentRevision.documentId', '=', documentId)\n .limit(limit)\n .execute()\n if (revisions.length === 0) return { revisions: 0, bytes: 0 }\n await transaction\n .deleteFrom('documentRevision')\n .where(\n 'id',\n 'in',\n revisions.map((revision) => revision.id)\n )\n .execute()\n const freed = await unreferencedObjects(transaction)\n .select('byteSize')\n .where('id', 'in', uniq(revisions.map((revision) => revision.storageObjectId)))\n .execute()\n const bytes = sumBy(freed, (object) => Number(object.byteSize))\n if (bytes > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', bytes),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', workspaceId)\n .execute()\n }\n return { revisions: revisions.length, bytes }\n })\n }\n\n /** Deletes freed files from the object store, then their rows; a failure stays for next time. */\n async function sweepObjects(now: Date, batchSize: number, result: RevisionCompactionResult) {\n const freed = await unreferencedObjects(database)\n .select(['id', 'objectKey'])\n .where('createdAt', '<', new Date(now.getTime() - OBJECT_SWEEP_GRACE_MS))\n .limit(batchSize)\n .execute()\n for (const object of freed) {\n try {\n await objects.delete(object.objectKey)\n await database\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .execute()\n result.objectsDeleted++\n } catch (error) {\n result.failed++\n await report(`Deleting file ${object.id} failed`, error)\n }\n }\n }\n\n return {\n async compactRevisions(input) {\n const now = input.now ?? new Date()\n const before = new Date(now.getTime() - input.graceMs)\n const result: RevisionCompactionResult = {\n versionsPruned: await pruneVersions(now, input.batchSize),\n imagesReleased: 0,\n revisionsDeleted: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0,\n failed: 0\n }\n const candidates = await compactable(database, before)\n .select(['documentRevision.documentId', 'document.workspaceId'])\n .limit(input.batchSize)\n .execute()\n let capacity = input.batchSize\n for (const [documentId, rows] of Object.entries(\n groupBy(candidates, (row) => row.documentId)\n )) {\n const workspaceId = rows[0]?.workspaceId\n if (!workspaceId || capacity <= 0) continue\n try {\n const compacted = await compactDocument(documentId, workspaceId, before, capacity)\n capacity -= compacted.revisions\n result.revisionsDeleted += compacted.revisions\n result.bytesReclaimed += compacted.bytes\n } catch (error) {\n result.failed++\n await report(`Compacting document ${documentId} failed`, error, {\n documentId,\n workspaceId\n })\n }\n }\n // Compaction just freed the images of the saves it deleted; the release lets their grace pass.\n // A release that raced a save referring to an image fails whole and is tried next time.\n try {\n const images = await releaseUnusedImages(\n database,\n new Date(now.getTime() - IMAGE_RELEASE_GRACE_MS),\n input.batchSize\n )\n result.imagesReleased = images.released\n result.bytesReclaimed += images.bytes\n } catch (error) {\n result.failed++\n await report('Releasing unused images failed', error)\n }\n await sweepObjects(now, input.batchSize, result)\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { reportCloudError, type CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nexport type UploadCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n now?: Date\n}\n\nexport type UploadCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n}\n\nexport type UploadCleanupService = {\n cleanupExpiredUploads(options: UploadCleanupOptions): Promise<UploadCleanupResult>\n}\n\ntype ClaimedUpload = {\n id: string\n objectKey: string\n multipartUploadId: string | null\n}\n\nexport function createUploadCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n /** Where each upload cleanup couldn't remove is reported; a pass carries on with the rest. */\n reportError?: CloudErrorReporter\n): UploadCleanupService {\n const quota = createStorageQuotaService(database)\n return {\n async cleanupExpiredUploads(options) {\n const now = options.now ?? new Date()\n const staleBefore = new Date(now.getTime() - options.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const uploads = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('upload')\n .select(['id', 'objectKey', 'multipartUploadId'])\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('expiresAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'finalizing'),\n expression('finalizationStartedAt', '<=', staleBefore)\n ]),\n expression.and([\n expression('status', '=', 'cleaning'),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('expiresAt')\n .limit(options.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n const ids = candidates.map((upload) => upload.id)\n await transaction\n .updateTable('upload')\n .set({\n status: 'cleaning',\n finalizationStartedAt: null,\n cleanupClaimId: claimId,\n cleanupClaimedAt: now\n })\n .where('id', 'in', ids)\n .execute()\n return candidates\n })\n\n let cleaned = 0\n let failed = 0\n for (const upload of uploads) {\n try {\n await removeUploadObject(objects, upload)\n const result = await database\n .updateTable('upload')\n .set({\n status: 'abandoned',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) > 0) {\n await quota.release(upload.id)\n cleaned++\n }\n } catch (error) {\n failed++\n await reportCloudError(reportError, `Cleaning up upload ${upload.id} failed`, error, {\n source: 'cleanup',\n resources: { uploadId: upload.id }\n })\n await database\n .updateTable('upload')\n .set({\n status: 'pending',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .execute()\n }\n }\n return { claimed: uploads.length, cleaned, failed }\n }\n }\n}\n\n/**\n * Aborting covers a multipart upload that never finished; deleting covers one that did, such as an\n * upload whose commit lost to a newer revision after its parts were assembled.\n */\nasync function removeUploadObject(objects: ObjectStore, upload: ClaimedUpload): Promise<void> {\n if (upload.multipartUploadId) {\n await objects.abortUpload({ key: upload.objectKey, uploadId: upload.multipartUploadId })\n }\n await objects.delete(upload.objectKey)\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { createStorageLimitNoticeService } from '#cloud/server/quota'\nimport { createRateLimitCleanupService } from '#cloud/server/rate-limit/cleanup'\nimport type { Kysely } from 'kysely'\n\nimport { createDocumentCleanupService } from './documents'\nimport { createRevisionCompactionService } from './revisions'\nimport { createUploadCleanupService } from './uploads'\nimport type { CleanupPassOptions, CleanupServices } from './worker'\n\n/**\n * Every cleanup service, over a deployment's database and bucket. Each reports what it couldn't\n * clean through `reportError`, where a deployment tracks errors, and carries on with the rest.\n * With `email`, a deployment that sends mail, it also tells accounts their storage is full.\n */\nexport function createCleanupServices(\n config: Pick<CloudServerConfig, 'deployment' | 'publicURL' | 'billingEndpoint'>,\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n policy: CloudPolicy,\n reportError?: CloudErrorReporter,\n email?: TransactionalEmailService\n): CleanupServices {\n return {\n uploads: createUploadCleanupService(database, objects, reportError),\n documents: createDocumentCleanupService(database, objects, { reportError }),\n revisions: createRevisionCompactionService(database, objects, {\n policy,\n deploymentMode: config.deployment,\n reportError\n }),\n rateLimits: createRateLimitCleanupService(database),\n storageLimits: email\n ? createStorageLimitNoticeService(database, {\n policy,\n email,\n publicURL: config.publicURL,\n upgradable: config.billingEndpoint !== undefined,\n deploymentMode: config.deployment\n })\n : undefined\n }\n}\n\n/** The batch, lease, and retention a deployment sets for each cleanup pass. */\nexport function cleanupPassOptions(config: CloudServerConfig): CleanupPassOptions {\n return {\n batchSize: config.cleanupBatchSize,\n documentRetentionMs: config.documentRetentionMs,\n documentPurgeGraceMs: config.documentPurgeGraceMs,\n leaseDurationMs: config.cleanupLeaseDurationMs\n }\n}\n","import type { StorageLimitNoticeResult, StorageLimitNoticeService } from '#cloud/server/quota'\n\nimport { startPeriodicWorker } from '../worker/periodic'\nimport type { DocumentCleanupResult, DocumentCleanupService } from './documents'\nimport {\n REVISION_COMPACTION_GRACE_MS,\n type RevisionCompactionResult,\n type RevisionCompactionService\n} from './revisions'\nimport type { UploadCleanupResult, UploadCleanupService } from './uploads'\n\nexport type CleanupWorkerOptions = {\n batchSize: number\n documentRetentionMs: number\n /** How long a document deleted forever keeps its files; 0 destroys it at once. */\n documentPurgeGraceMs: number\n intervalMs: number\n leaseDurationMs: number\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type CleanupResult = {\n uploads: UploadCleanupResult\n documents: DocumentCleanupResult\n revisions: RevisionCompactionResult | null\n rateLimits: number\n storageLimits: StorageLimitNoticeResult | null\n}\n\nexport type CleanupServices = {\n documents: DocumentCleanupService\n uploads: UploadCleanupService\n revisions?: RevisionCompactionService\n rateLimits?: { cleanupExpired(before: Date): Promise<number> }\n /** Emails accounts whose storage became full; only where the server sends email. */\n storageLimits?: Pick<StorageLimitNoticeService, 'notifyStorageLimits'>\n}\n\nexport type CleanupWorker = {\n runOnce(): Promise<CleanupResult>\n stop(): Promise<void>\n}\n\nexport type CleanupPassOptions = Pick<\n CleanupWorkerOptions,\n 'batchSize' | 'documentRetentionMs' | 'documentPurgeGraceMs' | 'leaseDurationMs'\n>\n\n/** One cleanup pass, for runtimes that schedule passes themselves. */\nexport async function runCleanup(\n cleanup: CleanupServices,\n options: CleanupPassOptions\n): Promise<CleanupResult> {\n const uploads = await cleanup.uploads.cleanupExpiredUploads({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs\n })\n const documents = await cleanup.documents.cleanupDeletedDocuments({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs,\n retentionMs: options.documentRetentionMs,\n purgeGraceMs: options.documentPurgeGraceMs\n })\n const revisions = cleanup.revisions\n ? await cleanup.revisions.compactRevisions({\n batchSize: options.batchSize,\n graceMs: REVISION_COMPACTION_GRACE_MS\n })\n : null\n const rateLimits = cleanup.rateLimits\n ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))\n : 0\n // After documents, so storage they freed counts before anyone is told theirs is full.\n const storageLimits = cleanup.storageLimits\n ? await cleanup.storageLimits.notifyStorageLimits()\n : null\n return { uploads, documents, revisions, rateLimits, storageLimits }\n}\n\nexport function startCleanupWorker(\n cleanup: CleanupServices,\n options: CleanupWorkerOptions\n): CleanupWorker {\n return startPeriodicWorker({\n intervalMs: options.intervalMs,\n signal: options.signal,\n onError: options.onError,\n run: () => runCleanup(cleanup, options)\n })\n}\n","import type { DocumentSummary } from '#cloud/contract'\nimport type { DocumentDatabase, DocumentSummaryRow } from '#cloud/server/documents/repository'\n\nconst SUMMARY_COLUMNS = [\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n] as const\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function documentSummary(row: DocumentSummaryRow): DocumentSummary {\n return {\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n}\n\nexport async function getDocumentSummaryRow(\n database: DocumentDatabase,\n documentId: string\n): Promise<DocumentSummaryRow | undefined> {\n return database\n .selectFrom('document')\n .select(SUMMARY_COLUMNS)\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .where('disabledAt', 'is', null)\n .executeTakeFirst()\n}\n\n/**\n * A document the server still keeps, even one in Trash or taken down, which only a deployment\n * administrator may reach; ordinary access goes through `getDocumentSummaryRow`.\n */\nexport async function getRetainedDocumentSummaryRow(\n database: DocumentDatabase,\n documentId: string\n): Promise<DocumentSummaryRow | undefined> {\n return database\n .selectFrom('document')\n .select(SUMMARY_COLUMNS)\n .where('id', '=', documentId)\n .executeTakeFirst()\n}\n","import type { DocumentSummary, SharedDocument, WorkspaceRole } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { CreateDocumentRecord } from '#cloud/server/documents/types'\nimport { uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\nimport * as v from 'valibot'\n\nimport { resolveDocumentAccess } from './access'\nimport { documentSummary, getDocumentSummaryRow } from './summary'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n\nexport type DocumentDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport type DocumentSummaryRow = Omit<DocumentSummary, 'createdAt' | 'updatedAt'> & {\n createdAt: Date | string\n updatedAt: Date | string\n}\n\nexport async function workspaceRole(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceRole | undefined> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', userId)\n .executeTakeFirst()\n return member?.role\n}\n\nexport async function listDocuments(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<DocumentSummary[] | undefined> {\n if (!(await workspaceRole(database, userId, workspaceId))) return undefined\n const rows = await database\n .selectFrom('document')\n .select([\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n ])\n .where('workspaceId', '=', workspaceId)\n .where('deletedAt', 'is', null)\n .where('disabledAt', 'is', null)\n .orderBy('updatedAt', 'desc')\n .execute()\n return rows.map(documentSummary)\n}\n\n/** Documents granted to the person directly that live in workspaces they are not a member of. */\nexport async function listSharedDocuments(\n database: DocumentDatabase,\n userId: string\n): Promise<SharedDocument[]> {\n const rows = await database\n .selectFrom('documentGrant')\n .innerJoin('document', 'document.id', 'documentGrant.documentId')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select([\n 'document.id',\n 'document.workspaceId',\n 'document.name',\n 'document.kind',\n 'document.currentRevisionId',\n 'document.version',\n 'document.createdAt',\n 'document.updatedAt',\n 'workspace.name as workspaceName',\n 'documentGrant.permission',\n 'documentGrant.createdAt as sharedAt',\n 'documentGrant.createdBy'\n ])\n .where('documentGrant.userId', '=', userId)\n .where('documentGrant.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n .where('document.disabledAt', 'is', null)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', userId)\n )\n )\n )\n .orderBy('document.updatedAt', 'desc')\n .execute()\n // Grants can be made by operator tools whose IDs are not accounts, so only UUIDs are looked up.\n const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(uuidSchema, id))\n const names = new Map(\n granters.length === 0\n ? []\n : (\n await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', granters)\n .execute()\n ).map((user) => [user.id, user.name] as const)\n )\n return rows.map(({ workspaceName, permission, sharedAt, createdBy, ...row }) => {\n const sharedByName = names.get(createdBy)\n return {\n ...documentSummary(row),\n workspaceName,\n permission,\n sharedBy: sharedByName === undefined ? null : { name: sharedByName },\n sharedAt: sharedAt instanceof Date ? sharedAt.toISOString() : sharedAt\n }\n })\n}\n\nexport async function findDocument(\n database: DocumentDatabase,\n userId: string,\n documentId: string\n): Promise<(DocumentSummary & { role: WorkspaceRole }) | undefined> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) return undefined\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) return undefined\n const role: WorkspaceRole = access.permission === 'edit' ? 'editor' : 'viewer'\n return { ...documentSummary(row), role }\n}\n\nexport async function insertDocument(\n database: DocumentDatabase,\n input: CreateDocumentRecord\n): Promise<void> {\n await database.insertInto('document').values(input).execute()\n}\n","import type { TrashedDocument, WorkspaceRole } from '#cloud/contract'\nimport { documentRoleCan, workspaceRoleCan } from '#cloud/server/auth/access-control'\nimport { createDocumentCleanupService } from '#cloud/server/cleanup'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { compact, uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\nimport * as v from 'valibot'\n\nimport { trashedDocumentAllows } from './access'\nimport { DocumentForbiddenError, DocumentNotFoundError, DocumentPurgeFailedError } from './errors'\nimport { markPurged } from './purge'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n\nconst WORKSPACE_ROLES: WorkspaceRole[] = ['admin', 'editor', 'viewer']\n\n/** The workspace roles whose members may delete any document there, and so restore it. */\nconst RESTORING_ROLES = WORKSPACE_ROLES.filter((role) =>\n workspaceRoleCan(role, { document: ['delete'] })\n)\n\nexport type DocumentTrashOptions = {\n /** How long a deleted document stays in Trash before the cleanup worker deletes it for good. */\n retentionMs: number\n /**\n * How long a document deleted forever keeps its files, out of sight, before cleanup destroys\n * it; 0 destroys it at once.\n */\n purgeGraceMs: number\n /** How long a cleanup claim holds before another pass may take the document over. */\n leaseDurationMs: number\n /** Where destroying a document deleted forever with no grace reports a failure. */\n reportError?: CloudErrorReporter\n}\n\n/** A deployment's defaults: 30 days in Trash, 7 days' grace, and a five-minute cleanup lease. */\nexport const DEFAULT_TRASH_OPTIONS: DocumentTrashOptions = {\n retentionMs: 30 * 24 * 60 * 60_000,\n purgeGraceMs: 7 * 24 * 60 * 60_000,\n leaseDurationMs: 5 * 60_000\n}\n\n/** The names of the accounts these IDs belong to; IDs that are not accounts are left out. */\nasync function accountNames(\n database: Kysely<CloudDatabase>,\n ids: (string | null)[]\n): Promise<Map<string, string>> {\n const accounts = uniq(compact(ids)).filter((id) => v.is(uuidSchema, id))\n if (accounts.length === 0) return new Map()\n const users = await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', accounts)\n .execute()\n return new Map(users.map((user) => [user.id, user.name]))\n}\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\n/**\n * Trash: documents deleted in the person's workspaces that cleanup has not removed yet. Whoever\n * may delete a document may restore it; its owner and workspace administrators may also delete\n * it forever, which takes it out of Trash and off their storage at once (see `markPurged`).\n */\nexport function createDocumentTrash(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: DocumentTrashOptions\n) {\n const cleanup = createDocumentCleanupService(database, objects, {\n reportError: options.reportError\n })\n\n /** Deleted after this moment, a document is still in Trash. */\n function retainedSince(now: Date): Date {\n return new Date(now.getTime() - options.retentionMs)\n }\n\n return {\n async list(userId: string, now = new Date()): Promise<TrashedDocument[]> {\n const rows = await database\n .selectFrom('document')\n .innerJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select([\n 'document.id',\n 'document.workspaceId',\n 'workspace.name as workspaceName',\n 'document.name',\n 'document.kind',\n 'document.createdBy',\n 'document.deletedAt',\n 'document.deletedBy',\n 'workspaceMember.role'\n ])\n .where('document.deletedAt', '>', retainedSince(now))\n .where('document.purgedAt', 'is', null)\n .where('document.cleanupClaimId', 'is', null)\n .where('document.disabledAt', 'is', null)\n .where((expression) =>\n expression.or([\n expression('workspaceMember.role', 'in', RESTORING_ROLES),\n expression('document.createdBy', '=', userId)\n ])\n )\n .orderBy('document.deletedAt', 'desc')\n .execute()\n const names = await accountNames(\n database,\n rows.map((row) => row.deletedBy)\n )\n return rows.flatMap(({ createdBy, deletedAt, deletedBy, role, ...row }) => {\n if (deletedAt === null) return []\n const deleted = new Date(deletedAt)\n const deleterName = deletedBy === null ? undefined : names.get(deletedBy)\n return {\n ...row,\n deletedAt: toISOString(deletedAt),\n deletedBy: deleterName === undefined ? null : { name: deleterName },\n purgeAt: new Date(deleted.getTime() + options.retentionMs).toISOString(),\n canPurge:\n workspaceRoleCan(role, { document: ['purge'] }) ||\n (createdBy === userId && documentRoleCan('owner', { document: ['purge'] }))\n }\n })\n },\n\n /** Puts a document back where it was; it counted toward storage all along, so no quota check. */\n async restore(userId: string, documentId: string, now = new Date()): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await lockInTrash(transaction, userId, documentId, now)\n await transaction\n .updateTable('document')\n // Changed now, so devices that deleted it stop hiding it (see `reconcileStorageDocuments`).\n .set({ deletedAt: null, deletedBy: null, updatedAt: now })\n .where('id', '=', documentId)\n .execute()\n })\n },\n\n /**\n * Deletes a document in Trash forever, for the person: it leaves Trash and their storage now,\n * and cleanup destroys it once the deployment's grace passes, or at once without one.\n */\n async purge(userId: string, documentId: string, now = new Date()): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await lockInTrash(transaction, userId, documentId, now)\n if (!(await trashedDocumentAllows(transaction, userId, documentId, 'purge'))) {\n throw new DocumentForbiddenError()\n }\n await markPurged(transaction, [documentId], userId, now)\n })\n if (options.purgeGraceMs > 0) return\n try {\n // A save still in flight holds it for the next cleanup pass; it is out of Trash already.\n await cleanup.destroyPurgedDocument(documentId, {\n leaseDurationMs: options.leaseDurationMs,\n now\n })\n } catch (error) {\n throw new DocumentPurgeFailedError(`Document ${documentId} could not be destroyed`, {\n cause: error\n })\n }\n }\n }\n\n /**\n * Holds a document in Trash until the transaction ends: deleted, not forever, inside retention,\n * and not being cleaned, by someone who may restore it; anything else is not found.\n */\n async function lockInTrash(\n transaction: Transaction<CloudDatabase>,\n userId: string,\n documentId: string,\n now: Date\n ): Promise<void> {\n const document = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'purgedAt', 'cleanupClaimId'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n const inTrash =\n document?.deletedAt != null &&\n document.purgedAt === null &&\n document.cleanupClaimId === null &&\n new Date(document.deletedAt) > retainedSince(now)\n if (!inTrash || !(await trashedDocumentAllows(transaction, userId, documentId, 'delete'))) {\n throw new DocumentNotFoundError()\n }\n }\n}\n\nexport type DocumentTrash = ReturnType<typeof createDocumentTrash>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport type { CloudPolicy } from './policy'\nimport { workspacePolicyContext } from './workspace'\n\n/**\n * Whether the owner of a workspace, or of a document's workspace, holds as much as their plan's\n * storage allows or more. Their workspaces are then read-only until they free space or their plan\n * grows: documents open and download, and can be deleted, but take no edits, uploads, or new\n * documents. A plan that shrinks below what an account holds, as when a subscription lapses,\n * reaches this the same way as filling it.\n */\nexport async function storageLimitReached(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy | undefined,\n target: { workspaceId: string } | { documentId: string },\n deploymentMode: 'official' | 'self-hosted' = 'self-hosted'\n): Promise<boolean> {\n if (!policy) return false\n const context = await workspacePolicyContext(database, target, { deploymentMode })\n if (!context) return false\n const maximum = await policy.number(\n CLOUD_FEATURE_KEYS.maximumStorageBytes,\n Number.MAX_SAFE_INTEGER,\n context\n )\n if (maximum === Number.MAX_SAFE_INTEGER) return false\n const usage = await createStorageQuotaService(database).snapshot(context.workspaceId)\n return usage !== null && usage.committedBytes >= maximum\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { DocumentServiceOptions } from '#cloud/server/documents/service'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport { storageLimitReached } from '#cloud/server/policy/storage'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport { StorageQuotaExceededError } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\n/**\n * The document `userId` may write to, and how large one file and its owner's storage may be for\n * this save: technical limits, tightened by the owner's plan. An owner who holds their whole\n * storage allowance or more is read-only, so nothing of theirs takes a save, however small.\n */\nexport async function writableDocument(\n database: Kysely<CloudDatabase>,\n options: Pick<DocumentServiceOptions, 'policy' | 'technicalMaximumUploadBytes'>,\n userId: string,\n documentId: string\n) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n // Access was resolved just above, so the document is read without resolving it again.\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) throw new DocumentNotFoundError()\n const document = documentSummary(row)\n const policyContext = await workspacePolicyContext(\n database,\n { documentId },\n { actorId: userId, deploymentMode: 'self-hosted' }\n )\n if (!policyContext) throw new DocumentNotFoundError()\n if (await storageLimitReached(database, options.policy, { documentId })) {\n throw new StorageQuotaExceededError('The owner holds their whole storage allowance')\n }\n const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER\n const maximumFileBytes = Math.min(\n technicalMaximum,\n options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumFileBytes,\n technicalMaximum,\n policyContext\n )\n : technicalMaximum\n )\n const maximumStorageBytes = options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumStorageBytes,\n Number.MAX_SAFE_INTEGER,\n policyContext\n )\n : Number.MAX_SAFE_INTEGER\n return {\n document,\n maximumFileBytes,\n maximumStorageBytes:\n maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport type { Transaction } from 'kysely'\n\n/** How long the newest version may be old before a save keeps the state it replaces. */\nexport const CHECKPOINT_INTERVAL_MS = 30 * 60_000\n\n/** Keeps a revision in the history, unless a version already keeps it. */\nexport async function keepRevision(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n revisionId: string\n createdBy: string\n createdAt: Date\n restoredFromVersionId?: string\n }\n): Promise<void> {\n await transaction\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId: input.documentId,\n revisionId: input.revisionId,\n kind: 'checkpoint',\n name: null,\n description: null,\n createdBy: input.createdBy,\n restoredFromVersionId: input.restoredFromVersionId ?? null,\n createdAt: input.createdAt\n })\n .onConflict((conflict) => conflict.column('revisionId').doNothing())\n .execute()\n}\n\n/**\n * Records the history's checkpoints as a save lands: the document's first save, and the state a\n * save replaces once the newest version is half an hour old. Each stretch of editing, and how the\n * document was left at the end of every session, stays in the history; the saves between them are\n * compacted later. Whether the history gained a checkpoint.\n */\nexport async function recordCheckpoint(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n previousRevisionId: string | null\n revisionId: string\n userId: string\n now: Date\n }\n): Promise<boolean> {\n if (!input.previousRevisionId) {\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.revisionId,\n createdBy: input.userId,\n createdAt: input.now\n })\n return true\n }\n const newest = await transaction\n .selectFrom('documentVersion')\n .select('createdAt')\n .where('documentId', '=', input.documentId)\n .orderBy('createdAt', 'desc')\n .limit(1)\n .executeTakeFirst()\n if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) {\n return false\n }\n const previous = await transaction\n .selectFrom('documentRevision')\n .select(['createdBy', 'createdAt'])\n .where('id', '=', input.previousRevisionId)\n .executeTakeFirst()\n if (!previous) return false\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.previousRevisionId,\n createdBy: previous.createdBy,\n createdAt: previous.createdAt\n })\n return true\n}\n\n/**\n * Tells the document's live rooms that its history changed. The change stands whatever the hook\n * does; an open list that misses it loads the history again when it is next opened.\n */\nexport function announceVersions(\n onVersionsChanged: ((documentId: string) => void) | undefined,\n documentId: string\n): void {\n try {\n onVersionsChanged?.(documentId)\n } catch (error) {\n logCloud('error', 'Announcing a version history change failed', { error: loggedError(error) })\n }\n}\n","import type {\n CommitImageUploadsInput,\n CommitUploadInput,\n CreateUploadInput,\n DocumentSummary,\n ImageUploadOffer,\n RequestImageUploadsInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport type { DocumentImages } from '#cloud/server/documents/images'\nimport { writableDocument } from '#cloud/server/documents/limits'\nimport { findDocument } from '#cloud/server/documents/repository'\nimport type { DocumentServiceOptions } from '#cloud/server/documents/service'\nimport type { CreateDocumentUploadResult } from '#cloud/server/documents/types'\nimport { announceVersions, recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'\nimport type { ObjectStore, StoredObject } from '#cloud/server/objects'\nimport { storageLimitReached } from '#cloud/server/policy/storage'\nimport { StorageQuotaExceededError, type StorageQuotaService } from '#cloud/server/quota'\nimport { isUndefined, limitAsync, omitBy, uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nconst UPLOAD_LIFETIME_MS = 15 * 60 * 1000\n/** How many of a save's images are checked and landed at once. */\nconst IMAGE_COMMIT_CONCURRENCY = 8\n\n/** Whether the stored object is the file the upload declared, which the commit names again. */\nfunction matchesUpload(\n stored: { checksum: string; byteSize: number; contentType: string },\n upload: { checksum: string; byteSize: number | string | bigint; contentType: string }\n): boolean {\n return (\n stored.checksum === upload.checksum &&\n stored.byteSize === Number(upload.byteSize) &&\n stored.contentType === upload.contentType\n )\n}\n\n/**\n * Saving a document: uploads of a new revision and of the images it names, reserved against the\n * workspace's storage, then committed once the store holds what each declared, landing the\n * revision as the document's current one.\n */\nexport function createDocumentUploads(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n {\n quota,\n images,\n options\n }: {\n quota: StorageQuotaService\n images: DocumentImages\n options: Pick<\n DocumentServiceOptions,\n 'policy' | 'technicalMaximumUploadBytes' | 'onVersionsChanged'\n >\n }\n) {\n /**\n * Refuses to land an upload once its document's owner holds their whole storage allowance, as\n * when their plan shrank after the upload was offered; an upload already landed is not landed\n * again, so retrying one stays as it was.\n */\n async function refuseAtStorageLimit(documentId: string): Promise<void> {\n if (await storageLimitReached(database, options.policy, { documentId })) {\n throw new StorageQuotaExceededError('The owner holds their whole storage allowance')\n }\n }\n\n /**\n * Makes a committed upload the document's current revision, unless it already was, and records\n * the checkpoint the save adds, if any. Whether the history gained one.\n */\n async function landRevision(\n transaction: Transaction<CloudDatabase>,\n {\n userId,\n uploadId,\n upload,\n stored,\n revisionId,\n storageObjectId,\n images: revisionImages,\n name,\n kind\n }: {\n userId: string\n uploadId: string\n upload: {\n documentId: string\n workspaceId: string\n baseRevisionId: string | null\n objectKey: string\n }\n stored: { checksum: string; byteSize: number; contentType: string }\n revisionId: string\n storageObjectId: string\n images: CommitUploadInput['images']\n name: CommitUploadInput['name']\n kind: CommitUploadInput['kind']\n }\n ): Promise<boolean> {\n const lockedUpload = await transaction\n .selectFrom('upload')\n .select('status')\n .where('id', '=', uploadId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (lockedUpload.status === 'committed') return false\n if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()\n const document = await transaction\n .selectFrom('document')\n .select(['currentRevisionId'])\n .where('id', '=', upload.documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (document.currentRevisionId !== upload.baseRevisionId) {\n throw new DocumentConflictError()\n }\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: upload.objectKey,\n checksum: stored.checksum,\n byteSize: stored.byteSize,\n contentType: stored.contentType\n })\n .execute()\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: upload.documentId,\n parentRevisionId: upload.baseRevisionId,\n storageObjectId,\n createdBy: userId\n })\n .execute()\n const attached = await images.attachInTransaction(transaction, {\n workspaceId: upload.workspaceId,\n revisionId,\n images: revisionImages\n })\n if (!attached) throw new UploadInvalidError()\n await transaction\n .updateTable('document')\n .set({\n // A revision may also retitle its document, or say the file it holds is a board.\n ...omitBy({ name, kind }, isUndefined),\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1)\n })\n .where('id', '=', upload.documentId)\n .execute()\n const checkpointed = await recordCheckpoint(transaction, {\n documentId: upload.documentId,\n previousRevisionId: document.currentRevisionId,\n revisionId,\n userId,\n now: new Date()\n })\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', uploadId)\n .execute()\n await quota.commitInTransaction(transaction, uploadId)\n return checkpointed\n }\n\n /** What committing an upload reads of it and its document. */\n function selectUploads() {\n return database\n .selectFrom('upload')\n .innerJoin('document', 'document.id', 'upload.documentId')\n .select([\n 'upload.id',\n 'upload.documentId',\n 'upload.kind',\n 'document.workspaceId',\n 'upload.baseRevisionId',\n 'upload.objectKey',\n 'upload.checksum',\n 'upload.byteSize',\n 'upload.contentType',\n 'upload.multipartUploadId',\n 'upload.status',\n 'upload.expiresAt'\n ])\n }\n type UploadRow = Awaited<ReturnType<ReturnType<typeof selectUploads>['executeTakeFirstOrThrow']>>\n\n /**\n * Claims a pending upload, completes it when it came in parts, checks the store holds the file\n * it declared, and lands it with `land`. An upload that fails goes back to pending, so its\n * commit can be tried again.\n */\n async function finalizeUpload<T>(\n upload: UploadRow,\n multipart: CommitUploadInput['multipart'],\n land: (stored: StoredObject) => Promise<T>\n ): Promise<T> {\n if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {\n throw new UploadInvalidError()\n }\n const claimed = await database\n .updateTable('upload')\n .set({ status: 'finalizing', finalizationStartedAt: new Date() })\n .where('id', '=', upload.id)\n .where('status', '=', 'pending')\n .returning('id')\n .executeTakeFirst()\n if (!claimed) throw new UploadInvalidError()\n try {\n if (multipart) {\n if (\n !objects.capabilities.multipartUpload ||\n multipart.uploadId !== upload.multipartUploadId\n ) {\n throw new UploadInvalidError()\n }\n await objects.completeUpload({\n key: upload.objectKey,\n uploadId: multipart.uploadId,\n parts: multipart.parts\n })\n }\n const stored = await objects.head(upload.objectKey)\n if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()\n return await land(stored)\n } catch (error) {\n await database\n .updateTable('upload')\n .set({ status: 'pending', finalizationStartedAt: null })\n .where('id', '=', upload.id)\n .where('status', '=', 'finalizing')\n .execute()\n throw error\n }\n }\n\n function landImage(upload: UploadRow, stored: StoredObject): Promise<void> {\n return database.transaction().execute((transaction) =>\n images.landInTransaction(transaction, {\n uploadId: upload.id,\n workspaceId: upload.workspaceId,\n objectKey: upload.objectKey,\n stored\n })\n )\n }\n\n async function commitUpload(\n userId: string,\n uploadId: string,\n input: CommitUploadInput\n ): Promise<DocumentSummary> {\n const upload = await selectUploads()\n .where('upload.id', '=', uploadId)\n .where('upload.createdBy', '=', userId)\n .executeTakeFirst()\n if (!upload) throw new DocumentNotFoundError()\n const access = await resolveDocumentAccess(database, userId, upload.documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n if (input.checksum !== upload.checksum) throw new UploadInvalidError()\n if (upload.status !== 'committed') {\n await refuseAtStorageLimit(upload.documentId)\n const checkpointed =\n upload.kind === 'image'\n ? await finalizeUpload(upload, input.multipart, (stored) =>\n landImage(upload, stored).then(() => false)\n )\n : await finalizeUpload(upload, input.multipart, (stored) =>\n database.transaction().execute((transaction) =>\n landRevision(transaction, {\n userId,\n uploadId,\n upload,\n stored,\n revisionId: crypto.randomUUID(),\n storageObjectId: crypto.randomUUID(),\n images: input.images,\n name: input.name,\n kind: input.kind\n })\n )\n )\n if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)\n }\n const document = await findDocument(database, userId, upload.documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n }\n\n return {\n async createUpload(\n userId: string,\n documentId: string,\n input: CreateUploadInput\n ): Promise<CreateDocumentUploadResult> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (document.currentRevisionId !== input.baseRevisionId) throw new DocumentConflictError()\n if (input.byteSize > maximumFileBytes) throw new UploadInvalidError()\n const uploadId = crypto.randomUUID()\n const objectKey = `documents/${document.workspaceId}/${documentId}/uploads/${uploadId}.fig`\n const expiresAt = new Date(Date.now() + UPLOAD_LIFETIME_MS)\n await database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('upload')\n .values({\n id: uploadId,\n documentId,\n baseRevisionId: input.baseRevisionId,\n objectKey,\n checksum: input.checksum,\n byteSize: input.byteSize,\n contentType: input.contentType,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: userId,\n expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: document.workspaceId,\n uploadId,\n bytes: input.byteSize,\n expiresAt,\n maximumBytes: maximumStorageBytes\n })\n })\n let objectUpload\n try {\n objectUpload = await objects.createUpload({\n key: objectKey,\n byteSize: input.byteSize,\n checksum: input.checksum,\n contentType: input.contentType,\n expiresAt\n })\n } catch (error) {\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .execute()\n throw error\n }\n if (objectUpload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: objectUpload.uploadId })\n .where('id', '=', uploadId)\n .execute()\n }\n return { id: uploadId, upload: objectUpload }\n },\n\n /** Uploads for the images a save of the document will name that its workspace lacks. */\n async requestImageUploads(\n userId: string,\n documentId: string,\n input: RequestImageUploadsInput\n ): Promise<{ uploads: ImageUploadOffer[] }> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (input.images.some((image) => image.byteSize > maximumFileBytes)) {\n throw new UploadInvalidError()\n }\n return {\n uploads: await images.requestUploads({\n userId,\n documentId,\n workspaceId: document.workspaceId,\n images: input.images,\n expiresAt: new Date(Date.now() + UPLOAD_LIFETIME_MS),\n maximumBytes: maximumStorageBytes\n })\n }\n },\n commitUpload,\n\n /**\n * Commits the image uploads a save asked for in one request, however many there are: each\n * must be an image upload this person made for the document.\n */\n async commitImageUploads(\n userId: string,\n documentId: string,\n uploads: CommitImageUploadsInput['uploads']\n ): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n const ids = uniq(uploads.map((upload) => upload.uploadId))\n const rows = new Map(\n (\n await selectUploads()\n .where('upload.id', 'in', ids)\n .where('upload.documentId', '=', documentId)\n .where('upload.createdBy', '=', userId)\n .execute()\n ).map((row) => [row.id, row])\n )\n if (rows.size !== ids.length || [...rows.values()].some((row) => row.kind !== 'image')) {\n throw new UploadInvalidError()\n }\n for (const commit of uploads) {\n if (rows.get(commit.uploadId)?.checksum !== commit.checksum) throw new UploadInvalidError()\n }\n if ([...rows.values()].some((row) => row.status !== 'committed')) {\n await refuseAtStorageLimit(documentId)\n }\n // Each image is its own object, so a few are checked and landed at once, each once however\n // often the request names it.\n const land = limitAsync(\n (upload: UploadRow, multipart: CommitUploadInput['multipart']) =>\n finalizeUpload(upload, multipart, (stored) => landImage(upload, stored)),\n IMAGE_COMMIT_CONCURRENCY\n )\n await Promise.all(\n uniqBy(uploads, (commit) => commit.uploadId).map(async (commit) => {\n const upload = rows.get(commit.uploadId)\n if (!upload) throw new UploadInvalidError()\n if (upload.status !== 'committed') await land(upload, commit.multipart)\n })\n )\n }\n }\n}\n","import type {\n CreateDocumentInput,\n DocumentDownload,\n DocumentSummary,\n SharedDocument\n} from '#cloud/contract'\nimport { workspaceRoleCan } from '#cloud/server/auth/access-control'\nimport { createUploadCleanupService } from '#cloud/server/cleanup'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n canDeleteDocument,\n canEditDocument,\n resolveDocumentAccess\n} from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport {\n createDocumentImages,\n currentImageUsage,\n DOWNLOAD_LIFETIME_MS,\n documentImageLinks,\n revisionImageDownloads\n} from '#cloud/server/documents/images'\nimport {\n findDocument,\n insertDocument,\n listDocuments,\n listSharedDocuments,\n workspaceRole\n} from '#cloud/server/documents/repository'\nimport {\n documentSummary,\n getDocumentSummaryRow,\n getRetainedDocumentSummaryRow\n} from '#cloud/server/documents/summary'\nimport {\n createDocumentTrash,\n DEFAULT_TRASH_OPTIONS,\n type DocumentTrashOptions\n} from '#cloud/server/documents/trash'\nimport { createDocumentUploads } from '#cloud/server/documents/uploads'\nimport type { CloudErrorReporter } from '#cloud/server/errors'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { storageLimitReached } from '#cloud/server/policy/storage'\nimport { createStorageQuotaService, StorageQuotaExceededError } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nexport type DocumentServiceOptions = {\n policy?: CloudPolicy\n technicalMaximumUploadBytes?: number\n /** Called once a save adds a checkpoint to the document's history. */\n onVersionsChanged?: (documentId: string) => void\n /** How long Trash keeps documents, the grace of one deleted forever, and the cleanup lease. */\n trash?: DocumentTrashOptions\n /** Where cleanup the service runs itself, such as of expired uploads, reports a failure. */\n reportError?: CloudErrorReporter\n}\n\nexport function createDocumentService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: DocumentServiceOptions = {}\n) {\n const cleanup = createUploadCleanupService(database, objects, options.reportError)\n const quota = createStorageQuotaService(database)\n const images = createDocumentImages(database, objects, quota)\n const trash = createDocumentTrash(database, objects, options.trash ?? DEFAULT_TRASH_OPTIONS)\n const uploads = createDocumentUploads(database, objects, { quota, images, options })\n /** Links for images a live room names, by checksum. */\n async function imageLinksOf(documentId: string, checksums: string[]) {\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n images: await documentImageLinks(database, objects, { documentId, checksums, expiresAt })\n }\n }\n\n async function createDownload(\n documentId: string,\n lookup: typeof getDocumentSummaryRow = getDocumentSummaryRow\n ): Promise<DocumentDownload> {\n const row = await lookup(database, documentId)\n if (!row?.currentRevisionId) throw new DocumentNotFoundError()\n const document: DocumentSummary = documentSummary(row)\n const revision = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.id as revisionId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', document.currentRevisionId)\n .where('documentRevision.documentId', '=', documentId)\n .executeTakeFirst()\n if (!revision) throw new DocumentNotFoundError()\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document,\n revisionId: revision.revisionId,\n byteSize: Number(revision.byteSize),\n checksum: revision.checksum,\n contentType: revision.contentType,\n download: await objects.createDownload({ key: revision.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, revision.revisionId, expiresAt)\n }\n }\n\n return {\n async cleanupExpiredUploads(now = new Date()): Promise<number> {\n const result = await cleanup.cleanupExpiredUploads({\n batchSize: 100,\n leaseDurationMs: 5 * 60 * 1000,\n now\n })\n if (result.failed > 0) throw new Error('One or more expired uploads could not be cleaned')\n return result.cleaned\n },\n\n list(userId: string, workspaceId: string): Promise<DocumentSummary[] | undefined> {\n return listDocuments(database, userId, workspaceId)\n },\n\n listShared(userId: string): Promise<SharedDocument[]> {\n return listSharedDocuments(database, userId)\n },\n\n /** Trash: list what the person may restore, restore it, or delete it for good. */\n trash,\n\n async usage(userId: string, workspaceId: string) {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n const result = await database\n .selectFrom('document')\n .leftJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')\n .leftJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select((expression) => [\n expression.fn.count('document.id').as('documentCount'),\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('document.workspaceId', '=', workspaceId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirstOrThrow()\n const shared = await currentImageUsage(database, workspaceId)\n return {\n bytesUsed: Number(result.bytesUsed) + shared.bytesUsed,\n objectCount: Number(result.objectCount) + shared.objectCount,\n documentCount: Number(result.documentCount)\n }\n },\n\n async access(userId: string, documentId: string) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return access\n },\n\n async downloadShared(documentId: string): Promise<DocumentDownload> {\n return createDownload(documentId)\n },\n\n /**\n * A document as it is now for a deployment administrator, taken down or in Trash included,\n * to look at what was reported or blocked; the caller checks the administrator.\n */\n async downloadRetained(documentId: string): Promise<DocumentDownload> {\n return createDownload(documentId, getRetainedDocumentSummaryRow)\n },\n\n /** Links for images a live room names, for someone who may view the document. */\n async imageLinks(userId: string, documentId: string, checksums: string[]) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return imageLinksOf(documentId, checksums)\n },\n\n /** Links for images a live room names, for a guest a share already let in. */\n imageLinksShared(documentId: string, checksums: string[]) {\n return imageLinksOf(documentId, checksums)\n },\n\n async download(userId: string, documentId: string): Promise<DocumentDownload> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return createDownload(documentId)\n },\n\n async remove(userId: string, documentId: string): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access) || !(await canDeleteDocument(database, userId, documentId))) {\n throw new DocumentForbiddenError()\n }\n await database\n .updateTable('document')\n .set({ deletedAt: new Date(), deletedBy: userId })\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .execute()\n },\n\n async create(\n userId: string,\n workspaceId: string,\n input: CreateDocumentInput\n ): Promise<DocumentSummary> {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!workspaceRoleCan(role, { document: ['create'] })) throw new DocumentForbiddenError()\n if (await storageLimitReached(database, options.policy, { workspaceId })) {\n throw new StorageQuotaExceededError('The owner holds their whole storage allowance')\n }\n const documentId = input.id ?? crypto.randomUUID()\n await insertDocument(database, {\n id: documentId,\n workspaceId,\n name: input.name,\n kind: input.kind,\n createdBy: userId\n })\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n },\n /** Saving: uploads of revisions and their images, and committing them. */\n ...uploads\n }\n}\n\nexport type DocumentService = ReturnType<typeof createDocumentService>\n","import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'\nimport { InvitationLimitError } from '#cloud/server/invitations'\nimport {\n DocumentShareInvalidError,\n DocumentShareSignInRequiredError,\n InvitationDeliveryError\n} from '#cloud/server/sharing/errors'\nimport { WorkspaceInvitationInvalidError } from '#cloud/server/workspaces/members'\nimport type { Context } from 'hono'\n\nexport function sharingDomainError(context: Context, error: unknown): Response | null {\n if (\n error instanceof DocumentNotFoundError ||\n error instanceof DocumentShareInvalidError ||\n error instanceof WorkspaceInvitationInvalidError\n ) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n if (error instanceof InvitationDeliveryError) {\n return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)\n }\n if (error instanceof InvitationLimitError) {\n return context.json({ error: { code: 'rate_limited' as const } }, 429)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return null\n}\n\nexport async function sharingRoute<T>(\n context: Context,\n action: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n const response = sharingDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n","import type { FileDocumentReportInput } from '#cloud/contract'\nimport type { EmailLocale } from '#cloud/email'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport type { Kysely } from 'kysely'\n\nimport { DAY_MS } from '@open-pencil/std/timing'\n\n/**\n * How many reports one person, or guest, may file about one link in a day, and how many a link\n * may gather from everyone, since a guest names themselves and could otherwise flood the queue.\n */\nexport const DOCUMENT_REPORT_BUDGET = {\n windowMs: DAY_MS,\n perReporter: 3,\n perShare: 50\n} as const\n\n/** How much of a description an administrator's email quotes; the console shows all of it. */\nconst EMAIL_DESCRIPTION_CHARACTERS = 500\n\n/** A report past the reporter's or the link's daily budget. */\nexport class DocumentReportLimitError extends Error {\n override readonly name = 'DocumentReportLimitError'\n}\n\nexport type DocumentReportServiceOptions = {\n sharing: Pick<DocumentSharingService, 'resolveShare'>\n email?: TransactionalEmailService\n /** Who hears of a new report: the deployment's administrators. */\n adminRecipients: readonly string[]\n publicURL: string\n}\n\nexport function createDocumentReportService(\n database: Kysely<CloudDatabase>,\n options: DocumentReportServiceOptions\n) {\n return {\n /**\n * Files a report about the document a share link opens, for someone the link lets in, and\n * tells the deployment's administrators. It answers nothing about the document, so a report\n * never tells its reporter more than the link already did.\n */\n async file(\n shareId: string,\n input: FileDocumentReportInput,\n actor?: CloudActor,\n /** The language the reporter's browser asked for, to reply in without an account's own. */\n replyLocale: EmailLocale | null = null\n ): Promise<void> {\n const resolved = await options.sharing.resolveShare(\n shareId,\n { secret: input.secret, guestId: input.guestId },\n actor\n )\n const reporterUserId = actor?.userId ?? null\n const reporterGuestId = actor ? null : (input.guestId ?? null)\n const since = new Date(Date.now() - DOCUMENT_REPORT_BUDGET.windowMs)\n await database.transaction().execute(async (transaction) => {\n const [byReporter, byShare] = await Promise.all([\n transaction\n .selectFrom('documentReport')\n .select((expression) => expression.fn.countAll<string>().as('count'))\n .where('shareId', '=', shareId)\n .where('createdAt', '>', since)\n .where((expression) => {\n if (reporterUserId) return expression('reporterUserId', '=', reporterUserId)\n if (reporterGuestId) return expression('reporterGuestId', '=', reporterGuestId)\n return expression.and([\n expression('reporterUserId', 'is', null),\n expression('reporterGuestId', 'is', null)\n ])\n })\n .executeTakeFirstOrThrow(),\n transaction\n .selectFrom('documentReport')\n .select((expression) => expression.fn.countAll<string>().as('count'))\n .where('shareId', '=', shareId)\n .where('createdAt', '>', since)\n .executeTakeFirstOrThrow()\n ])\n if (\n Number(byReporter.count) >= DOCUMENT_REPORT_BUDGET.perReporter ||\n Number(byShare.count) >= DOCUMENT_REPORT_BUDGET.perShare\n ) {\n throw new DocumentReportLimitError()\n }\n const id = crypto.randomUUID()\n const replyEmail = input.replyEmail ?? actor?.email ?? null\n await transaction\n .insertInto('documentReport')\n .values({\n id,\n documentId: resolved.documentId,\n shareId,\n reporterUserId,\n reporterGuestId,\n replyEmail,\n replyLocale,\n reason: input.reason,\n description: input.description\n })\n .execute()\n if (!options.email) return\n const document = await transaction\n .selectFrom('document')\n .select('name')\n .where('id', '=', resolved.documentId)\n .executeTakeFirstOrThrow()\n // Whoever left an address hears that the report arrived, and later what was decided.\n if (replyEmail) {\n await options.email.enqueue(\n {\n idempotencyKey: `document-report-received/${id}`,\n kind: 'document-report-received',\n recipientEmail: replyEmail,\n fallbackLocale: replyLocale,\n payload: { documentName: document.name }\n },\n transaction\n )\n }\n for (const recipientEmail of options.adminRecipients) {\n await options.email.enqueue(\n {\n idempotencyKey: `document-report/${id}/${recipientEmail}`,\n kind: 'document-report',\n recipientEmail,\n payload: {\n documentName: document.name,\n reason: input.reason,\n description: input.description.slice(0, EMAIL_DESCRIPTION_CHARACTERS),\n actionURL: new URL('/admin/reports', options.publicURL).href\n }\n },\n transaction\n )\n }\n })\n }\n }\n}\n\nexport type DocumentReportService = ReturnType<typeof createDocumentReportService>\n","import { fileDocumentReportSchema } from '#cloud/contract'\nimport { acceptedLocale } from '#cloud/email'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport { shareActor } from '#cloud/server/sharing/actor'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport { shareParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { DocumentReportLimitError, type DocumentReportService } from './service'\n\n/** Reports about documents shared by link, which anyone the link lets in may file. */\nexport function createPublicReportRoutes(\n service: DocumentReportService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono().post(\n '/shares/:shareId/reports',\n shareParams,\n validatedJSON(fileDocumentReportSchema),\n async (context) => {\n try {\n return await sharingRoute(context, async () => {\n await service.file(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession),\n acceptedLocale(context.req.header('accept-language'))\n )\n return context.json({ received: true as const }, 201)\n })\n } catch (error) {\n if (error instanceof DocumentReportLimitError) {\n return context.json({ error: { code: 'rate_limited' as const } }, 429)\n }\n throw error\n }\n }\n )\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport {\n cloudAdminDocumentFilterSchema,\n type CloudAdminDocument,\n type CloudAdminDocumentFilter,\n type DocumentDownload\n} from '#cloud/contract'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { unmarkPurged } from '#cloud/server/documents/purge'\nimport type { DocumentService } from '#cloud/server/documents/service'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { tellReporters } from '#cloud/server/reports'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { uniq } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely, Transaction } from 'kysely'\n\nimport { extractFigThumbnailFromReader } from '@open-pencil/fig'\n\ntype DocumentExpression = ExpressionBuilder<CloudDatabase, 'document'>\n\n/** Whether reports about the document are still waiting for a decision. */\nconst reported = (expression: DocumentExpression) =>\n expression.exists(\n expression\n .selectFrom('documentReport')\n .select('documentReport.id')\n .whereRef('documentReport.documentId', '=', 'document.id')\n .where('documentReport.status', '=', 'open')\n )\n\nconst live = (expression: DocumentExpression) => expression('document.deletedAt', 'is', null)\n\nconst FILTERS: ListFilters<CloudAdminDocumentFilter, 'document'> = {\n all: live,\n reported: (expression) => expression.and([live(expression), reported(expression)]),\n disabled: (expression) =>\n expression.and([live(expression), expression('document.disabledAt', 'is not', null)]),\n purged: (expression) => expression('document.purgedAt', 'is not', null)\n}\n\n/**\n * What the console lists: live documents, and those deleted forever an administrator can still\n * restore, inside the grace and not yet being destroyed.\n */\nfunction listable(graceSince: Date) {\n return (expression: DocumentExpression) =>\n expression.or([\n live(expression),\n expression.and([\n expression('document.purgedAt', '>', graceSince),\n expression('document.cleanupClaimId', 'is', null)\n ])\n ])\n}\n\n/** Documents whose name, ID, or maker's name or email has the search in it. */\nfunction searchCondition(search: string) {\n const pattern = containsPattern(search)\n return (expression: DocumentExpression) =>\n expression.or([\n expression('document.name', 'ilike', pattern),\n expression(expression.cast('document.id', 'text'), '=', search.toLowerCase()),\n expression.exists(\n expression\n .selectFrom('user')\n .select('user.id')\n .whereRef(userIdText, '=', 'document.createdBy')\n .where((inner) =>\n inner.or([inner('user.email', 'ilike', pattern), inner('user.name', 'ilike', pattern)])\n )\n )\n ])\n}\n\n/** Where the console finds what it shows of documents besides their rows. */\nexport type AdminDocumentsOptions = {\n /** How long a document deleted forever waits before cleanup destroys it. */\n purgeGraceMs?: number\n /** The workspace whose documents are the deployment's community gallery, if it has one. */\n communityWorkspaceId?: string | null\n}\n\n/** A share link that still opens its document: not revoked, and not expired by `now`. */\nfunction liveShare(now: Date) {\n return (expression: ExpressionBuilder<CloudDatabase, 'documentShare'>) =>\n expression.and([\n expression('documentShare.revokedAt', 'is', null),\n expression.or([\n expression('documentShare.expiresAt', 'is', null),\n expression('documentShare.expiresAt', '>', now)\n ])\n ])\n}\n\n/**\n * The documents with these IDs as the console shows them, in no particular order; with\n * `purgeGraceMs`, when cleanup destroys one deleted forever.\n */\nexport async function adminDocuments(\n database: Kysely<CloudDatabase>,\n documentIds: readonly string[],\n { purgeGraceMs, communityWorkspaceId = null }: AdminDocumentsOptions = {}\n): Promise<Map<string, CloudAdminDocument>> {\n const ids = uniq(documentIds).filter(isUUID)\n if (ids.length === 0) return new Map()\n const now = new Date()\n const rows = await database\n .selectFrom('document')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select((expression) => [\n 'document.id',\n 'document.name',\n 'document.kind',\n 'document.createdBy',\n 'document.createdAt',\n 'document.updatedAt',\n 'document.disabledAt',\n 'document.disabledReason',\n 'document.purgedAt',\n 'document.currentRevisionId',\n 'workspace.id as workspaceId',\n 'workspace.name as workspaceName',\n expression\n .selectFrom('documentReport')\n .select((inner) => inner.fn.countAll<string>().as('count'))\n .whereRef('documentReport.documentId', '=', 'document.id')\n .where('documentReport.status', '=', 'open')\n .as('openReports'),\n expression\n .selectFrom('documentShare')\n .select((inner) => inner.fn.countAll<string>().as('count'))\n .whereRef('documentShare.documentId', '=', 'document.id')\n .where(liveShare(now))\n .as('links'),\n expression\n .selectFrom('documentShare')\n .select((inner) => inner.fn.countAll<string>().as('count'))\n .whereRef('documentShare.documentId', '=', 'document.id')\n .where(liveShare(now))\n .where('documentShare.permission', '=', 'edit')\n .as('editLinks')\n ])\n .where('document.id', 'in', ids)\n .execute()\n const ownerIds = uniq(rows.map((row) => row.createdBy)).filter(isUUID)\n const owners = ownerIds.length\n ? await database\n .selectFrom('user')\n .select(['id', 'name', 'email'])\n .where('id', 'in', ownerIds)\n .execute()\n : []\n const ownerById = new Map(owners.map((owner) => [owner.id, owner]))\n return new Map(\n rows.map((row) => [\n row.id,\n {\n id: row.id,\n name: row.name,\n kind: row.kind,\n workspace: { id: row.workspaceId, name: row.workspaceName },\n owner: ownerById.get(row.createdBy) ?? null,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? '',\n disabledAt: dateString(row.disabledAt),\n disabledReason: row.disabledReason,\n openReports: Number(row.openReports ?? 0),\n purgedAt: dateString(row.purgedAt),\n revisionId: row.currentRevisionId,\n exposure: {\n community: communityWorkspaceId !== null && row.workspaceId === communityWorkspaceId,\n links: Number(row.links ?? 0),\n editLinks: Number(row.editLinks ?? 0)\n },\n destroyedAt:\n row.purgedAt === null || purgeGraceMs === undefined\n ? null\n : new Date(new Date(row.purgedAt).getTime() + purgeGraceMs).toISOString()\n }\n ])\n )\n}\n\ntype AuditDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/** Records an administrator's action on a document, a link, or a report. */\nexport async function auditContentAction(\n database: AuditDatabase,\n actorId: string,\n action: string,\n subject: { type: 'document' | 'document-share' | 'document-report'; id: string },\n metadata: Record<string, unknown> = {}\n): Promise<void> {\n await database\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action,\n subjectType: subject.type,\n subjectId: subject.id,\n metadata\n })\n .execute()\n}\n\n/** A document that is not deleted, held until the transaction ends; none is not found. */\nfunction lockedDocument(transaction: Transaction<CloudDatabase>, documentId: string) {\n return transaction\n .selectFrom('document')\n .select(['id', 'disabledAt'])\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .forUpdate()\n .executeTakeFirstOrThrow()\n}\n\nexport type AdminDocumentServiceOptions = {\n /**\n * Ends a taken-down document's live rooms, saving them, so a takedown reaches open tabs at once\n * and a restore loses no edit.\n */\n closeRooms?: (documentId: string) => void\n /** How long a document deleted forever waits before cleanup destroys it; 0 when not given. */\n purgeGraceMs?: number\n /** The workspace whose documents are the deployment's community gallery, if it has one. */\n communityWorkspaceId?: string | null\n /** Where documents are stored, for their thumbnails; without it none has one. */\n objects?: Pick<ObjectStore, 'readRange'>\n /** Documents' downloads; without it none can be downloaded. */\n documents?: Pick<DocumentService, 'downloadRetained'>\n /**\n * Tells the owner of a document's workspace when it is blocked and restored. Without it, or\n * without the server's address its link needs, nobody is told.\n */\n email?: TransactionalEmailService\n publicURL?: string\n /** Where an owner writes to contest a block: the deployment's abuse address. */\n contactEmail?: string\n}\n\n/** The owner of a document's workspace, and the document's name, to tell about a block. */\nasync function documentOwner(transaction: Transaction<CloudDatabase>, documentId: string) {\n const document = await transaction\n .selectFrom('document')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select(['document.name', 'workspace.ownerId'])\n .where('document.id', '=', documentId)\n .executeTakeFirst()\n if (!document) return undefined\n const owner = await transaction\n .selectFrom('user')\n .select(['name', 'email'])\n .where((expression) => expression(userIdText(expression), '=', document.ownerId))\n .executeTakeFirst()\n return owner && { ...owner, documentName: document.name }\n}\n\nexport function createAdminDocumentService(\n database: Kysely<CloudDatabase>,\n options: AdminDocumentServiceOptions = {}\n) {\n const purgeGraceMs = options.purgeGraceMs ?? 0\n const { email, publicURL } = options\n const graceSince = (now: Date) => new Date(now.getTime() - purgeGraceMs)\n return {\n /** A page of documents, newest change first, and how many match the search under each filter. */\n async list(query: AdminListQuery<CloudAdminDocumentFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('document').where(listable(graceSince(new Date())))\n if (search) searched = searched.where(searchCondition(search))\n const counts = await countEachFilter(\n searched,\n cloudAdminDocumentFilterSchema.options,\n FILTERS\n )\n const page = await searched\n .where(FILTERS[filter])\n .select('document.id')\n .orderBy('document.updatedAt', 'desc')\n .orderBy('document.id')\n .limit(limit)\n .offset(offset)\n .execute()\n const documents = await adminDocuments(\n database,\n page.map((row) => row.id),\n { purgeGraceMs, communityWorkspaceId: options.communityWorkspaceId }\n )\n return {\n documents: page.flatMap((row) => documents.get(row.id) ?? []),\n total: counts[filter],\n counts\n }\n },\n\n /**\n * The thumbnail a document's stored file carries at `revisionId`, read from storage in ranges\n * as the community gallery reads its own; null when that revision is not current any more,\n * its file is gone, or it carries none.\n */\n /** Whether `revisionId` is still the document's saved state, so a copy of its thumbnail holds. */\n async isCurrentRevision(documentId: string, revisionId: string): Promise<boolean> {\n const row = await database\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .where('currentRevisionId', '=', revisionId)\n .executeTakeFirst()\n return row !== undefined\n },\n\n async thumbnail(documentId: string, revisionId: string): Promise<Uint8Array | null> {\n const { objects } = options\n if (!objects) return null\n const row = await database\n .selectFrom('document')\n .innerJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select(['storageObject.objectKey', 'storageObject.byteSize'])\n .where('document.id', '=', documentId)\n .where('document.currentRevisionId', '=', revisionId)\n .executeTakeFirst()\n if (!row) return null\n const gone = new Error('The document’s stored file is gone')\n try {\n return await extractFigThumbnailFromReader({\n size: Number(row.byteSize),\n read: async (start, endExclusive) => {\n const bytes = await objects.readRange(row.objectKey, start, endExclusive)\n if (!bytes) throw gone\n return bytes\n }\n })\n } catch (error) {\n if (error === gone) return null\n throw error\n }\n },\n\n /**\n * Links to download a document as it is now, its file and images, for an administrator to look\n * at it outside any editor, taken down or in Trash included, recorded in the audit log. A\n * document never saved has none.\n */\n async download(actorId: string, documentId: string): Promise<DocumentDownload> {\n if (!options.documents) throw new DocumentNotFoundError()\n // A taken-down document too: looking at it is what moderating it takes.\n const download = await options.documents.downloadRetained(documentId)\n await auditContentAction(database, actorId, 'document.downloaded', {\n type: 'document',\n id: documentId\n })\n return download\n },\n\n /**\n * Takes a document down: it opens for nobody, its owner included, its links stop working,\n * and its live rooms close, saved. Its open reports count as acted on. Nothing is deleted and\n * its collaboration epoch stays, so enabling it gives everything back, live edits included.\n */\n async disable(actorId: string, documentId: string, reason: string | undefined): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n const document = await lockedDocument(transaction, documentId)\n if (document.disabledAt) return\n const disabledAt = new Date()\n await transaction\n .updateTable('document')\n .set({ disabledAt, disabledReason: reason ?? null })\n .where('id', '=', documentId)\n .execute()\n const reports = await transaction\n .updateTable('documentReport')\n .set({ status: 'actioned', resolvedAt: new Date(), resolvedBy: actorId })\n .where('documentId', '=', documentId)\n .where('status', '=', 'open')\n .returning('id')\n .execute()\n // Everyone who reported it and left an address hears it was blocked.\n await tellReporters(\n transaction,\n { email, contactEmail: options.contactEmail },\n reports.map((report) => report.id),\n 'blocked'\n )\n await auditContentAction(\n transaction,\n actorId,\n 'document.disabled',\n { type: 'document', id: documentId },\n reason ? { reason } : {}\n )\n // Told in the same transaction, so a block that rolls back sends nothing.\n const owner = email && publicURL && (await documentOwner(transaction, documentId))\n if (owner) {\n await email.enqueue(\n {\n idempotencyKey: `document-blocked/${documentId}/${disabledAt.getTime()}`,\n kind: 'document-blocked',\n recipientEmail: owner.email,\n payload: {\n name: owner.name || null,\n documentName: owner.documentName,\n reason: reason ?? null,\n contactEmail: options.contactEmail ?? null,\n actionURL: publicURL\n }\n },\n transaction\n )\n }\n })\n options.closeRooms?.(documentId)\n },\n\n /** Puts a document taken down back where it was. */\n async enable(actorId: string, documentId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n const document = await lockedDocument(transaction, documentId)\n if (!document.disabledAt) return\n await transaction\n .updateTable('document')\n .set({ disabledAt: null, disabledReason: null })\n .where('id', '=', documentId)\n .execute()\n await auditContentAction(transaction, actorId, 'document.enabled', {\n type: 'document',\n id: documentId\n })\n const owner = email && publicURL && (await documentOwner(transaction, documentId))\n if (owner) {\n await email.enqueue(\n {\n idempotencyKey: `document-restored/${documentId}/${Date.now()}`,\n kind: 'document-restored',\n recipientEmail: owner.email,\n payload: {\n name: owner.name || null,\n documentName: owner.documentName,\n actionURL: publicURL\n }\n },\n transaction\n )\n }\n })\n },\n\n /**\n * Brings back a document someone deleted forever, while its grace lasts: it is live again in\n * its workspace, not in Trash, and counts toward the workspace's storage again, over its plan\n * or not. A document cleanup is destroying, or whose workspace has nobody left in it, can't be.\n */\n async undelete(actorId: string, documentId: string, now = new Date()): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n const document = await transaction\n .selectFrom('document')\n .select(['id', 'workspaceId', 'purgedAt', 'purgedBytes', 'cleanupClaimId'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n // Cleanup may have destroyed it since the list was loaded.\n if (\n !document ||\n document.purgedAt === null ||\n document.cleanupClaimId !== null ||\n new Date(document.purgedAt) <= graceSince(now)\n ) {\n throw new AdminDomainError(\n 'document_not_restorable',\n 'Only a document deleted forever, inside its grace, can be restored'\n )\n }\n const member = await transaction\n .selectFrom('workspaceMember')\n .select('userId')\n .where('workspaceId', '=', document.workspaceId)\n .limit(1)\n .executeTakeFirst()\n if (!member) {\n throw new AdminDomainError('workspace_gone', 'The document’s workspace has nobody in it')\n }\n await unmarkPurged(transaction, {\n id: document.id,\n workspaceId: document.workspaceId,\n purgedBytes: Number(document.purgedBytes)\n })\n await auditContentAction(\n transaction,\n actorId,\n 'document.undeleted',\n { type: 'document', id: documentId },\n { workspaceId: document.workspaceId }\n )\n })\n },\n\n /**\n * Revokes a share link for good, as its owner can: the collaboration epoch moves on, so the\n * link's guests lose their tickets, while members keep editing.\n */\n async revokeShare(actorId: string, shareId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n const share = await transaction\n .selectFrom('documentShare')\n .select(['id', 'documentId', 'revokedAt'])\n .where('id', '=', shareId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (share.revokedAt) return\n await transaction\n .updateTable('documentShare')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('id', '=', shareId)\n .execute()\n await transaction\n .updateTable('document')\n .set((expression) => ({ collaborationEpoch: expression('collaborationEpoch', '+', 1) }))\n .where('id', '=', share.documentId)\n .execute()\n await auditContentAction(\n transaction,\n actorId,\n 'document-share.revoked',\n { type: 'document-share', id: shareId },\n { documentId: share.documentId }\n )\n })\n }\n }\n}\n\nexport type AdminDocumentService = ReturnType<typeof createAdminDocumentService>\n","import {\n adminDocuments,\n auditContentAction,\n type AdminDocumentsOptions\n} from '#cloud/admin/documents/service'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport {\n cloudAdminReportFilterSchema,\n type CloudAdminReport,\n type CloudAdminReportFilter\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { tellReporters, type ReportReplies } from '#cloud/server/reports'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { uniq } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\ntype ReportExpression = ExpressionBuilder<CloudDatabase, 'documentReport'>\n\nconst FILTERS: ListFilters<CloudAdminReportFilter, 'documentReport'> = {\n open: (expression) => expression('documentReport.status', '=', 'open'),\n actioned: (expression) => expression('documentReport.status', '=', 'actioned'),\n dismissed: (expression) => expression('documentReport.status', '=', 'dismissed'),\n all: (expression) => expression.lit(true)\n}\n\n/** Reports whose description, reply address, or document's name has the search in it. */\nfunction searchCondition(search: string) {\n const pattern = containsPattern(search)\n return (expression: ReportExpression) =>\n expression.or([\n expression('documentReport.description', 'ilike', pattern),\n expression('documentReport.replyEmail', 'ilike', pattern),\n expression.exists(\n expression\n .selectFrom('document')\n .select('document.id')\n .whereRef('document.id', '=', 'documentReport.documentId')\n .where('document.name', 'ilike', pattern)\n )\n ])\n}\n\n/** Reports' administration, which tells each reporter who left an address what it decided. */\nexport function createAdminReportService(\n database: Kysely<CloudDatabase>,\n replies: ReportReplies = {},\n documentOptions: Pick<AdminDocumentsOptions, 'communityWorkspaceId'> = {}\n) {\n return {\n /** A page of reports, newest first, and how many match the search under each filter. */\n async list(query: AdminListQuery<CloudAdminReportFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'open'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('documentReport')\n if (search) searched = searched.where(searchCondition(search))\n const counts = await countEachFilter(searched, cloudAdminReportFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .selectAll()\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n const shareIds = uniq(rows.flatMap((row) => (row.shareId ? [row.shareId] : [])))\n const reporterIds = uniq(\n rows.flatMap((row) => (row.reporterUserId ? [row.reporterUserId] : []))\n ).filter(isUUID)\n const [documents, shares, reporters] = await Promise.all([\n adminDocuments(\n database,\n rows.map((row) => row.documentId),\n documentOptions\n ),\n shareIds.length\n ? database\n .selectFrom('documentShare')\n .select(['id', 'revokedAt'])\n .where('id', 'in', shareIds)\n .execute()\n : [],\n reporterIds.length\n ? database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', reporterIds)\n .execute()\n : []\n ])\n const revoked = new Map(shares.map((share) => [share.id, share.revokedAt !== null]))\n const reporterNames = new Map(reporters.map((reporter) => [reporter.id, reporter.name]))\n const reports: CloudAdminReport[] = rows.flatMap((row) => {\n const document = documents.get(row.documentId)\n if (!document) return []\n return [\n {\n id: row.id,\n reason: row.reason,\n description: row.description,\n status: row.status,\n reporter: row.reporterUserId\n ? { id: row.reporterUserId, name: reporterNames.get(row.reporterUserId) ?? null }\n : null,\n replyEmail: row.replyEmail,\n createdAt: dateString(row.createdAt) ?? '',\n resolvedAt: dateString(row.resolvedAt),\n document,\n share: row.shareId\n ? { id: row.shareId, revoked: revoked.get(row.shareId) ?? true }\n : null\n }\n ]\n })\n return { reports, total: counts[filter], counts }\n },\n\n /** Closes an open report, as dismissed or as acted on; a closed one stays as it was. */\n async resolve(\n actorId: string,\n reportId: string,\n status: 'dismissed' | 'actioned'\n ): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n const report = await transaction\n .selectFrom('documentReport')\n .select(['id', 'status', 'documentId'])\n .where('id', '=', reportId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (report.status !== 'open') return\n await transaction\n .updateTable('documentReport')\n .set({ status, resolvedAt: new Date(), resolvedBy: actorId })\n .where('id', '=', reportId)\n .execute()\n await auditContentAction(\n transaction,\n actorId,\n `document-report.${status}`,\n { type: 'document-report', id: reportId },\n { documentId: report.documentId }\n )\n await tellReporters(transaction, replies, [reportId], status)\n })\n }\n }\n}\n\nexport type AdminReportService = ReturnType<typeof createAdminReportService>\n","import type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport type { BillingTokenService } from './tokens'\n\nexport type BillingRouteEnvironment = { Variables: { actor: CloudActor } }\n\n/** Without a billing service, the deployment sells nothing and the token route is not found. */\nexport function createBillingRoutes(\n service: BillingTokenService | undefined,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<BillingRouteEnvironment>()\n if (service && rateLimit) {\n router.use(\n '/billing/token',\n createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.billingToken)\n )\n }\n return router.post('/billing/token', async (context) => {\n if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json(await service.issue(context.get('actor')))\n })\n}\n","import { CLOUD_BILLING_API_PATHS } from '#cloud/contract'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\nimport { joinURL } from 'ufo'\n\nimport type { BillingTokenService } from './tokens'\n\nexport type SeatNotifierOptions = {\n database: Kysely<CloudDatabase>\n /** The billing service's discovered endpoint. */\n endpoint: string\n tokens: BillingTokenService\n /** Sends a notice; the global `fetch` by default. */\n fetch?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * Tells the billing service when the people who can edit in an account's workspaces change, so it\n * can charge for the seats. Each notice carries a billing token for that account and nothing\n * else: the service reads the count from Cloud's internal API, so a notice that never arrives only\n * leaves the change to the service's own reconciliation.\n */\nexport function createSeatNotifier(options: SeatNotifierOptions) {\n const send = options.fetch ?? ((url: string, init: RequestInit) => fetch(url, init))\n return {\n async notify(accountIds: readonly string[]): Promise<void> {\n if (accountIds.length === 0) return\n const accounts = await options.database\n .selectFrom('user')\n .select((eb) => [userIdText(eb).as('userId'), 'email'])\n .where((eb) => eb(userIdText(eb), 'in', accountIds))\n .execute()\n // Every notice is sent before any failure is reported, so one refusal never leaves\n // another account's notice cut off.\n const sent = await Promise.allSettled(\n accounts.map(async (account) => {\n const { token } = await options.tokens.issue(account)\n const response = await send(joinURL(options.endpoint, CLOUD_BILLING_API_PATHS.seats), {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` }\n })\n if (!response.ok) {\n throw new Error(`Billing refused a seat notice with status ${response.status}`)\n }\n })\n )\n const failed: unknown[] = sent.flatMap((result): unknown[] =>\n result.status === 'rejected' ? [result.reason] : []\n )\n if (failed.length > 0) throw new AggregateError(failed, 'Billing missed seat notices')\n }\n }\n}\n\nexport type SeatNotifier = ReturnType<typeof createSeatNotifier>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\n/**\n * An account's seats: the people who can edit in the workspaces it owns, each counted once\n * however many of them they edit, the owner too. Viewers take no seat.\n */\nexport async function accountSeats(database: Kysely<CloudDatabase>, accountId: string) {\n const row = await database\n .selectFrom('workspaceMember')\n .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')\n .select((eb) => eb.fn.count<string>('workspaceMember.userId').distinct().as('seats'))\n .where('workspace.ownerId', '=', accountId)\n .where('workspaceMember.role', 'in', ['editor', 'admin'])\n .executeTakeFirst()\n return Number(row?.seats ?? 0)\n}\n","import * as v from 'valibot'\n\nconst positiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1))\nconst nonNegativeIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\nexport const staticEntitlementsSchema = v.object({\n documents: v.optional(\n v.object({\n maximumFileBytes: v.optional(positiveIntegerSchema),\n revisionHistory: v.optional(v.boolean())\n }),\n {}\n ),\n storage: v.optional(v.object({ maximumBytes: v.optional(positiveIntegerSchema) }), {}),\n sharing: v.optional(\n v.object({\n links: v.optional(v.boolean()),\n guestView: v.optional(v.boolean()),\n guestEdit: v.optional(v.boolean()),\n guestPresence: v.optional(v.boolean())\n }),\n {}\n ),\n collaboration: v.optional(\n v.object({\n enabled: v.optional(v.boolean()),\n maximumParticipants: v.optional(positiveIntegerSchema)\n }),\n {}\n ),\n services: v.optional(\n v.object({\n enabled: v.optional(v.boolean()),\n monthlyCreditAllowance: v.optional(nonNegativeIntegerSchema)\n }),\n {}\n )\n})\nexport type StaticEntitlements = v.InferOutput<typeof staticEntitlementsSchema>\n\nexport const staticEntitlementsTOMLSchema = v.strictObject({\n documents: v.optional(\n v.strictObject({\n maximum_file_bytes: v.optional(positiveIntegerSchema),\n revision_history: v.optional(v.boolean())\n })\n ),\n storage: v.optional(v.strictObject({ maximum_bytes: v.optional(positiveIntegerSchema) })),\n sharing: v.optional(\n v.strictObject({\n links: v.optional(v.boolean()),\n guest_view: v.optional(v.boolean()),\n guest_edit: v.optional(v.boolean()),\n guest_presence: v.optional(v.boolean())\n })\n ),\n collaboration: v.optional(\n v.strictObject({\n enabled: v.optional(v.boolean()),\n maximum_participants: v.optional(positiveIntegerSchema)\n })\n ),\n services: v.optional(\n v.strictObject({\n enabled: v.optional(v.boolean()),\n monthly_credit_allowance: v.optional(nonNegativeIntegerSchema)\n })\n )\n})\n","export const CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES = 1024 * 1024\nexport const CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM = 1000\n\nexport type CloudTechnicalLimits = {\n maximumUploadBytes: number\n maximumCollaborationMessageBytes: number\n maximumConnectionsPerRoom: number\n}\n","import {\n CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,\n cloudEditorVersionSchema,\n RELAY_MINIMUM_MESSAGE_BYTES,\n sendsTokenSafely\n} from '#cloud/contract'\nimport { staticEntitlementsSchema } from '#cloud/server/policy/schema'\nimport * as v from 'valibot'\n\nimport {\n CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,\n CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM\n} from './limits'\n\nexport const httpURLSchema = v.pipe(\n v.string(),\n v.url(),\n v.check((value) => {\n const protocol = new URL(value).protocol\n return protocol === 'https:' || protocol === 'http:'\n }, 'URL must use HTTP or HTTPS')\n)\n\nconst websocketURLSchema = v.pipe(\n v.string(),\n v.url(),\n v.check((value) => {\n const protocol = new URL(value).protocol\n return protocol === 'ws:' || protocol === 'wss:'\n }, 'URL must use WS or WSS')\n)\n\nconst optionalTextSchema = v.optional(v.pipe(v.string(), v.trim(), v.minLength(1)))\n\n/**\n * A prefix deleted files move under: one lowercase path segment and a slash, which no object key\n * the server makes starts with (they start with `documents/`).\n */\nexport const deletedPrefixSchema = v.pipe(\n v.string(),\n v.regex(/^[a-z0-9][a-z0-9-]*\\/$/),\n v.check((prefix) => prefix !== 'documents/', 'deleted_prefix cannot be documents/')\n)\n\nconst rawCloudServerConfigSchema = v.object({\n deployment: v.picklist(['official', 'self-hosted']),\n publicURL: httpURLSchema,\n listingMinimumEditorVersion: v.optional(cloudEditorVersionSchema),\n minimumEditorVersion: v.optional(cloudEditorVersionSchema),\n relayURL: v.optional(websocketURLSchema),\n technicalLimits: v.optional(\n v.object({\n maximumUploadBytes: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),\n CLOUD_PROTOCOL_MAX_UPLOAD_BYTES\n ),\n maximumCollaborationMessageBytes: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(RELAY_MINIMUM_MESSAGE_BYTES)),\n CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES\n ),\n maximumConnectionsPerRoom: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1)),\n CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM\n )\n }),\n {\n maximumUploadBytes: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,\n maximumCollaborationMessageBytes: CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,\n maximumConnectionsPerRoom: CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM\n }\n ),\n staticEntitlements: v.optional(staticEntitlementsSchema),\n /** With database entitlements, what an account without stored ones takes, value by value. */\n defaultEntitlements: v.optional(staticEntitlementsSchema),\n databaseURL: v.pipe(v.string(), v.url()),\n authSecret: v.pipe(v.string(), v.minLength(32)),\n trustedOrigins: v.optional(v.array(httpURLSchema), []),\n /** The server's editor works with files on this device without signing in to the server. */\n localEditor: v.optional(v.boolean(), true),\n authTrustedIPHeaders: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),\n authTrustedProxies: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),\n enrollmentMode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),\n indexingPolicy: v.optional(v.picklist(['allow', 'deny']), 'deny'),\n enrollmentAdminNotificationEmails: v.optional(\n v.array(v.pipe(v.string(), v.trim(), v.email())),\n []\n ),\n emailPasswordEnabled: v.optional(v.boolean(), false),\n emailPasswordSignUpEnabled: v.optional(v.boolean(), true),\n emailPasswordMinimumLength: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),\n 8\n ),\n emailPasswordMaximumLength: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),\n 128\n ),\n emailVerificationExpiresIn: v.optional(v.pipe(v.number(), v.integer(), v.minValue(60)), 3600),\n passwordResetExpiresIn: v.optional(v.pipe(v.number(), v.integer(), v.minValue(60)), 3600),\n compromisedPasswordCheck: v.optional(v.boolean(), false),\n deploymentAdminMFARequired: v.optional(v.boolean(), false),\n totpEnabled: v.optional(v.boolean(), false),\n passkeysEnabled: v.optional(v.boolean(), false),\n recoveryCodesEnabled: v.optional(v.boolean(), false),\n mfaTrustedDeviceDays: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14),\n passkeyRPName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1)), 'OpenPencil Cloud'),\n captchaProvider: v.optional(v.literal('cloudflare-turnstile')),\n captchaSiteKey: optionalTextSchema,\n captchaSecretKey: optionalTextSchema,\n captchaAllowedHostnames: v.optional(v.array(v.pipe(v.string(), v.trim(), v.minLength(1))), []),\n googleClientId: optionalTextSchema,\n googleClientSecret: optionalTextSchema,\n appleClientId: optionalTextSchema,\n appleTeamId: optionalTextSchema,\n appleKeyId: optionalTextSchema,\n applePrivateKey: optionalTextSchema,\n githubClientId: optionalTextSchema,\n githubClientSecret: optionalTextSchema,\n appleAppBundleIdentifier: optionalTextSchema,\n s3Endpoint: httpURLSchema,\n s3Region: v.pipe(v.string(), v.trim(), v.minLength(1)),\n s3Bucket: v.pipe(v.string(), v.trim(), v.minLength(1)),\n s3AccessKeyId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n s3SecretAccessKey: v.pipe(v.string(), v.minLength(1)),\n s3SessionToken: optionalTextSchema,\n s3ForcePathStyle: v.optional(v.boolean(), true),\n s3ChecksumVerification: v.optional(v.picklist(['native', 'metadata']), 'native'),\n s3ServerSideEncryption: v.optional(v.picklist(['AES256', 'aws:kms'])),\n s3KmsKeyId: optionalTextSchema,\n /** Where a deleted file is kept until the bucket's lifecycle rule expires it; see `deleted_prefix`. */\n s3DeletedPrefix: v.optional(deletedPrefixSchema),\n smtpHost: optionalTextSchema,\n smtpPort: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65_535))),\n smtpSecure: v.optional(v.boolean()),\n smtpUser: optionalTextSchema,\n smtpPassword: optionalTextSchema,\n emailFrom: optionalTextSchema,\n emailReplyTo: v.optional(v.pipe(v.string(), v.email())),\n emailTransport: v.optional(v.picklist(['none', 'smtp', 'cloudflare']), 'none'),\n emailBatchSize: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000)), 50),\n emailIntervalMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 30_000),\n emailLeaseDurationMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 5 * 60_000),\n emailMaximumAttempts: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(20)),\n 5\n ),\n cleanupEnabled: v.optional(v.boolean(), true),\n cleanupBatchSize: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000)),\n 100\n ),\n cleanupIntervalMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 60_000),\n cleanupLeaseDurationMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 5 * 60_000),\n documentRetentionMs: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(0)),\n 30 * 24 * 60 * 60_000\n ),\n /**\n * How long a document deleted forever keeps its files and rows, out of everyone's sight, so a\n * server administrator can still bring it back; 0 destroys it at once.\n */\n documentPurgeGraceMs: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(0)),\n 7 * 24 * 60 * 60_000\n ),\n /** The OpenPencil services editors reach with tokens this server signs; see `src/contract/services.ts`. */\n servicesEndpoint: v.optional(httpURLSchema),\n /** The PKCS #8 PEM of the P-256 key that signs service tokens. */\n servicesSigningKey: optionalTextSchema,\n servicesTokenLifetimeSeconds: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(60), v.maxValue(60 * 60)),\n 10 * 60\n ),\n /** The billing service accounts buy plans and credits from, which discovery advertises. */\n billingEndpoint: v.optional(httpURLSchema),\n /** The bearer token services such as billing present to the internal API. */\n internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32))),\n /**\n * The operator's own terms, privacy policy, abuse contact, and minimum age; without it the\n * server shows none. With `requireAcceptance`, an account uses the server only once it accepted\n * `termsVersion`.\n */\n legal: v.optional(\n v.object({\n termsURL: v.optional(httpURLSchema),\n privacyURL: v.optional(httpURLSchema),\n termsVersion: optionalTextSchema,\n requireAcceptance: v.boolean(),\n abuseEmail: v.optional(v.pipe(v.string(), v.email())),\n minimumAge: v.optional(v.pipe(v.number(), v.integer(), v.minValue(13), v.maxValue(21)))\n })\n ),\n /**\n * The workspace whose documents anyone may open read-only, without signing in or a link: the\n * deployment's community gallery. Without it the server has none.\n */\n community: v.optional(\n v.object({\n workspaceId: v.pipe(v.string(), v.uuid()),\n /** The gallery document editors open as their tour. */\n tourDocumentId: v.optional(v.pipe(v.string(), v.uuid()))\n })\n ),\n /** How a self-hosted server names itself on its public pages. */\n branding: v.optional(\n v.object({\n name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n logoURL: v.optional(httpURLSchema),\n helpURL: v.optional(httpURLSchema)\n })\n ),\n /** Where server errors are reported; without it the server reports nothing. */\n errorTracking: v.optional(\n v.object({\n provider: v.literal('posthog'),\n host: httpURLSchema,\n projectAPIKey: v.pipe(v.string(), v.trim(), v.minLength(1)),\n /** Error reports name the account and records involved; off unless a deployment sets it. */\n includeIds: v.optional(v.boolean(), false)\n })\n )\n})\n\nexport type CloudServerConfig = v.InferOutput<typeof rawCloudServerConfigSchema>\n\nexport class CloudConfigError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CloudConfigError'\n }\n}\n\nfunction requireTogether(\n config: CloudServerConfig,\n label: string,\n fields: Array<keyof CloudServerConfig>\n): void {\n const configured = fields.filter((field) => Boolean(config[field]))\n if (configured.length !== 0 && configured.length !== fields.length) {\n throw new CloudConfigError(`${label} configuration must provide ${fields.join(', ')}`)\n }\n}\n\nfunction validateAuthenticationConfig(config: CloudServerConfig): void {\n if (config.emailPasswordMinimumLength > config.emailPasswordMaximumLength) {\n throw new CloudConfigError('Minimum password length cannot exceed maximum password length')\n }\n if (config.emailPasswordEnabled && config.emailTransport === 'none') {\n throw new CloudConfigError(\n 'Email and password authentication requires transactional email delivery'\n )\n }\n if (config.deploymentAdminMFARequired && !config.totpEnabled && !config.passkeysEnabled) {\n throw new CloudConfigError('Deployment administrator MFA requires TOTP or passkeys')\n }\n if (config.deployment === 'official' && !config.deploymentAdminMFARequired) {\n throw new CloudConfigError('An official deployment requires MFA for deployment administrators')\n }\n if (config.recoveryCodesEnabled && !config.totpEnabled) {\n throw new CloudConfigError('MFA recovery codes require TOTP')\n }\n requireTogether(config, 'CAPTCHA', ['captchaProvider', 'captchaSiteKey', 'captchaSecretKey'])\n if (\n config.deployment === 'official' &&\n config.emailPasswordEnabled &&\n config.emailPasswordSignUpEnabled &&\n (!config.compromisedPasswordCheck || !config.captchaProvider)\n ) {\n throw new CloudConfigError(\n 'Official email and password sign-up requires compromised-password checks and CAPTCHA'\n )\n }\n requireTogether(config, 'Google', ['googleClientId', 'googleClientSecret'])\n requireTogether(config, 'Apple', [\n 'appleClientId',\n 'appleTeamId',\n 'appleKeyId',\n 'applePrivateKey'\n ])\n requireTogether(config, 'GitHub', ['githubClientId', 'githubClientSecret'])\n}\n\nfunction validateEmailConfig(config: CloudServerConfig): void {\n requireTogether(config, 'SMTP', ['smtpHost', 'smtpPort'])\n requireTogether(config, 'SMTP authentication', ['smtpUser', 'smtpPassword'])\n if (config.emailTransport === 'smtp' && !config.smtpHost) {\n throw new CloudConfigError('SMTP email transport requires SMTP configuration')\n }\n if (config.smtpHost && config.emailTransport !== 'smtp') {\n throw new CloudConfigError('SMTP configuration requires the smtp email transport')\n }\n if (config.emailTransport !== 'none' && !config.emailFrom) {\n throw new CloudConfigError('Transactional email delivery requires an email from address')\n }\n if (config.deployment === 'official' && config.smtpHost && config.smtpSecure === false) {\n throw new CloudConfigError('Official SMTP delivery must use a secure connection')\n }\n}\n\nfunction validateServiceConfig(config: CloudServerConfig): void {\n requireTogether(config, 'Services', ['servicesEndpoint', 'servicesSigningKey'])\n // Billing tokens are signed with the services' key, and billing sets plans through the\n // internal API, which static entitlements would hide.\n if (config.billingEndpoint && !config.servicesSigningKey) {\n throw new CloudConfigError('Billing needs the services signing key to sign its tokens')\n }\n if (config.billingEndpoint && !config.internalServiceToken) {\n throw new CloudConfigError('Billing needs the internal API to set the plans it sells')\n }\n if (config.internalServiceToken && config.staticEntitlements) {\n throw new CloudConfigError(\n 'The internal API writes database entitlements, which static entitlements would hide'\n )\n }\n // Editors send these endpoints a bearer token, which must not cross the network in the clear.\n for (const [name, endpoint] of [\n ['services', config.servicesEndpoint],\n ['billing', config.billingEndpoint]\n ] as const) {\n if (endpoint && !sendsTokenSafely(endpoint)) {\n throw new CloudConfigError(\n `The ${name} endpoint must use HTTPS, or HTTP only to 127.0.0.1 or [::1] for development`\n )\n }\n }\n}\n\nfunction validateLegalConfig(config: CloudServerConfig): void {\n const legal = config.legal\n if (legal?.requireAcceptance && !(legal.termsURL && legal.termsVersion)) {\n throw new CloudConfigError('[legal] require_acceptance needs terms_url and terms_version')\n }\n}\n\nfunction validateObjectStorageConfig(config: CloudServerConfig): void {\n if (config.s3KmsKeyId && config.s3ServerSideEncryption !== 'aws:kms') {\n throw new CloudConfigError('S3 KMS key ID requires aws:kms server-side encryption')\n }\n const endpointHost = new URL(config.s3Endpoint).hostname\n if (!endpointHost.endsWith('.r2.cloudflarestorage.com')) return\n if (config.s3Region !== 'auto') {\n throw new CloudConfigError('Cloudflare R2 S3 region must be auto')\n }\n if (config.s3ForcePathStyle) {\n throw new CloudConfigError('Cloudflare R2 S3 endpoint must disable path-style requests')\n }\n if (config.s3ChecksumVerification !== 'metadata') {\n throw new CloudConfigError('Cloudflare R2 checksum verification must use metadata')\n }\n}\n\nexport function parseCloudServerConfig(input: unknown): CloudServerConfig {\n const config = v.parse(rawCloudServerConfigSchema, input)\n validateAuthenticationConfig(config)\n validateEmailConfig(config)\n validateServiceConfig(config)\n validateObjectStorageConfig(config)\n validateLegalConfig(config)\n return config\n}\n","import { CloudConfigError, type CloudServerConfig } from '#cloud/server/config/schema'\nimport { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK } from 'jose'\n\nconst ALGORITHM = 'ES256'\n\nexport type ServicesSigningKey = {\n privateKey: CryptoKey\n /** The public half, as published in the JWKS. */\n publicJWK: JWK & { kid: string }\n}\n\n/**\n * Imports the P-256 key that signs service tokens. Its `kid` is the public key's thumbprint,\n * so replacing the key changes the `kid`, and a service that caches the JWKS refetches it on the\n * first token it cannot match. Tokens the old key signed fail once and are re-requested.\n */\nexport async function importServicesSigningKey(pem: string): Promise<ServicesSigningKey> {\n const privateKey = await importPKCS8(pem, ALGORITHM, { extractable: true })\n const { kty, crv, x, y } = await exportJWK(privateKey)\n const publicJWK = { kty, crv, x, y }\n const kid = await calculateJwkThumbprint(publicJWK)\n return {\n privateKey: await importPKCS8(pem, ALGORITHM),\n publicJWK: { ...publicJWK, kid, alg: ALGORITHM, use: 'sig' }\n }\n}\n\n/**\n * Imports the configured signing key at startup, so a key that cannot sign stops the runtime\n * instead of failing every token request after discovery has advertised services.\n */\nexport async function loadServicesSigningKey(\n config: Pick<CloudServerConfig, 'servicesSigningKey'>\n): Promise<ServicesSigningKey | undefined> {\n if (!config.servicesSigningKey) return undefined\n try {\n return await importServicesSigningKey(config.servicesSigningKey)\n } catch {\n throw new CloudConfigError('Services signing key must be a PKCS #8 P-256 private key')\n }\n}\n\nexport const SERVICES_SIGNING_ALGORITHM = ALGORITHM\n","import { CLOUD_BILLING_TOKEN_AUDIENCE, type BillingToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport { SERVICES_SIGNING_ALGORITHM, type ServicesSigningKey } from '#cloud/server/services/keys'\nimport { SignJWT } from 'jose'\n\nexport type BillingTokenServiceOptions = {\n /** The Cloud public URL, which billing checks as the token's `iss`. */\n issuer: string\n /** The services' key, whose public half Cloud publishes for billing to verify with. */\n signingKey: ServicesSigningKey\n lifetimeSeconds: number\n}\n\nexport function createBillingTokenService(options: BillingTokenServiceOptions) {\n const { privateKey, publicJWK } = options.signingKey\n return {\n /**\n * Signs a token that lets the signed-in person buy or manage their own account's plan and\n * credits with billing; nobody else's, since an account is the person.\n */\n async issue(actor: Pick<CloudActor, 'userId' | 'email'>): Promise<BillingToken> {\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAt = issuedAt + options.lifetimeSeconds\n const token = await new SignJWT({ email: actor.email })\n .setProtectedHeader({ alg: SERVICES_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })\n .setIssuer(options.issuer)\n .setAudience(CLOUD_BILLING_TOKEN_AUDIENCE)\n .setSubject(actor.userId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(privateKey)\n return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }\n }\n }\n}\n\nexport type BillingTokenService = ReturnType<typeof createBillingTokenService>\n","/** The workspace's plan does not include services. */\nexport class ServicesNotEntitledError extends Error {\n constructor() {\n super('The workspace is not entitled to services')\n this.name = 'ServicesNotEntitledError'\n }\n}\n","import { createServicesTokenSchema } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { ServicesNotEntitledError } from './errors'\nimport type { ServicesTokenService } from './tokens'\n\nexport type ServicesRouteEnvironment = { Variables: { actor: CloudActor } }\n\n/** Without a service, the deployment offers no services and the token route is not found. */\nexport function createServicesRoutes(\n service: ServicesTokenService | undefined,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<ServicesRouteEnvironment>()\n if (service && rateLimit) {\n router.use(\n '/services/token',\n createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.servicesToken)\n )\n }\n return router.post(\n '/services/token',\n validatedJSON(createServicesTokenSchema),\n async (context) => {\n if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)\n try {\n return context.json(\n await service.issue(context.get('actor'), context.req.valid('json').workspaceId)\n )\n } catch (error) {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof ServicesNotEntitledError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n throw error\n }\n }\n )\n}\n","import { CLOUD_SERVICES_TOKEN_AUDIENCE, type ServicesToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport { SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\n\nimport { ServicesNotEntitledError } from './errors'\nimport { SERVICES_SIGNING_ALGORITHM, type ServicesSigningKey } from './keys'\n\nexport type ServicesTokenServiceOptions = {\n database: Kysely<CloudDatabase>\n policy: CloudPolicy\n deploymentMode: 'official' | 'self-hosted'\n /** The Cloud public URL, which services check as the token's `iss`. */\n issuer: string\n signingKey: ServicesSigningKey\n lifetimeSeconds: number\n}\n\nexport function createServicesTokenService(options: ServicesTokenServiceOptions) {\n const { privateKey, publicJWK } = options.signingKey\n\n return {\n /**\n * Signs a token that lets a workspace member reach the services on the workspace's behalf,\n * spending its owner's credits. Entitlements are read for every token, so a plan change reaches the service within one\n * token lifetime.\n */\n async issue(actor: CloudActor, workspaceId: string): Promise<ServicesToken> {\n if (!(await workspaceRole(options.database, actor.userId, workspaceId))) {\n throw new DocumentNotFoundError()\n }\n const context = await workspacePolicyContext(\n options.database,\n { workspaceId },\n { actorId: actor.userId, deploymentMode: options.deploymentMode }\n )\n if (!context) throw new DocumentNotFoundError()\n const [enabled, allowance] = await Promise.all([\n options.policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),\n options.policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)\n ])\n if (!enabled) throw new ServicesNotEntitledError()\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAt = issuedAt + options.lifetimeSeconds\n const token = await new SignJWT({\n workspaceId,\n // Credits are the owner's, shared by every workspace they own.\n accountId: context.targetingKey,\n monthlyCreditAllowance: allowance < 0 ? null : allowance\n })\n .setProtectedHeader({ alg: SERVICES_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })\n .setIssuer(options.issuer)\n .setAudience(CLOUD_SERVICES_TOKEN_AUDIENCE)\n .setSubject(actor.userId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(privateKey)\n return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }\n },\n\n jwks() {\n return { keys: [publicJWK] }\n }\n }\n}\n\nexport type ServicesTokenService = ReturnType<typeof createServicesTokenService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nexport async function requireSharingAccess(\n database: Kysely<CloudDatabase>,\n userId: string,\n documentId: string\n): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!access.canManageSharing) throw new DocumentForbiddenError()\n}\n\n/**\n * Ends every collaboration ticket and room key issued for the document so far: removing someone's\n * access must also remove them from its live room.\n */\nexport async function advanceCollaborationEpoch(\n database: Kysely<CloudDatabase>,\n documentId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1) })\n .where('id', '=', documentId)\n .executeTakeFirst()\n}\n","import { pickBy } from 'es-toolkit/object'\nimport { isNotNil } from 'es-toolkit/predicate'\nimport * as v from 'valibot'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport {\n staticEntitlementsSchema,\n staticEntitlementsTOMLSchema,\n type StaticEntitlements\n} from './schema'\n\n/** Entitlements as a writer sends them, with any group left out. */\nexport type StaticEntitlementsInput = v.InferInput<typeof staticEntitlementsSchema>\n\n/** Entitlements as the deployment TOML spells them, renamed to their structured form. */\nexport function staticEntitlementsFromTOML(\n value: v.InferOutput<typeof staticEntitlementsTOMLSchema>\n): StaticEntitlements {\n return v.parse(staticEntitlementsSchema, {\n documents: {\n maximumFileBytes: value.documents?.maximum_file_bytes,\n revisionHistory: value.documents?.revision_history\n },\n storage: { maximumBytes: value.storage?.maximum_bytes },\n sharing: {\n links: value.sharing?.links,\n guestView: value.sharing?.guest_view,\n guestEdit: value.sharing?.guest_edit,\n guestPresence: value.sharing?.guest_presence\n },\n collaboration: {\n enabled: value.collaboration?.enabled,\n maximumParticipants: value.collaboration?.maximum_participants\n },\n services: {\n enabled: value.services?.enabled,\n monthlyCreditAllowance: value.services?.monthly_credit_allowance\n }\n })\n}\n\nexport function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {\n return staticEntitlementsFromTOML(v.parse(staticEntitlementsTOMLSchema, input))\n}\n\nexport function staticEntitlementValues(input: unknown): Record<string, boolean | number> {\n const entitlements = v.parse(staticEntitlementsSchema, input)\n const values: Record<string, boolean | number | undefined> = {\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: entitlements.documents.maximumFileBytes,\n [CLOUD_FEATURE_KEYS.revisionHistory]: entitlements.documents.revisionHistory,\n [CLOUD_FEATURE_KEYS.maximumStorageBytes]: entitlements.storage.maximumBytes,\n [CLOUD_FEATURE_KEYS.links]: entitlements.sharing.links,\n [CLOUD_FEATURE_KEYS.guestView]: entitlements.sharing.guestView,\n [CLOUD_FEATURE_KEYS.guestEdit]: entitlements.sharing.guestEdit,\n [CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,\n [CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,\n [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,\n [CLOUD_FEATURE_KEYS.cloudServices]: entitlements.services.enabled,\n [CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.services.monthlyCreditAllowance\n }\n return pickBy(values, isNotNil) as Record<string, boolean | number>\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\nimport { staticEntitlementsSchema } from './schema'\nimport { staticEntitlementValues, type StaticEntitlementsInput } from './static'\n\n/**\n * Each account's stored entitlements, value by value over `defaults`: what an account takes until\n * billing or an operator stores its own, and whatever a stored plan leaves out.\n */\nexport class DatabaseEntitlementSource implements EntitlementSource {\n constructor(\n private readonly database: Kysely<CloudDatabase>,\n private readonly defaults: Record<string, boolean | number> = {}\n ) {}\n\n private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {\n if (subject.type !== 'user') return {}\n const row = await this.database\n .selectFrom('accountEntitlement')\n .select('values')\n .where('userId', '=', subject.id)\n .executeTakeFirst()\n if (!row) return this.defaults\n return {\n ...this.defaults,\n ...staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values))\n }\n }\n\n async boolean(subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, _key: string): Promise<string | null> {\n return null\n }\n}\n\n/** Each account's stored entitlements, which every workspace it owns takes. */\nconst accountIdSchema = v.pipe(v.string(), v.uuid())\n\nexport function createAccountEntitlementRepository(database: Kysely<CloudDatabase>) {\n return {\n /**\n * The account `userId` names, as the user table spells it, or null when there is none, so a\n * plan is stored under the key policy reads, whatever case the caller wrote the ID in.\n */\n async account(userId: string): Promise<string | null> {\n if (!v.is(accountIdSchema, userId)) return null\n const user = await database\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .executeTakeFirst()\n return user?.id ?? null\n },\n\n async get(userId: string) {\n return database\n .selectFrom('accountEntitlement')\n .selectAll()\n .where('userId', '=', userId)\n .executeTakeFirst()\n },\n\n async set(userId: string, values: StaticEntitlementsInput, source: string) {\n const validated = v.parse(staticEntitlementsSchema, values)\n return database\n .insertInto('accountEntitlement')\n .values({ userId, values: validated, source })\n .onConflict((conflict) =>\n conflict.column('userId').doUpdateSet({\n values: validated,\n source,\n revision: (expression) => expression('accountEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n )\n .returningAll()\n .executeTakeFirstOrThrow()\n },\n\n /**\n * Stores entitlements an external writer versioned, unless the stored row carries a newer\n * version: billing events arrive out of order, and a late one must not undo a newer plan.\n * An unversioned row, such as one an operator set, is replaced.\n */\n async setVersioned(\n userId: string,\n values: StaticEntitlementsInput,\n source: string,\n externalVersion: number\n ): Promise<{ applied: boolean }> {\n const validated = v.parse(staticEntitlementsSchema, values)\n const row = await database\n .insertInto('accountEntitlement')\n .values({ userId, values: validated, source, externalVersion })\n .onConflict((conflict) =>\n conflict\n .column('userId')\n .doUpdateSet({\n values: validated,\n source,\n externalVersion,\n revision: (expression) => expression('accountEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n .where((expression) =>\n expression.or([\n expression('accountEntitlement.externalVersion', 'is', null),\n expression('accountEntitlement.externalVersion', '<', externalVersion)\n ])\n )\n )\n .returning('userId')\n .executeTakeFirst()\n return { applied: row !== undefined }\n },\n\n async clear(userId: string): Promise<void> {\n await database.deleteFrom('accountEntitlement').where('userId', '=', userId).execute()\n }\n }\n}\n","export type EntitlementSubject = {\n type: 'workspace' | 'user' | 'organization' | 'deployment'\n id: string\n}\n\nexport type EntitlementSource = {\n boolean(subject: EntitlementSubject, key: string): Promise<boolean | null>\n number(subject: EntitlementSubject, key: string): Promise<number | null>\n string(subject: EntitlementSubject, key: string): Promise<string | null>\n}\n\nexport class StaticEntitlementSource implements EntitlementSource {\n constructor(private readonly values: Readonly<Record<string, boolean | number | string>>) {}\n\n async boolean(_subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = this.values[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(_subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = this.values[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, key: string): Promise<string | null> {\n const value = this.values[key]\n return typeof value === 'string' ? value : null\n }\n}\n","import {\n type EvaluationContext,\n type Logger,\n type Provider,\n type ProviderMetadata,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\n\nfunction subject(context: EvaluationContext): EntitlementSubject {\n const type = context.subjectType\n return {\n type: type === 'user' || type === 'organization' || type === 'deployment' ? type : 'workspace',\n id: context.targetingKey ?? 'deployment'\n }\n}\n\nexport class EntitlementOpenFeatureProvider implements Provider {\n readonly metadata: ProviderMetadata = { name: 'openpencil-entitlements' }\n readonly runsOn = 'server' as const\n\n constructor(private readonly source: EntitlementSource) {}\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const value = await this.source.boolean(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const value = await this.source.number(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const value = await this.source.string(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveObjectEvaluation<T>(\n _flagKey: string,\n defaultValue: T\n ): Promise<ResolutionDetails<T>> {\n return { value: defaultValue, reason: 'DEFAULT' }\n }\n}\n","import { cloudEditorVersionSchema } from '#cloud/contract'\nimport { deletedPrefixSchema } from '#cloud/server/config/schema'\nimport { staticEntitlementsTOMLSchema } from '#cloud/server/policy/schema'\nimport * as v from 'valibot'\n\n/*\n * The deployment file, `openpencil-cloud.toml`: what an operator writes, with secrets named by the\n * environment variables that hold them. `../deployment.ts` reads it into the server's configuration.\n */\n\n/** PostHog's EU Cloud ingestion host, where OpenPencil's own project is. */\nconst POSTHOG_DEFAULT_HOST = 'https://eu.i.posthog.com'\n\nconst DEFAULT_SECRET_NAMES = {\n databaseURL: 'DATABASE_URL',\n authSecret: 'BETTER_AUTH_SECRET',\n googleClientId: 'GOOGLE_CLIENT_ID',\n googleClientSecret: 'GOOGLE_CLIENT_SECRET',\n applePrivateKey: 'APPLE_PRIVATE_KEY',\n githubClientSecret: 'GITHUB_CLIENT_SECRET',\n s3AccessKeyId: 'S3_ACCESS_KEY_ID',\n s3SecretAccessKey: 'S3_SECRET_ACCESS_KEY',\n s3SessionToken: 'S3_SESSION_TOKEN',\n smtpUser: 'OPENPENCIL_CLOUD_SMTP_USER',\n smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',\n turnstileSecretKey: 'TURNSTILE_SECRET_KEY',\n servicesSigningKey: 'OPENPENCIL_CLOUD_SERVICES_SIGNING_KEY',\n internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN',\n posthogProjectAPIKey: 'POSTHOG_PROJECT_API_KEY'\n} as const\n\nconst urlSchema = v.pipe(v.string(), v.url())\nconst textSchema = v.pipe(v.string(), v.trim(), v.minLength(1))\nconst positiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1))\nconst secretReferenceSchema = v.strictObject({ from_env: textSchema })\nconst configurableTextSchema = v.union([textSchema, secretReferenceSchema])\nconst defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })\n\nconst providerSchema = v.strictObject({\n google: v.optional(\n v.strictObject({\n client_id: v.optional(configurableTextSchema, {\n from_env: DEFAULT_SECRET_NAMES.googleClientId\n }),\n client_secret: defaultReference(DEFAULT_SECRET_NAMES.googleClientSecret)\n })\n ),\n apple: v.optional(\n v.strictObject({\n client_id: textSchema,\n team_id: textSchema,\n key_id: textSchema,\n private_key: defaultReference(DEFAULT_SECRET_NAMES.applePrivateKey),\n app_bundle_identifier: v.optional(textSchema)\n })\n ),\n github: v.optional(\n v.strictObject({\n client_id: configurableTextSchema,\n client_secret: defaultReference(DEFAULT_SECRET_NAMES.githubClientSecret)\n })\n )\n})\n\n/** Where replies go, when someone reads the email and writes back; `from` otherwise. */\nconst replyToSchema = v.optional(v.pipe(v.string(), v.email()))\n\nconst emailSchema = v.optional(\n v.variant('transport', [\n v.strictObject({ transport: v.literal('none') }),\n v.strictObject({\n transport: v.literal('smtp'),\n from: textSchema,\n reply_to: replyToSchema,\n smtp: v.strictObject({\n host: textSchema,\n port: positiveIntegerSchema,\n secure: v.optional(v.boolean()),\n user: v.optional(secretReferenceSchema, {\n from_env: DEFAULT_SECRET_NAMES.smtpUser\n }),\n password: v.optional(secretReferenceSchema, {\n from_env: DEFAULT_SECRET_NAMES.smtpPassword\n })\n })\n }),\n v.strictObject({\n transport: v.literal('cloudflare'),\n from: textSchema,\n reply_to: replyToSchema\n })\n ]),\n { transport: 'none' }\n)\n\n/**\n * Every table is strict: a key the schema doesn't know, such as one renamed since, stops startup\n * instead of leaving its setting at a default the operator never chose.\n */\nexport const cloudDeploymentConfigSchema = v.strictObject({\n schema_version: v.literal(2),\n deployment: v.strictObject({\n mode: v.picklist(['official', 'self-hosted']),\n public_url: urlSchema,\n indexing: v.optional(v.picklist(['allow', 'deny']), 'deny'),\n trusted_origins: v.optional(v.array(urlSchema), []),\n // The server's editor works with files on this device without signing in to the server.\n local_editor: v.optional(v.boolean(), true),\n listing: v.optional(v.strictObject({ minimum_editor_version: cloudEditorVersionSchema })),\n // How a self-hosted server names itself on its public pages.\n branding: v.optional(\n v.strictObject({\n name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n logo_url: v.optional(urlSchema),\n help_url: v.optional(urlSchema)\n })\n ),\n // Older editors ask to be updated, and the server refuses their requests.\n minimum_editor_version: v.optional(cloudEditorVersionSchema)\n }),\n database: v.optional(\n v.strictObject({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }),\n {\n url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }\n }\n ),\n authentication: v.strictObject({\n secret: defaultReference(DEFAULT_SECRET_NAMES.authSecret),\n enrollment: v.optional(\n v.strictObject({\n mode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),\n notification_emails: v.optional(v.array(v.pipe(v.string(), v.email())), [])\n }),\n { mode: 'open', notification_emails: [] }\n ),\n email_password: v.optional(\n v.strictObject({\n enabled: v.optional(v.boolean(), false),\n sign_up: v.optional(v.boolean(), true),\n minimum_password_length: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),\n 8\n ),\n maximum_password_length: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),\n 128\n ),\n verification_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),\n password_reset_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),\n compromised_password_check: v.optional(v.boolean(), false)\n }),\n {\n enabled: false,\n sign_up: true,\n minimum_password_length: 8,\n maximum_password_length: 128,\n verification_link_lifetime_minutes: 60,\n password_reset_link_lifetime_minutes: 60,\n compromised_password_check: false\n }\n ),\n mfa: v.optional(\n v.strictObject({\n required_for_admins: v.optional(v.boolean(), false),\n totp: v.optional(v.boolean(), false),\n recovery_codes: v.optional(v.boolean(), false),\n trusted_device_lifetime_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14)\n }),\n {\n required_for_admins: false,\n totp: false,\n recovery_codes: false,\n trusted_device_lifetime_days: 14\n }\n ),\n // Passkeys belong to public_url's host and origin.\n passkeys: v.optional(\n v.strictObject({\n enabled: v.optional(v.boolean(), false),\n rp_name: v.optional(textSchema, 'OpenPencil Cloud')\n }),\n { enabled: false, rp_name: 'OpenPencil Cloud' }\n ),\n captcha: v.optional(\n v.strictObject({\n provider: v.literal('cloudflare-turnstile'),\n site_key: textSchema,\n secret_key: defaultReference(DEFAULT_SECRET_NAMES.turnstileSecretKey),\n allowed_hostnames: v.optional(v.array(textSchema), [])\n })\n ),\n trusted_proxies: v.optional(\n v.strictObject({\n headers: v.optional(v.array(textSchema), []),\n addresses: v.optional(v.array(textSchema), [])\n }),\n { headers: [], addresses: [] }\n ),\n providers: v.optional(providerSchema, {})\n }),\n object_storage: v.strictObject({\n endpoint: urlSchema,\n region: textSchema,\n bucket: textSchema,\n credentials: v.optional(\n v.strictObject({\n access_key_id: defaultReference(DEFAULT_SECRET_NAMES.s3AccessKeyId),\n secret_access_key: defaultReference(DEFAULT_SECRET_NAMES.s3SecretAccessKey),\n session_token: v.optional(secretReferenceSchema, {\n from_env: DEFAULT_SECRET_NAMES.s3SessionToken\n })\n }),\n {\n access_key_id: { from_env: DEFAULT_SECRET_NAMES.s3AccessKeyId },\n secret_access_key: { from_env: DEFAULT_SECRET_NAMES.s3SecretAccessKey }\n }\n ),\n force_path_style: v.optional(v.boolean(), true),\n checksum_verification: v.optional(v.picklist(['native', 'metadata']), 'native'),\n server_side_encryption: v.optional(v.picklist(['AES256', 'aws:kms'])),\n kms_key_id: v.optional(textSchema),\n /**\n * Keeps each file cleanup deletes under this prefix, such as `deleted/`, so a database restored\n * to an earlier time still finds it; a lifecycle rule on the prefix expires them.\n */\n deleted_prefix: v.optional(deletedPrefixSchema),\n maximum_upload_bytes: v.optional(positiveIntegerSchema)\n }),\n collaboration: v.optional(\n v.strictObject({\n relay_url: v.optional(urlSchema),\n maximum_message_bytes: v.optional(positiveIntegerSchema),\n maximum_connections_per_room: v.optional(positiveIntegerSchema)\n }),\n {}\n ),\n documents: v.optional(\n v.strictObject({\n retention_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 30),\n purge_grace_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 7)\n }),\n { retention_days: 30, purge_grace_days: 7 }\n ),\n email: emailSchema,\n workers: v.optional(\n v.strictObject({\n email: v.optional(\n v.strictObject({\n batch_size: v.optional(positiveIntegerSchema, 50),\n interval_ms: v.optional(positiveIntegerSchema, 30_000),\n lease_ms: v.optional(positiveIntegerSchema, 300_000),\n maximum_attempts: v.optional(positiveIntegerSchema, 5)\n }),\n { batch_size: 50, interval_ms: 30_000, lease_ms: 300_000, maximum_attempts: 5 }\n ),\n cleanup: v.optional(\n v.strictObject({\n enabled: v.optional(v.boolean(), true),\n batch_size: v.optional(positiveIntegerSchema, 100),\n interval_ms: v.optional(positiveIntegerSchema, 60_000),\n lease_ms: v.optional(positiveIntegerSchema, 300_000)\n }),\n { enabled: true, batch_size: 100, interval_ms: 60_000, lease_ms: 300_000 }\n )\n })\n ),\n entitlements: v.optional(\n v.variant('source', [\n v.strictObject({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),\n // The values every account takes until billing or an operator stores its own: the free plan.\n v.strictObject({ source: v.literal('database'), ...staticEntitlementsTOMLSchema.entries })\n ])\n ),\n services: v.optional(\n v.strictObject({\n endpoint: urlSchema,\n signing_key: defaultReference(DEFAULT_SECRET_NAMES.servicesSigningKey),\n token_lifetime_minutes: v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(60)),\n 10\n )\n })\n ),\n billing: v.optional(v.strictObject({ endpoint: urlSchema })),\n internal_api: v.optional(\n v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })\n ),\n /**\n * Optional: the operator's terms and privacy policy, linked at sign-up and in the portal, and\n * with `require_acceptance`, accepted once per `terms_version` before an account uses the server.\n */\n legal: v.optional(\n v.strictObject({\n terms_url: v.optional(urlSchema),\n privacy_url: v.optional(urlSchema),\n terms_version: v.optional(textSchema),\n require_acceptance: v.optional(v.boolean(), false),\n abuse_email: v.optional(v.pipe(v.string(), v.email())),\n minimum_age: v.optional(v.pipe(v.number(), v.integer(), v.minValue(13), v.maxValue(21)))\n })\n ),\n /**\n * Optional: a workspace whose documents anyone may open read-only, without signing in or a\n * link, as the deployment's community gallery. Everything saved there is public. `tour` names\n * the gallery document the editor opens as its tour, and the docs landing shows.\n */\n community: v.optional(\n v.strictObject({\n workspace: v.pipe(v.string(), v.uuid()),\n tour: v.optional(v.pipe(v.string(), v.uuid()))\n })\n ),\n /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */\n error_tracking: v.optional(\n v.strictObject({\n provider: v.literal('posthog'),\n host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),\n project_api_key: v.optional(configurableTextSchema, {\n from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey\n }),\n /** Send the account and record IDs an error involved; off, reports name neither. */\n include_ids: v.optional(v.boolean(), false)\n })\n )\n})\n\nexport type CloudDeploymentConfig = v.InferOutput<typeof cloudDeploymentConfigSchema>\n/** Deployment configuration as an operator writes it, before defaults are applied. */\nexport type CloudDeploymentInput = v.InferInput<typeof cloudDeploymentConfigSchema>\nexport type CloudSecretReference = v.InferOutput<typeof secretReferenceSchema>\n","import { staticEntitlementsFromTOML } from '#cloud/server/policy/static'\nimport { parse as parseTOML } from 'smol-toml'\nimport * as v from 'valibot'\n\nimport { DAY_MS } from '@open-pencil/std/timing'\n\nimport { parseCloudServerConfig, type CloudServerConfig } from './schema'\nimport {\n cloudDeploymentConfigSchema,\n type CloudDeploymentConfig,\n type CloudSecretReference\n} from './toml/schema'\n\nexport type CloudEnvironment = Readonly<Record<string, string | undefined>>\n\nexport function parseCloudDeploymentSource(source: string): CloudDeploymentConfig {\n return v.parse(cloudDeploymentConfigSchema, parseTOML(source))\n}\n\nfunction requiredSecret(environment: CloudEnvironment, reference: CloudSecretReference): string {\n const value = environment[reference.from_env]\n if (!value) throw new Error(`Required secret binding is unavailable: ${reference.from_env}`)\n return value\n}\n\nfunction configuredText(\n environment: CloudEnvironment,\n value: string | CloudSecretReference\n): string {\n return typeof value === 'string' ? value : requiredSecret(environment, value)\n}\n\nfunction optionalSecret(\n environment: CloudEnvironment,\n reference?: CloudSecretReference\n): string | undefined {\n return reference ? environment[reference.from_env] : undefined\n}\n\nfunction staticEntitlements(config: CloudDeploymentConfig) {\n if (config.entitlements?.source !== 'static') return undefined\n return staticEntitlementsFromTOML(config.entitlements)\n}\n\nfunction defaultEntitlements(config: CloudDeploymentConfig) {\n if (config.entitlements?.source !== 'database') return undefined\n return staticEntitlementsFromTOML(config.entitlements)\n}\n\nfunction emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n if (config.email.transport === 'none') return { emailTransport: 'none' as const }\n if (config.email.transport === 'cloudflare') {\n return {\n emailTransport: 'cloudflare' as const,\n emailFrom: config.email.from,\n emailReplyTo: config.email.reply_to\n }\n }\n return {\n emailTransport: 'smtp' as const,\n emailFrom: config.email.from,\n emailReplyTo: config.email.reply_to,\n smtpHost: config.email.smtp.host,\n smtpPort: config.email.smtp.port,\n smtpSecure: config.email.smtp.secure,\n smtpUser: optionalSecret(environment, config.email.smtp.user),\n smtpPassword: optionalSecret(environment, config.email.smtp.password)\n }\n}\n\nfunction authenticationConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n const google = config.authentication.providers.google\n const apple = config.authentication.providers.apple\n const github = config.authentication.providers.github\n return {\n googleClientId: google ? configuredText(environment, google.client_id) : undefined,\n googleClientSecret: google ? requiredSecret(environment, google.client_secret) : undefined,\n appleClientId: apple?.client_id,\n appleTeamId: apple?.team_id,\n appleKeyId: apple?.key_id,\n applePrivateKey: apple ? requiredSecret(environment, apple.private_key) : undefined,\n appleAppBundleIdentifier: apple?.app_bundle_identifier,\n githubClientId: github ? configuredText(environment, github.client_id) : undefined,\n githubClientSecret: github ? requiredSecret(environment, github.client_secret) : undefined\n }\n}\n\nfunction workerConfig(config: CloudDeploymentConfig) {\n const email = config.workers?.email\n const cleanup = config.workers?.cleanup\n return {\n emailBatchSize: email?.batch_size,\n emailIntervalMs: email?.interval_ms,\n emailLeaseDurationMs: email?.lease_ms,\n emailMaximumAttempts: email?.maximum_attempts,\n cleanupEnabled: cleanup?.enabled,\n cleanupBatchSize: cleanup?.batch_size,\n cleanupIntervalMs: cleanup?.interval_ms,\n cleanupLeaseDurationMs: cleanup?.lease_ms,\n documentRetentionMs: config.documents.retention_days * DAY_MS,\n documentPurgeGraceMs: config.documents.purge_grace_days * DAY_MS\n }\n}\n\nfunction serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n return {\n servicesEndpoint: config.services?.endpoint,\n servicesSigningKey: config.services\n ? requiredSecret(environment, config.services.signing_key)\n : undefined,\n servicesTokenLifetimeSeconds: config.services\n ? config.services.token_lifetime_minutes * 60\n : undefined,\n billingEndpoint: config.billing?.endpoint,\n internalServiceToken: config.internal_api\n ? requiredSecret(environment, config.internal_api.service_token)\n : undefined\n }\n}\n\nfunction legalConfig(config: CloudDeploymentConfig) {\n const legal = config.legal\n if (!legal) return undefined\n return {\n termsURL: legal.terms_url,\n privacyURL: legal.privacy_url,\n termsVersion: legal.terms_version,\n requireAcceptance: legal.require_acceptance,\n abuseEmail: legal.abuse_email,\n minimumAge: legal.minimum_age\n }\n}\n\nfunction errorTrackingConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n const tracking = config.error_tracking\n if (!tracking) return undefined\n return {\n provider: tracking.provider,\n host: tracking.host,\n projectAPIKey: configuredText(environment, tracking.project_api_key),\n includeIds: tracking.include_ids\n }\n}\n\n/** Hard limits, whatever a plan allows; each lives in the section it limits. */\nfunction technicalLimits(config: CloudDeploymentConfig) {\n return {\n maximumUploadBytes: config.object_storage.maximum_upload_bytes,\n maximumCollaborationMessageBytes: config.collaboration.maximum_message_bytes,\n maximumConnectionsPerRoom: config.collaboration.maximum_connections_per_room\n }\n}\n\nexport function parseCloudDeploymentConfig(\n input: unknown,\n environment: CloudEnvironment\n): CloudServerConfig {\n const config = v.parse(cloudDeploymentConfigSchema, input)\n return parseCloudServerConfig({\n deployment: config.deployment.mode,\n publicURL: config.deployment.public_url,\n indexingPolicy: config.deployment.indexing,\n trustedOrigins: config.deployment.trusted_origins,\n localEditor: config.deployment.local_editor,\n listingMinimumEditorVersion: config.deployment.listing?.minimum_editor_version,\n minimumEditorVersion: config.deployment.minimum_editor_version,\n databaseURL: requiredSecret(environment, config.database.url),\n authSecret: requiredSecret(environment, config.authentication.secret),\n enrollmentMode: config.authentication.enrollment.mode,\n enrollmentAdminNotificationEmails: config.authentication.enrollment.notification_emails,\n emailPasswordEnabled: config.authentication.email_password.enabled,\n emailPasswordSignUpEnabled: config.authentication.email_password.sign_up,\n emailPasswordMinimumLength: config.authentication.email_password.minimum_password_length,\n emailPasswordMaximumLength: config.authentication.email_password.maximum_password_length,\n emailVerificationExpiresIn:\n config.authentication.email_password.verification_link_lifetime_minutes * 60,\n passwordResetExpiresIn:\n config.authentication.email_password.password_reset_link_lifetime_minutes * 60,\n compromisedPasswordCheck: config.authentication.email_password.compromised_password_check,\n deploymentAdminMFARequired: config.authentication.mfa.required_for_admins,\n totpEnabled: config.authentication.mfa.totp,\n recoveryCodesEnabled: config.authentication.mfa.recovery_codes,\n mfaTrustedDeviceDays: config.authentication.mfa.trusted_device_lifetime_days,\n passkeysEnabled: config.authentication.passkeys.enabled,\n passkeyRPName: config.authentication.passkeys.rp_name,\n captchaProvider: config.authentication.captcha?.provider,\n captchaSiteKey: config.authentication.captcha?.site_key,\n captchaSecretKey: config.authentication.captcha\n ? requiredSecret(environment, config.authentication.captcha.secret_key)\n : undefined,\n captchaAllowedHostnames: config.authentication.captcha?.allowed_hostnames,\n authTrustedIPHeaders: config.authentication.trusted_proxies.headers,\n authTrustedProxies: config.authentication.trusted_proxies.addresses,\n ...authenticationConfig(config, environment),\n s3Endpoint: config.object_storage.endpoint,\n s3Region: config.object_storage.region,\n s3Bucket: config.object_storage.bucket,\n s3AccessKeyId: requiredSecret(environment, config.object_storage.credentials.access_key_id),\n s3SecretAccessKey: requiredSecret(\n environment,\n config.object_storage.credentials.secret_access_key\n ),\n s3SessionToken: environment[config.object_storage.credentials.session_token.from_env],\n s3ForcePathStyle: config.object_storage.force_path_style,\n s3ChecksumVerification: config.object_storage.checksum_verification,\n s3ServerSideEncryption: config.object_storage.server_side_encryption,\n s3KmsKeyId: config.object_storage.kms_key_id,\n s3DeletedPrefix: config.object_storage.deleted_prefix,\n relayURL: config.collaboration.relay_url,\n staticEntitlements: staticEntitlements(config),\n defaultEntitlements: defaultEntitlements(config),\n ...emailConfig(config, environment),\n ...workerConfig(config),\n ...serviceConfig(config, environment),\n legal: legalConfig(config),\n community: config.community\n ? { workspaceId: config.community.workspace, tourDocumentId: config.community.tour }\n : undefined,\n branding: config.deployment.branding && {\n name: config.deployment.branding.name,\n logoURL: config.deployment.branding.logo_url,\n helpURL: config.deployment.branding.help_url\n },\n errorTracking: errorTrackingConfig(config, environment),\n technicalLimits: technicalLimits(config)\n })\n}\n\nexport function parseCloudDeploymentTOML(\n source: string,\n environment: CloudEnvironment\n): CloudServerConfig {\n return parseCloudDeploymentConfig(parseCloudDeploymentSource(source), environment)\n}\n","import {\n CLOUD_BILLING_CONTRACT_VERSION,\n type BillingFreePlan,\n CLOUD_SERVICES_CONTRACT_VERSION,\n CLOUD_PROTOCOL_VERSION,\n parseCloudDiscovery,\n type CloudDiscovery\n} from '#cloud/contract'\nimport { configuredSocialProviders } from '#cloud/server/auth/social-providers'\nimport { withoutTrailingSlash } from 'ufo'\n\nimport type { CloudServerConfig } from './schema'\n\n/**\n * The free plan billing compares its plans with: what an account takes before billing stores its\n * own, as the deployment's default entitlements say. Services without an allowance have no monthly\n * limit, as the services token says of them too.\n */\nfunction freePlan(config: CloudServerConfig): BillingFreePlan {\n const { storage, services } = config.defaultEntitlements ?? {}\n return {\n storageBytes: storage?.maximumBytes ?? null,\n services: services?.enabled ?? false,\n monthlyCredits: services?.monthlyCreditAllowance ?? null\n }\n}\n\nexport function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscovery {\n const authentication: CloudDiscovery['authentication'] = {\n socialProviders: configuredSocialProviders(config),\n enterpriseSSO: false,\n enrollmentMode: config.enrollmentMode\n }\n if (config.emailPasswordEnabled) {\n authentication.emailPassword = {\n signIn: true,\n signUp: config.emailPasswordSignUpEnabled,\n minimumPasswordLength: config.emailPasswordMinimumLength\n }\n if (config.captchaProvider && config.captchaSiteKey) {\n authentication.emailPassword.captcha = {\n provider: config.captchaProvider,\n siteKey: config.captchaSiteKey\n }\n }\n }\n if (config.totpEnabled || config.passkeysEnabled) {\n authentication.mfa = {\n deploymentAdminRequired: config.deploymentAdminMFARequired,\n totp: config.totpEnabled,\n passkeys: config.passkeysEnabled,\n recoveryCodes: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n\n return parseCloudDiscovery({\n protocolVersion: CLOUD_PROTOCOL_VERSION,\n deployment: config.deployment,\n apiURL: withoutTrailingSlash(new URL('/api', config.publicURL).href),\n authURL: withoutTrailingSlash(new URL('/api/auth', config.publicURL).href),\n localEditor: config.localEditor,\n authentication,\n capabilities: {\n documents: true,\n workspaces: true,\n collaboration: true\n },\n listing: config.listingMinimumEditorVersion\n ? { minimumEditorVersion: config.listingMinimumEditorVersion }\n : undefined,\n minimumEditorVersion: config.minimumEditorVersion,\n services: config.servicesEndpoint\n ? { endpoint: config.servicesEndpoint, contractVersion: CLOUD_SERVICES_CONTRACT_VERSION }\n : undefined,\n billing: config.billingEndpoint\n ? {\n endpoint: config.billingEndpoint,\n contractVersion: CLOUD_BILLING_CONTRACT_VERSION,\n freePlan: freePlan(config)\n }\n : undefined,\n community: config.community,\n branding: config.branding,\n legal: config.legal\n })\n}\n","import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'\nimport {\n DefaultLogger,\n ErrorCode,\n OpenFeatureError,\n TypedInMemoryProvider,\n type EvaluationContext,\n type Provider,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'\n\nconst DEFAULT_FLAGS = {\n [CLOUD_FEATURE_KEYS.links]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestView]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestEdit]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestPresence]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.collaboration]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.serverEnforcedWrites]: {\n variants: { enabled: false, disabled: false },\n defaultVariant: 'disabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.revisionHistory]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: {\n variants: { default: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES },\n defaultVariant: 'default',\n disabled: false\n }\n} as const\n\nfunction evaluationContext(context: CloudPolicyContext): EvaluationContext {\n const evaluation: EvaluationContext = {\n targetingKey: context.targetingKey,\n deploymentMode: context.deploymentMode\n }\n evaluation.subjectType = context.subjectType\n if (context.actorId) evaluation.actorId = context.actorId\n if (context.workspaceId) evaluation.workspaceId = context.workspaceId\n if (context.organizationId) evaluation.organizationId = context.organizationId\n if (context.documentId) evaluation.documentId = context.documentId\n return evaluation\n}\n\nconst logger = new DefaultLogger()\n\n/** A flag's value, or the default when the provider failed or reported an error, as a client does. */\nasync function resolved<T>(evaluation: () => Promise<ResolutionDetails<T>>, defaultValue: T) {\n return (await resolution(evaluation, defaultValue)).value\n}\n\n/**\n * A flag's value, and whether the provider failed to answer. A flag it doesn't know is no failure:\n * the default stands for it, as for a plan that sets no value.\n */\nasync function resolution<T>(\n evaluation: () => Promise<ResolutionDetails<T>>,\n defaultValue: T\n): Promise<{ value: T; failed: boolean }> {\n try {\n const details = await evaluation()\n if (!details.errorCode) return { value: details.value, failed: false }\n return { value: defaultValue, failed: details.errorCode !== ErrorCode.FLAG_NOT_FOUND }\n } catch (error) {\n const unknown = error instanceof OpenFeatureError && error.code === ErrorCode.FLAG_NOT_FOUND\n return { value: defaultValue, failed: !unknown }\n }\n}\n\n/**\n * Answers entitlement questions from one OpenFeature provider. It asks the provider directly\n * rather than through the global `OpenFeature` API: each app has its own provider, and the API\n * keeps every provider registered under a domain reachable for the life of the process, with the\n * database its entitlement source holds.\n */\nexport class CloudPolicy {\n constructor(private readonly provider: Provider) {}\n\n boolean(key: string, defaultValue: boolean, context: CloudPolicyContext): Promise<boolean> {\n return resolved(\n () =>\n this.provider.resolveBooleanEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n ),\n defaultValue\n )\n }\n\n number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {\n return resolved(() => this.evaluateNumber(key, defaultValue, context), defaultValue)\n }\n\n /**\n * Like `number`, and says whether the provider failed to answer, for a caller that must not\n * take the default for an answer, such as one that undoes something when a limit is gone.\n */\n numberResolution(\n key: string,\n defaultValue: number,\n context: CloudPolicyContext\n ): Promise<{ value: number; failed: boolean }> {\n return resolution(() => this.evaluateNumber(key, defaultValue, context), defaultValue)\n }\n\n private evaluateNumber(key: string, defaultValue: number, context: CloudPolicyContext) {\n return this.provider.resolveNumberEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n )\n }\n}\n\nexport function createDefaultCloudPolicy(provider?: Provider): CloudPolicy {\n return new CloudPolicy(provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nimport { DatabaseEntitlementSource } from './database'\nimport { StaticEntitlementSource } from './entitlements'\nimport { createDefaultCloudPolicy } from './policy'\nimport { EntitlementOpenFeatureProvider } from './provider'\nimport { staticEntitlementValues } from './static'\n\n/**\n * The policy a deployment configures: its static entitlements, or the database's, over the\n * defaults an account without stored entitlements takes.\n */\nexport function createConfiguredCloudPolicy(\n config: Pick<CloudServerConfig, 'staticEntitlements' | 'defaultEntitlements'>,\n database: Kysely<CloudDatabase>\n) {\n return createDefaultCloudPolicy(\n new EntitlementOpenFeatureProvider(\n config.staticEntitlements\n ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))\n : new DatabaseEntitlementSource(\n database,\n config.defaultEntitlements ? staticEntitlementValues(config.defaultEntitlements) : {}\n )\n )\n )\n}\n","import type { AccountEntitlements, WorkspaceEntitlements } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { createStorageQuotaService, type StorageQuotaSnapshot } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nimport { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'\nimport type { CloudPolicy } from './policy'\nimport { workspacePolicyContext } from './workspace'\n\nexport function createEntitlementService(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n technicalMaximumFileBytes: number,\n technicalMaximumParticipants = Number.MAX_SAFE_INTEGER\n) {\n const quota = createStorageQuotaService(database)\n return {\n /** A workspace's entitlements: its owner's plan and pooled storage, for any member to read. */\n async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {\n if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()\n const context = await workspacePolicyContext(\n database,\n { workspaceId },\n { actorId: userId, deploymentMode: 'self-hosted' }\n )\n if (!context) throw new DocumentNotFoundError()\n const [entitlements, usage] = await Promise.all([\n resolve(context),\n quota.snapshot(workspaceId)\n ])\n // The workspace may have gone since its role was read; it has no usage to report then.\n if (!usage) throw new DocumentNotFoundError()\n return { ...entitlements, usage: storageUsage(usage) }\n },\n\n /** The signed-in account's own plan, and the storage its workspaces hold together. */\n async account(userId: string): Promise<AccountEntitlements> {\n const [entitlements, usage] = await Promise.all([\n resolve({\n targetingKey: userId,\n subjectType: 'user',\n actorId: userId,\n deploymentMode: 'self-hosted'\n }),\n quota.account(userId)\n ])\n return { ...entitlements, usage: storageUsage(usage) }\n }\n }\n\n async function resolve(\n context: CloudPolicyContext\n ): Promise<Omit<WorkspaceEntitlements, 'usage'>> {\n const [\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudServices,\n maximumFileBytes,\n maximumStorage,\n maximumParticipants,\n monthlyCreditAllowance\n ] = await Promise.all([\n policy.boolean(CLOUD_FEATURE_KEYS.links, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, technicalMaximumParticipants, context),\n policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)\n ])\n // Technical limits are ceilings: an entitlement can lower them but never raise them.\n const participants = Math.min(technicalMaximumParticipants, maximumParticipants)\n return {\n features: {\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudServices\n },\n limits: {\n maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),\n maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,\n maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,\n monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance\n }\n }\n }\n}\n\nfunction storageUsage(usage: StorageQuotaSnapshot): WorkspaceEntitlements['usage'] {\n return { committedStorageBytes: usage.committedBytes, reservedStorageBytes: usage.reservedBytes }\n}\n\nexport type EntitlementService = ReturnType<typeof createEntitlementService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS, type CloudPolicy } from '#cloud/server/policy'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport type { Kysely } from 'kysely'\n\nexport type SharingPolicyOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport type CapabilityLinkPolicyInput = {\n actorId: string\n documentId: string\n}\n\nexport function createSharingPolicy(\n database: Kysely<CloudDatabase>,\n options: SharingPolicyOptions\n) {\n async function requireCapabilityLink(input: CapabilityLinkPolicyInput): Promise<void> {\n if (!options.policy) return\n const context = await workspacePolicyContext(\n database,\n { documentId: input.documentId },\n { actorId: input.actorId, deploymentMode: options.deploymentMode ?? 'self-hosted' }\n )\n if (!context) throw new DocumentNotFoundError()\n // Whether guests may follow the link is checked when they do, so edit links still work for\n // people signed in to the server.\n if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.links, false, context))) {\n throw new DocumentForbiddenError()\n }\n }\n\n return { requireCapabilityLink }\n}\n\nexport type SharingPolicy = ReturnType<typeof createSharingPolicy>\n","import type {\n CreateDocumentShareInput,\n DocumentPermission,\n DocumentShare,\n ResolveDocumentShareInput,\n UpdateDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport { isBannedNow, type CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport type { Kysely, UpdateObject } from 'kysely'\nimport * as v from 'valibot'\n\nimport { randomHex } from '@open-pencil/std/random'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { shareContract } from '../contracts'\nimport { capabilityHashMatches, hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '../errors'\nimport { createSharingPolicy } from '../policy'\n\nconst SHARE_SECRET_BYTES = 24\n\n/** An account ID as the user table keys it; other IDs in `createdBy` name no account. */\nconst accountIdSchema = v.pipe(v.string(), v.uuid())\n\n/**\n * Whether any of these people is banned, for a ban that has not run out. A link stops working\n * while whoever made it, or made its document, is banned, so what a banned person put up is no\n * longer public. The IDs are matched as the user table keys them, so the lookup uses its index.\n */\nasync function anyBanned(database: Kysely<CloudDatabase>, userIds: string[]): Promise<boolean> {\n const accounts = userIds.filter((id) => v.is(accountIdSchema, id))\n if (accounts.length === 0) return false\n const banned = await database\n .selectFrom('user')\n .select('id')\n .where('id', 'in', accounts)\n .where(isBannedNow)\n .executeTakeFirst()\n return banned !== undefined\n}\n\nexport type DocumentShareCapability = {\n share: DocumentShare\n secret: string\n path: string\n}\n\nexport type ResolvedSharePrincipal =\n | { kind: 'user'; userId: string; name: string; email: string }\n | { kind: 'guest'; guestId: string; name: string }\n\nexport type ResolvedDocumentShare = {\n documentId: string\n /** What this person may do: the link's permission, or view for a guest who may not edit. */\n permission: DocumentPermission\n /** What the link lets someone signed in to the server do. */\n linkPermission: DocumentPermission\n principal: ResolvedSharePrincipal\n roomEpoch: number\n}\n\nexport type CapabilityServiceOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCapabilityService(\n database: Kysely<CloudDatabase>,\n options: CapabilityServiceOptions\n) {\n const sharingPolicy = createSharingPolicy(database, options)\n\n /**\n * What a guest may do through a link: edit only where guests may edit, otherwise view where\n * guests may view, so an edit link still shows the document to someone not signed in. `null`\n * means the guest signs in first. Without a policy, guests get the link's own permission.\n */\n async function guestPermission(\n documentId: string,\n linkPermission: DocumentPermission\n ): Promise<DocumentPermission | null> {\n const policy = options.policy\n if (!policy) return linkPermission\n // A workspace takes its owner's plan.\n const context = await workspacePolicyContext(\n database,\n { documentId },\n { deploymentMode: options.deploymentMode ?? 'self-hosted' }\n )\n if (!context) return null\n if (\n linkPermission === 'edit' &&\n (await policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context))\n ) {\n return 'edit'\n }\n return (await policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context)) ? 'view' : null\n }\n\n async function updateActiveShare(\n userId: string,\n documentId: string,\n shareId: string,\n changes: UpdateObject<CloudDatabase, 'documentShare'>\n ) {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .updateTable('documentShare')\n .set(changes)\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n return {\n async listShares(userId: string, documentId: string): Promise<DocumentShare[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentShare')\n .selectAll()\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt', 'desc')\n .execute()\n return rows.map(shareContract)\n },\n\n async createShare(\n userId: string,\n documentId: string,\n input: CreateDocumentShareInput\n ): Promise<DocumentShareCapability> {\n await requireSharingAccess(database, userId, documentId)\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const id = crypto.randomUUID()\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n return transaction\n .insertInto('documentShare')\n .values({\n id,\n documentId,\n permission: input.permission,\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n createdBy: userId,\n expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,\n revokedAt: null,\n lastUsedAt: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n })\n return { share: shareContract(row), secret, path: `/share/${id}#${secret}` }\n },\n\n async updateShare(\n userId: string,\n documentId: string,\n shareId: string,\n input: UpdateDocumentShareInput\n ): Promise<DocumentShare> {\n // Authorization comes first, so a caller without access learns nothing about the share\n // or the document's link policy.\n await requireSharingAccess(database, userId, documentId)\n const current = await database\n .selectFrom('documentShare')\n .select('id')\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!current) throw new DocumentNotFoundError()\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }\n if (input.permission) changes.permission = input.permission\n if (input.expiresAt !== undefined) {\n changes.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n }\n const row = await updateActiveShare(userId, documentId, shareId, changes)\n return shareContract(row)\n },\n\n async rotateShare(\n userId: string,\n documentId: string,\n shareId: string\n ): Promise<DocumentShareCapability> {\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const updated = await transaction\n .updateTable('documentShare')\n .set({\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n updatedAt: new Date()\n })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!updated) throw new DocumentNotFoundError()\n return updated\n })\n return { share: shareContract(row), secret, path: `/share/${shareId}#${secret}` }\n },\n\n async revokeShare(userId: string, documentId: string, shareId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentShare')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n },\n\n async resolveShare(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<ResolvedDocumentShare> {\n const row = await database\n .selectFrom('documentShare')\n .innerJoin('document', 'document.id', 'documentShare.documentId')\n .select([\n 'documentShare.id',\n 'documentShare.documentId',\n 'documentShare.permission',\n 'documentShare.secretHash',\n 'documentShare.roomEpoch',\n 'documentShare.expiresAt',\n 'documentShare.createdBy as linkMaker',\n 'document.createdBy as documentMaker'\n ])\n .where('documentShare.id', '=', shareId)\n .where('documentShare.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n // A document an administrator took down opens for nobody.\n .where('document.disabledAt', 'is', null)\n .executeTakeFirst()\n if (\n !row ||\n !capabilityHashMatches(row.secretHash, input.secret) ||\n (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now()) ||\n (await anyBanned(database, [row.linkMaker, row.documentMaker]))\n ) {\n throw new DocumentShareInvalidError()\n }\n const permission = actor\n ? row.permission\n : await guestPermission(row.documentId, row.permission)\n if (!permission) {\n // Guests are not let in here; people signed in to the server are.\n throw new DocumentShareSignInRequiredError()\n }\n await database\n .updateTable('documentShare')\n .set({ lastUsedAt: new Date() })\n .where('id', '=', shareId)\n .execute()\n return {\n documentId: row.documentId,\n permission,\n linkPermission: row.permission,\n principal: actor\n ? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }\n : {\n kind: 'guest',\n guestId: input.guestId ?? crypto.randomUUID(),\n name: input.guestName ?? 'Guest'\n },\n roomEpoch: row.roomEpoch\n }\n }\n }\n}\n\nexport type CapabilityService = ReturnType<typeof createCapabilityService>\n","import type { DocumentGrant, PutDocumentGrantInput } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { grantContract } from '../contracts'\n\nexport function createGrantService(database: Kysely<CloudDatabase>) {\n return {\n async listGrants(userId: string, documentId: string): Promise<DocumentGrant[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentGrant')\n .select(['id', 'documentId', 'userId', 'permission', 'createdBy', 'createdAt', 'updatedAt'])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt')\n .execute()\n return rows.map(grantContract)\n },\n\n /**\n * Changes the permission of someone who already has access. Access itself is only given by an\n * invitation the person accepts, so nobody can put a document in a stranger's files.\n */\n async putGrant(\n userId: string,\n documentId: string,\n targetUserId: string,\n input: PutDocumentGrantInput\n ): Promise<DocumentGrant> {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .updateTable('documentGrant')\n .set({ permission: input.permission, createdBy: userId, updatedAt: new Date() })\n .where('documentId', '=', documentId)\n .where('userId', '=', targetUserId)\n .where('revokedAt', 'is', null)\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return grantContract(row)\n },\n\n /** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */\n async revokeGrant(userId: string, documentId: string, targetUserId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentGrant')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('documentId', '=', documentId)\n .where('userId', '=', targetUserId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n }\n }\n}\n\nexport type GrantService = ReturnType<typeof createGrantService>\n","import { requestSharedImageLinksSchema, resolveDocumentShareSchema } from '#cloud/contract'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport type { DocumentService } from '#cloud/server/documents'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport { shareParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { shareActor } from './actor'\n\nexport function createPublicDocumentRoutes(\n sharing: DocumentSharingService,\n documents: DocumentService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post(\n '/shares/:shareId/document',\n shareParams,\n validatedJSON(resolveDocumentShareSchema),\n (context) =>\n sharingRoute(context, async () => {\n const resolution = await sharing.resolveShare(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json({\n resolution,\n document: await documents.downloadShared(resolution.documentId)\n })\n })\n )\n .post(\n '/shares/:shareId/images',\n shareParams,\n validatedJSON(requestSharedImageLinksSchema),\n (context) =>\n sharingRoute(context, async () => {\n const { checksums, ...share } = context.req.valid('json')\n const resolution = await sharing.resolveShare(\n context.req.valid('param').shareId,\n share,\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json(await documents.imageLinksShared(resolution.documentId, checksums))\n })\n )\n}\n","import type {\n AcceptDocumentInvitationInput,\n AcceptedInvitation,\n CreateDocumentInvitationInput,\n CreateInvitationContinuationInput,\n DocumentInvitation,\n InvitationPreview,\n WorkspaceRole\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport {\n INVITATION_LIFETIME_MS,\n INVITATION_SECRET_BYTES,\n spendInvitationBudget,\n type DocumentInvitationMessage,\n type InvitationDelivery,\n type InvitationOutbox\n} from '#cloud/server/invitations'\nimport type { Kysely } from 'kysely'\n\nimport { randomHex } from '@open-pencil/std/random'\n\nimport { requireSharingAccess } from '../access'\nimport {\n createInvitationContinuationService,\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '../continuation'\nimport { dateString, grantContract, invitationContract } from '../contracts'\nimport { hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'\n\n/** Workspace invitations share the invitation link; their ids are not document invitations. */\nexport type WorkspaceInvitationResolver = {\n preview(invitationId: string, token: string): Promise<InvitationPreview | null>\n accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null>\n}\n\nexport type InvitationServiceOptions = {\n workspaceInvitations?: WorkspaceInvitationResolver\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n}\n\nexport function createInvitationService(\n database: Kysely<CloudDatabase>,\n options: InvitationServiceOptions\n) {\n async function previewDocumentInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const invitation = await database\n .selectFrom('documentInvitation')\n .innerJoin('document', 'document.id', 'documentInvitation.documentId')\n .select([\n 'documentInvitation.emailNormalized',\n 'documentInvitation.permission',\n 'documentInvitation.tokenHash',\n 'documentInvitation.expiresAt',\n 'documentInvitation.acceptedAt',\n 'documentInvitation.revokedAt',\n 'documentInvitation.invitedBy',\n 'document.name as documentName'\n ])\n .where('documentInvitation.id', '=', invitationId)\n // A taken-down document's invitations name nothing until it is restored.\n .where('document.disabledAt', 'is', null)\n .executeTakeFirst()\n if (!invitation || !invitationTokenIsActive(invitation, input.token)) {\n throw new DocumentShareInvalidError()\n }\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'document',\n documentName: invitation.documentName,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n permission: invitation.permission,\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n }\n\n const continuation = options.continuationSecret\n ? createInvitationContinuationService(\n database,\n options.continuationSecret,\n // Continuations are kept for document invitations only.\n async (invitationId, token) => previewDocumentInvitation(invitationId, { token })\n )\n : null\n\n return {\n async listInvitations(userId: string, documentId: string): Promise<DocumentInvitation[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentInvitation')\n .select([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('invitedAt')\n .execute()\n return rows.map(invitationContract)\n },\n\n async createInvitation(\n userId: string,\n documentId: string,\n input: CreateDocumentInvitationInput\n ): Promise<{ invitation: DocumentInvitation; token: string }> {\n await requireSharingAccess(database, userId, documentId)\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const deliveryContext =\n (options.delivery || options.outbox) && options.publicURL\n ? await Promise.all([\n database\n .selectFrom('user')\n .select(['name', 'locale'])\n .where('id', '=', userId)\n .executeTakeFirst(),\n database\n .selectFrom('document')\n .select('name')\n .where('id', '=', documentId)\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('user')\n .select('locale')\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)\n )\n .executeTakeFirst()\n ])\n : null\n const acceptanceURL =\n deliveryContext && options.publicURL\n ? cloudInvitationURL(options.publicURL, id, token)\n : null\n const message: DocumentInvitationMessage | null =\n deliveryContext && acceptanceURL\n ? {\n deliveryId: id,\n recipientEmail: input.email,\n // Someone without an account yet reads the inviter's language.\n locale: deliveryContext[2]?.locale ?? deliveryContext[0]?.locale ?? 'en',\n inviterName: deliveryContext[0]?.name ?? null,\n documentName: deliveryContext[1].name,\n permission: input.permission,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL\n }\n : null\n const row = await database.transaction().execute(async (transaction) => {\n await spendInvitationBudget(transaction, { senderId: userId, email: input.email })\n const inserted = await transaction\n .insertInto('documentInvitation')\n .values({\n id,\n documentId,\n emailNormalized: input.email,\n permission: input.permission,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .executeTakeFirstOrThrow()\n if (options.outbox && message) {\n await options.outbox.enqueueDocumentInvitation(message, transaction)\n }\n return inserted\n })\n const invitation = invitationContract(row)\n if (options.delivery && message && !options.outbox) {\n try {\n await options.delivery.sendDocumentInvitation(message)\n } catch (error) {\n await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', id)\n .execute()\n throw new InvitationDeliveryError('Invitation delivery failed', { cause: error })\n }\n }\n return { invitation, token }\n },\n\n async createInvitationContinuation(input: CreateInvitationContinuationInput) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.create(input)\n },\n\n async consumeInvitationContinuation(id: string) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.consume(id)\n },\n\n /** What an invitation link offers: a document, or a workspace when the id is one of those. */\n async previewInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const workspace = await options.workspaceInvitations?.preview(invitationId, input.token)\n return workspace ?? previewDocumentInvitation(invitationId, input)\n },\n\n async acceptInvitation(\n actor: CloudActor,\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<AcceptedInvitation> {\n const workspace = await options.workspaceInvitations?.accept(actor, invitationId, input.token)\n if (workspace) return { kind: 'workspace', ...workspace }\n const invitation = await database\n .selectFrom('documentInvitation')\n .innerJoin('document', 'document.id', 'documentInvitation.documentId')\n .select([\n 'documentInvitation.id',\n 'documentInvitation.documentId',\n 'documentInvitation.emailNormalized',\n 'documentInvitation.permission',\n 'documentInvitation.invitedBy',\n 'documentInvitation.tokenHash',\n 'documentInvitation.expiresAt',\n 'documentInvitation.acceptedAt',\n 'documentInvitation.revokedAt'\n ])\n .where('documentInvitation.id', '=', invitationId)\n // Refused, not consumed, while the document is taken down, so it works again on restore.\n .where('document.disabledAt', 'is', null)\n .executeTakeFirst()\n if (\n !invitation ||\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, input.token)\n ) {\n throw new DocumentShareInvalidError()\n }\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .insertInto('documentGrant')\n .values({\n id: crypto.randomUUID(),\n documentId: invitation.documentId,\n userId: actor.userId,\n permission: invitation.permission,\n // The grant is the inviter's, so \"shared by\" names them, not the recipient.\n createdBy: invitation.invitedBy,\n revokedAt: null\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'userId']).doUpdateSet({\n permission: invitation.permission,\n createdBy: invitation.invitedBy,\n revokedAt: null,\n updatedAt: new Date()\n })\n )\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirstOrThrow()\n await transaction\n .updateTable('documentInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n return { kind: 'document' as const, grant: grantContract(row) }\n })\n },\n\n async revokeInvitation(\n userId: string,\n documentId: string,\n invitationId: string\n ): Promise<void> {\n await requireSharingAccess(database, userId, documentId)\n const result = await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n }\n }\n}\n\nexport type InvitationService = ReturnType<typeof createInvitationService>\n","import {\n acceptDocumentInvitationSchema,\n createInvitationContinuationSchema,\n createDocumentInvitationSchema,\n createDocumentShareSchema,\n putDocumentGrantSchema,\n resolveDocumentShareSchema,\n updateDocumentShareSchema\n} from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport type { DocumentSharingService } from '#cloud/server/sharing/service'\nimport {\n documentInvitationParams,\n documentParams,\n documentShareParams,\n documentUserParams,\n invitationContinuationParams,\n invitationParams,\n shareParams,\n validatedJSON\n} from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { shareActor } from './actor'\n\nexport type SharingRouteEnvironment = {\n Variables: { actor: CloudActor }\n}\n\nexport function createDocumentSharingRoutes(\n service: DocumentSharingService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<SharingRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/invitations',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .get('/documents/:documentId/users/:userId', documentUserParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n user: await service.userProfile(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId\n )\n })\n )\n )\n .get('/documents/:documentId/shares', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n shares: await service.listShares(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/shares',\n documentParams,\n validatedJSON(createDocumentShareSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/shares/:shareId',\n documentShareParams,\n validatedJSON(updateDocumentShareSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n share: await service.updateShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId,\n context.req.valid('json')\n )\n })\n )\n )\n .post('/documents/:documentId/shares/:shareId/rotate', documentShareParams, (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.rotateShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId\n )\n )\n )\n )\n .delete('/documents/:documentId/shares/:shareId', documentShareParams, (context) =>\n sharingRoute(context, async () => {\n await service.revokeShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/grants', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n grants: await service.listGrants(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .put(\n '/documents/:documentId/grants/:userId',\n documentUserParams,\n validatedJSON(putDocumentGrantSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n grant: await service.putGrant(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId,\n context.req.valid('json')\n )\n })\n )\n )\n .delete('/documents/:documentId/grants/:userId', documentUserParams, (context) =>\n sharingRoute(context, async () => {\n await service.revokeGrant(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/invitations', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitations: await service.listInvitations(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/invitations',\n documentParams,\n validatedJSON(createDocumentInvitationSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createInvitation(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/invitations/:invitationId/accept',\n invitationParams,\n validatedJSON(acceptDocumentInvitationSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n accepted: await service.acceptInvitation(\n context.get('actor'),\n context.req.valid('param').invitationId,\n context.req.valid('json')\n )\n })\n )\n )\n .delete(\n '/documents/:documentId/invitations/:invitationId',\n documentInvitationParams,\n (context) =>\n sharingRoute(context, async () => {\n await service.revokeInvitation(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').invitationId\n )\n return context.body(null, 204)\n })\n )\n}\n\nexport function createPublicSharingRoutes(\n service: DocumentSharingService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post(\n '/invitations/continuations',\n validatedJSON(createInvitationContinuationSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)\n )\n )\n .post(\n '/invitations/continuations/:continuationId/consume',\n invitationContinuationParams,\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.consumeInvitationContinuation(context.req.valid('param').continuationId)\n )\n )\n )\n .post(\n '/invitations/:invitationId/preview',\n invitationParams,\n validatedJSON(acceptDocumentInvitationSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitation: await service.previewInvitation(\n context.req.valid('param').invitationId,\n context.req.valid('json')\n )\n })\n )\n )\n .post(\n '/shares/:shareId/resolve',\n shareParams,\n validatedJSON(resolveDocumentShareSchema),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n resolution: await service.resolveShare(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n })\n )\n )\n}\n","import type { CloudUserProfile } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nimport { requireSharingAccess } from './access'\nimport {\n createCapabilityService,\n type DocumentShareCapability,\n type ResolvedDocumentShare,\n type ResolvedSharePrincipal\n} from './capabilities/service'\nimport { createGrantService } from './grants/service'\nimport { createInvitationService, type WorkspaceInvitationResolver } from './invitations/service'\n\nexport type { DocumentShareCapability, ResolvedDocumentShare, ResolvedSharePrincipal }\n\nexport type DocumentSharingServiceOptions = {\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n workspaceInvitations?: WorkspaceInvitationResolver\n}\n\nexport function createDocumentSharingService(\n database: Kysely<CloudDatabase>,\n options: DocumentSharingServiceOptions = {}\n) {\n const capabilities = createCapabilityService(database, options)\n const grants = createGrantService(database)\n const invitations = createInvitationService(database, options)\n\n return {\n async userProfile(\n userId: string,\n documentId: string,\n profileUserId: string\n ): Promise<CloudUserProfile | null> {\n await requireSharingAccess(database, userId, documentId)\n // Only people connected to this document: its owner, its workspace's members, the holders\n // and givers of its grants, and the people who invited others to it. User IDs are text in\n // these tables, so they are compared with the requested ID rather than `user.id`.\n const related = await database\n .selectFrom('document')\n .select('document.id')\n .where('document.id', '=', documentId)\n .where((expression) =>\n expression.or([\n expression('document.createdBy', '=', profileUserId),\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', profileUserId)\n ),\n expression.exists(\n expression\n .selectFrom('documentGrant')\n .select('documentGrant.id')\n .whereRef('documentGrant.documentId', '=', 'document.id')\n .where((grant) =>\n grant.or([\n grant.and([\n grant('documentGrant.userId', '=', profileUserId),\n grant('documentGrant.revokedAt', 'is', null)\n ]),\n grant('documentGrant.createdBy', '=', profileUserId)\n ])\n )\n ),\n expression.exists(\n expression\n .selectFrom('documentInvitation')\n .select('documentInvitation.id')\n .whereRef('documentInvitation.documentId', '=', 'document.id')\n .where('documentInvitation.invitedBy', '=', profileUserId)\n )\n ])\n )\n .executeTakeFirst()\n if (!related) return null\n const user = await database\n .selectFrom('user')\n .select(['id', 'name', 'email', 'image'])\n .where('id', '=', profileUserId)\n .executeTakeFirst()\n return user ?? null\n },\n\n ...capabilities,\n ...grants,\n ...invitations\n }\n}\n\nexport type DocumentSharingService = ReturnType<typeof createDocumentSharingService>\n","import { resolveDocumentShareSchema } from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration/service'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'\nimport { documentParams, shareParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CollaborationRouteEnvironment = { Variables: { actor: CloudActor } }\n\nfunction notFound(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError || error instanceof DocumentShareInvalidError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return null\n}\n\nexport function createCollaborationRoutes(\n service: CollaborationTicketService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<CollaborationRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/collaboration-ticket',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.collaborationTicket,\n routeParamResource('documentId')\n )\n )\n }\n return router.post(\n '/documents/:documentId/collaboration-ticket',\n documentParams,\n async (context) => {\n try {\n return context.json({\n ticket: await service.issueUserTicket(\n context.get('actor'),\n context.req.valid('param').documentId\n )\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n\nexport function createPublicCollaborationRoutes(\n service: Pick<CollaborationTicketService, 'issueShareTicket'>,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono<CollaborationRouteEnvironment>().post(\n '/shares/:shareId/collaboration-ticket',\n shareParams,\n validatedJSON(resolveDocumentShareSchema),\n async (context) => {\n try {\n const actor = resolveSession ? await resolveSession(context.req.raw) : null\n // A signed-in caller is named in error reports, as on the routes that require one.\n if (actor) context.set('actor', actor)\n return context.json({\n ticket: await service.issueShareTicket(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n actor ?? undefined\n )\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n","import {\n RELAY_DOCUMENT_PARAM,\n type CollaborationPrincipal,\n type CollaborationTicket,\n type DocumentPermission,\n type ResolveDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { storageLimitReached } from '#cloud/server/policy/storage'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { base64url, SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\nimport { withQuery } from 'ufo'\n\nconst TICKET_LIFETIME_SECONDS = 5 * 60\n\nasync function derivedRoomKey(authSecret: string, documentId: string, roomEpoch: number) {\n const inputBytes = new TextEncoder().encode(`${authSecret}:room:${documentId}:${roomEpoch}`)\n const key = await crypto.subtle.importKey('raw', inputBytes, 'HKDF', false, ['deriveBits'])\n const bits = await crypto.subtle.deriveBits(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new TextEncoder().encode(`openpencil-cloud:${documentId}`),\n info: new TextEncoder().encode(`collaboration-room:${roomEpoch}`)\n },\n key,\n 256\n )\n return base64url.encode(new Uint8Array(bits))\n}\n\nexport type CollaborationTicketClaims = {\n authSecret: string\n documentId: string\n principal: CollaborationPrincipal\n permission: DocumentPermission\n /** Why a peer who could edit only views, which the editor explains; never part of the token. */\n readOnly?: 'storage-limit'\n roomEpoch: number\n /**\n * The relay that enforces writes; without one the ticket is for peer-to-peer rooms. The ticket's\n * URL names the document, so a runtime can route the socket to where the room lives.\n */\n relayURL?: string\n}\n\n/** Signs a ticket for a document's collaboration room once access has been decided. */\nexport async function signCollaborationTicket({\n authSecret,\n documentId,\n principal,\n permission,\n readOnly,\n roomEpoch,\n relayURL\n}: CollaborationTicketClaims): Promise<CollaborationTicket> {\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAtSeconds = issuedAt + TICKET_LIFETIME_SECONDS\n const roomId = `cloud:${documentId}:${roomEpoch}`\n const roomKey = await derivedRoomKey(authSecret, documentId, roomEpoch)\n const claims = {\n documentId,\n roomId,\n principal,\n permission,\n roomEpoch,\n serverEnforcedWrites: Boolean(relayURL)\n }\n const token = await new SignJWT(claims)\n .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAtSeconds)\n .setSubject(principal.kind === 'user' ? principal.userId : principal.guestId)\n .sign(new TextEncoder().encode(authSecret))\n const ticket = {\n token,\n provider: 'trystero' as const,\n ...(readOnly && { readOnly }),\n ...claims,\n roomKey,\n expiresAt: new Date(expiresAtSeconds * 1000).toISOString(),\n relayHeartbeat: false\n }\n if (!relayURL) return ticket\n // This deployment's relay answers the heartbeat, which editors then use to notice a lost socket.\n return {\n ...ticket,\n provider: 'relay' as const,\n serverURL: withQuery(relayURL, { [RELAY_DOCUMENT_PARAM]: documentId }),\n relayHeartbeat: true\n }\n}\n\nexport type CollaborationTicketServiceOptions = {\n database: Kysely<CloudDatabase>\n sharing: DocumentSharingService\n authSecret: string\n relayURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCollaborationTicketService({\n database,\n sharing,\n authSecret,\n relayURL,\n policy,\n deploymentMode = 'self-hosted'\n}: CollaborationTicketServiceOptions) {\n /**\n * The permission a ticket carries: an owner at their storage limit leaves their documents\n * read-only, so whoever could edit them views them instead, and the ticket says why.\n */\n async function ticketPermission(documentId: string, permission: DocumentPermission) {\n if (\n permission === 'edit' &&\n (await storageLimitReached(database, policy, { documentId }, deploymentMode))\n ) {\n return { permission: 'view' as const, readOnly: 'storage-limit' as const }\n }\n return { permission }\n }\n\n return {\n async issueUserTicket(actor: CloudActor, documentId: string): Promise<CollaborationTicket> {\n const access = await resolveDocumentAccess(database, actor.userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (policy) {\n const context = await workspacePolicyContext(\n database,\n { documentId },\n { actorId: actor.userId, deploymentMode }\n )\n if (!context || !(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context))) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .where('disabledAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId,\n principal: { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },\n ...(await ticketPermission(documentId, access.permission)),\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n },\n\n async issueShareTicket(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<CollaborationTicket> {\n const resolved = await sharing.resolveShare(shareId, input, actor)\n if (policy) {\n const context = await workspacePolicyContext(\n database,\n { documentId: resolved.documentId },\n { actorId: actor?.userId, deploymentMode }\n )\n if (!context || !(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context))) {\n throw new DocumentNotFoundError()\n }\n if (!actor && !(await policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context))) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', resolved.documentId)\n .where('deletedAt', 'is', null)\n .where('disabledAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId: resolved.documentId,\n principal: resolved.principal,\n ...(await ticketPermission(resolved.documentId, resolved.permission)),\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n }\n }\n}\n\nexport type CollaborationTicketService = ReturnType<typeof createCollaborationTicketService>\n","import {\n collaborationPrincipalSchema,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport { jwtVerify } from 'jose'\nimport * as v from 'valibot'\n\nconst relayClaimsSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n principal: collaborationPrincipalSchema,\n permission: v.picklist(['view', 'edit']),\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n serverEnforcedWrites: v.literal(true),\n exp: v.pipe(v.number(), v.integer())\n})\n\nexport type RelayAuthorization = {\n roomId: string\n documentId: string\n roomEpoch: number\n permission: DocumentPermission\n principal: CollaborationPrincipal\n /** When the ticket stops being valid, in milliseconds since the epoch. */\n expiresAt: number\n}\n\n/** Verifies a collaboration ticket issued for the relay; throws for anything else. */\nexport async function authorizeRelayTicket(\n token: string,\n authSecret: string\n): Promise<RelayAuthorization> {\n const verified = await jwtVerify(token, new TextEncoder().encode(authSecret), {\n algorithms: ['HS256']\n })\n const claims = v.parse(relayClaimsSchema, verified.payload)\n if (claims.roomId !== `cloud:${claims.documentId}:${claims.roomEpoch}`) {\n throw new Error('Collaboration ticket names a different room')\n }\n return {\n roomId: claims.roomId,\n documentId: claims.documentId,\n roomEpoch: claims.roomEpoch,\n permission: claims.permission,\n principal: claims.principal,\n expiresAt: claims.exp * 1000\n }\n}\n\nexport function principalKey(principal: CollaborationPrincipal): string {\n return principal.kind === 'user' ? `user:${principal.userId}` : `guest:${principal.guestId}`\n}\n","import {\n presenceName,\n type CloudPresence,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as v from 'valibot'\n\nconst awarenessStateSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.looseObject({ user: v.optional(v.looseObject({})) })\n)\n\ntype AwarenessEntry = { clientId: number; clock: number; state: string }\n\nfunction decodeEntries(update: Uint8Array): AwarenessEntry[] | null {\n try {\n const decoder = decoding.createDecoder(update)\n const count = decoding.readVarUint(decoder)\n const entries: AwarenessEntry[] = []\n for (let index = 0; index < count; index++) {\n entries.push({\n clientId: decoding.readVarUint(decoder),\n clock: decoding.readVarUint(decoder),\n state: decoding.readVarString(decoder)\n })\n }\n return decoder.pos === update.byteLength ? entries : null\n } catch {\n return null\n }\n}\n\nfunction encodeEntries(entries: AwarenessEntry[]): Uint8Array {\n return encoding.encode((encoder) => {\n encoding.writeVarUint(encoder, entries.length)\n for (const entry of entries) {\n encoding.writeVarUint(encoder, entry.clientId)\n encoding.writeVarUint(encoder, entry.clock)\n encoding.writeVarString(encoder, entry.state)\n }\n })\n}\n\n/** Who the relay verified a peer to be, as other peers see it in presence. */\nexport type VerifiedPresence = {\n principal: CollaborationPrincipal\n permission: DocumentPermission\n}\n\nfunction verifiedIdentity({ principal, permission }: VerifiedPresence): CloudPresence {\n return {\n kind: principal.kind,\n id: principal.kind === 'user' ? principal.userId : principal.guestId,\n name: principal.name,\n permission\n }\n}\n\nexport type StampedAwareness = {\n /** The update to forward, or null when nothing in it may be forwarded. */\n update: Uint8Array | null\n /** Presence clients this update introduced for the peer. */\n claimed: number[]\n}\n\n/**\n * Rewrites a peer's presence update so others see who the relay verified rather than what the\n * peer claims: the display name comes from the ticket, and a `cloud` field carries the verified\n * identity and permission. Entries for presence clients another peer owns are dropped, so one\n * peer cannot speak for another; removals pass through for the peer's own clients only.\n */\nexport function stampAwareness(\n update: Uint8Array,\n presence: VerifiedPresence,\n ownedByOthers: (clientId: number) => boolean\n): StampedAwareness {\n const entries = decodeEntries(update)\n if (!entries) return { update: null, claimed: [] }\n const identity = verifiedIdentity(presence)\n const forwarded: AwarenessEntry[] = []\n const claimed: number[] = []\n for (const entry of entries) {\n if (ownedByOthers(entry.clientId)) continue\n if (entry.state === 'null') {\n forwarded.push(entry)\n continue\n }\n const parsed = v.safeParse(awarenessStateSchema, entry.state)\n if (!parsed.success) continue\n const state = {\n ...parsed.output,\n // The ticket's name, cut to what peers accept, so a long one cannot hide the member.\n user: { ...parsed.output.user, name: presenceName(identity.name) },\n cloud: identity\n }\n claimed.push(entry.clientId)\n forwarded.push({ ...entry, state: JSON.stringify(state) })\n }\n return { update: forwarded.length > 0 ? encodeEntries(forwarded) : null, claimed }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { workspacePolicyContext } from '#cloud/server/policy/workspace'\nimport type { Kysely } from 'kysely'\n\nimport type { CollaborationRelayOptions } from './hub'\n\n/**\n * The relay's lookups of a document: its participant limit under `policy`, none while it is taken\n * down, and its epoch.\n */\nexport function relayDocumentLookups(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n deploymentMode: 'official' | 'self-hosted'\n): Pick<CollaborationRelayOptions, 'maximumParticipants' | 'currentRoomEpoch'> {\n return {\n async maximumParticipants(documentId) {\n // A taken-down document's room takes nobody, even with a ticket issued before.\n const open = await database\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .where('disabledAt', 'is', null)\n .executeTakeFirst()\n if (!open) return 0\n const context = await workspacePolicyContext(database, { documentId }, { deploymentMode })\n if (!context) return 0\n const limit = await policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, -1, context)\n return limit < 0 ? null : limit\n },\n async currentRoomEpoch(documentId) {\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .executeTakeFirst()\n return document?.collaborationEpoch ?? null\n }\n }\n}\n","import {\n createRelayClientAssembler,\n decodeRelayClientFrame,\n RELAY_CLOSE,\n type RelayClientFrame\n} from '#cloud/contract'\n\nimport { authorizeRelayTicket, principalKey, type RelayAuthorization } from './authorize'\nimport type { RelayPeerState } from './resume'\n\n/** One client's socket, as a runtime adapter hands it to the relay. */\nexport type RelaySocket = {\n send(data: Uint8Array): void\n close(code: number, reason: string): void\n /**\n * Keeps the peer's state with the socket, for a runtime that sets the relay aside while sockets\n * stay open and resumes their peers with `resume` when it wakes.\n */\n remember?(state: RelayPeerState): void\n}\n\n/** What the adapter reports back about that socket. */\nexport type RelayConnection = {\n receive(data: Uint8Array): void\n closed(): void\n}\n\n/** A socket admitted to a room, as the person and permission its ticket names. */\nexport type RelayPeer = {\n id: string\n socket: RelaySocket\n authorization: RelayAuthorization\n presenceClients: Set<number>\n}\n\n/** A room message from an admitted peer. */\nexport type RelayRoomFrame = Extract<RelayClientFrame, { type: 'message' }>\n\n/** What a connection asks of the relay it belongs to. */\nexport type ConnectionRelay = {\n authSecret: string\n /** The one document the relay serves, when it serves one. */\n documentId?: string\n maximumMessageBytes: number\n /** The most an editor's update may carry once its fragments are joined. */\n maximumUpdateBytes: number\n authTimeoutMs: number\n /** Admits a newcomer whose ticket verified, or turns it away and answers null. */\n admit(socket: RelaySocket, authorization: RelayAuthorization): Promise<RelayPeer | null>\n /** Takes a refreshed ticket for a peer already in its room. */\n refreshed(peer: RelayPeer): void\n /** Handles a peer's room message; a promise while it waits for the room's document. */\n deliver(peer: RelayPeer, frame: RelayRoomFrame): Promise<void> | undefined\n depart(peer: RelayPeer): void\n /** Reports a failure, naming the ticket's document and person once the ticket verified. */\n report(message: string, error: unknown, authorization?: RelayAuthorization): void\n}\n\n/**\n * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with\n * the peer it already is. It joins fragmented frames, holds what arrives while a ticket is checked\n * or the room's document loads, and refreshes tickets.\n */\nexport function openRelayConnection(\n socket: RelaySocket,\n resumed: RelayPeer | null,\n relay: ConnectionRelay\n): RelayConnection {\n let peer: RelayPeer | null = resumed\n /** The last ticket that passed every check, which a failure handling it reports. */\n let verified: RelayAuthorization | undefined\n /** Read through an object, since it changes across awaits and between messages. */\n const state = { closed: false, busy: false }\n const isClosed = () => state.closed\n const queued: Uint8Array[] = []\n let queuedBytes = 0\n // Only an editor's writes can be large: a viewer's frames, and a peer's before it is\n // admitted, fit in one message, so nobody else can make the relay hold more.\n const assembler = createRelayClientAssembler(() =>\n peer?.authorization.permission === 'edit' ? relay.maximumUpdateBytes : relay.maximumMessageBytes\n )\n const authTimer = resumed\n ? undefined\n : setTimeout(\n () => socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket'),\n relay.authTimeoutMs\n )\n\n async function authenticate(token: string) {\n let authorization: RelayAuthorization\n try {\n authorization = await authorizeRelayTicket(token, relay.authSecret)\n } catch {\n socket.close(RELAY_CLOSE.unauthorized, 'Invalid collaboration ticket')\n return\n }\n if (relay.documentId !== undefined && authorization.documentId !== relay.documentId) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different document')\n return\n }\n if (state.closed) return\n if (peer) {\n // A refreshed ticket keeps the peer in its room as the same person; a lowered\n // permission applies from now on.\n const current = peer.authorization\n if (\n authorization.roomId !== current.roomId ||\n principalKey(authorization.principal) !== principalKey(current.principal)\n ) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different room or person')\n return\n }\n verified = authorization\n peer.authorization = authorization\n relay.refreshed(peer)\n return\n }\n clearTimeout(authTimer)\n verified = authorization\n const admitted = await relay.admit(socket, authorization)\n // The socket may have closed while the room loaded.\n if (admitted && isClosed()) relay.depart(admitted)\n else peer = admitted\n }\n\n function process(data: Uint8Array) {\n if (data.byteLength > relay.maximumMessageBytes) {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const assembled = assembler.push(data)\n if (assembled.type === 'partial') return\n if (assembled.type === 'too-large') {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const frame = assembled.type === 'frame' ? decodeRelayClientFrame(assembled.data) : null\n if (!frame) {\n socket.close(RELAY_CLOSE.protocol, 'Malformed collaboration frame')\n return\n }\n if (frame.type === 'auth') {\n state.busy = true\n void authenticate(frame.token)\n .catch((error: unknown) => {\n relay.report('Checking a collaboration ticket failed', error, verified)\n socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')\n })\n .finally(() => {\n state.busy = false\n flush()\n })\n return\n }\n if (!peer) {\n socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n return\n }\n const delivered = relay.deliver(peer, frame)\n if (!delivered) return\n // The room's document is loading; this peer's later messages wait for it.\n state.busy = true\n void delivered.finally(() => {\n state.busy = false\n flush()\n })\n }\n\n function flush() {\n while (!state.busy && !state.closed && queued.length > 0) {\n const next = queued.shift()\n if (!next) continue\n queuedBytes -= next.byteLength\n process(next)\n }\n }\n\n return {\n receive(data) {\n if (state.closed) return\n queuedBytes += data.byteLength\n // Before admission a peer has sent its ticket and has nothing else to say, so what\n // waits for the room to open is held to one message's worth.\n if (!peer && queuedBytes > relay.maximumMessageBytes) {\n queued.length = 0\n queuedBytes = 0\n socket.close(RELAY_CLOSE.messageTooLarge, 'Too much sent before joining the room')\n return\n }\n queued.push(data)\n flush()\n },\n closed() {\n state.closed = true\n queued.length = 0\n queuedBytes = 0\n clearTimeout(authTimer)\n if (peer) relay.depart(peer)\n }\n }\n}\n","import * as Y from 'yjs'\n\nimport type { CollaborationRoomIdentity, CollaborationStateStore } from './persistence'\n\n/** When a room folds its log into a fresh snapshot: after this many updates or bytes logged. */\nexport type RoomLogLimits = { updates: number; bytes: number }\n\nexport type RoomLog = {\n /**\n * Saves what the document took since the last save: one merged update in the log, or a snapshot\n * in the log's place once it reaches its limits, as the room closes, or after a failed save.\n * Saves run one at a time; a refused one rejects, and the next save writes a snapshot.\n */\n save(options?: { closing?: boolean }): Promise<void>\n}\n\n/**\n * A room's document as its store saved it, its snapshot with the updates logged after it, and the\n * log its saves go to. Each room has one writer, the relay holding it, so sequences only grow.\n */\nexport async function openRoomLog(\n store: CollaborationStateStore,\n room: CollaborationRoomIdentity,\n limits: RoomLogLimits\n): Promise<{ document: Y.Doc; log: RoomLog; savedBytes: number }> {\n const saved = await store.load(room)\n const document = new Y.Doc()\n if (saved.snapshot) Y.applyUpdate(document, saved.snapshot)\n for (const update of saved.updates) Y.applyUpdate(document, update)\n\n /** Updates since the last save, which the next one logs. */\n let pending: Uint8Array[] = []\n document.on('update', (update: Uint8Array) => pending.push(update))\n /** The last sequence a save may have written: an append that failed may still have landed. */\n let sequence = saved.sequence\n let loggedCount = saved.updates.length\n let loggedBytes = saved.updates.reduce((total, update) => total + update.byteLength, 0)\n /** Set by a failed save, after which only a snapshot is sure to hold the room. */\n let compactNext = false\n /** The save in flight; the next one waits for it, so two never claim one sequence. */\n let saving: Promise<void> = Promise.resolve()\n\n async function write(closing: boolean) {\n const compact =\n compactNext ||\n loggedCount >= limits.updates ||\n loggedBytes >= limits.bytes ||\n (closing && (loggedCount > 0 || pending.length > 0))\n // Updates that arrive while this save is in flight go to the next one.\n const batch = pending\n pending = []\n if (compact) {\n await store.compact(room, sequence, Y.encodeStateAsUpdate(document))\n loggedCount = 0\n loggedBytes = 0\n compactNext = false\n } else if (batch.length > 0) {\n const update = Y.mergeUpdates(batch)\n sequence += 1\n await store.append(room, sequence, update)\n loggedCount += 1\n loggedBytes += update.byteLength\n }\n }\n\n const log: RoomLog = {\n save({ closing = false } = {}) {\n const run = saving.then(() => write(closing))\n saving = run.catch(() => {\n compactNext = true\n })\n return run\n }\n }\n const savedBytes =\n (saved.snapshot?.byteLength ?? 0) +\n saved.updates.reduce((total, update) => total + update.byteLength, 0)\n return { document, log, savedBytes }\n}\n","import {\n COLLAB_ACTIONS,\n decodeRoomUpdate,\n encodeSyncReply,\n RELAY_CLOSE,\n RELAY_SERVER_PEER,\n relayServerMessages,\n type RelayServerFrame\n} from '#cloud/contract'\nimport * as Y from 'yjs'\n\nimport type { RelayPeer, RelaySocket } from './connection'\nimport type { RoomLog } from './log'\n\n/**\n * A room's document and the log its saves go to, loaded when a message first needs them, with an\n * upper bound on the document's size: what was saved plus every update since. The bound is\n * measured again only once it reaches `maximumRoomBytes` after something was deleted, since only\n * a deletion can leave the document smaller than the bound.\n */\nexport type RoomContent = {\n document: Y.Doc\n log: RoomLog\n bytes: number\n deletedSinceMeasure: boolean\n}\n\nexport type Room = {\n id: string\n identity: { documentId: string; roomEpoch: number }\n peers: Map<string, RelayPeer>\n persistTimer: ReturnType<typeof setTimeout> | null\n /**\n * Null until a message needs the document: peers resumed after the runtime woke the relay\n * exchange presence without it, so a wake for presence alone loads nothing from the store.\n */\n content: RoomContent | null\n loading: Promise<RoomContent> | null\n}\n\n/** A room with no peers whose document has not been loaded. */\nexport function newRoom(id: string, identity: Room['identity']): Room {\n return { id, identity, peers: new Map(), persistTimer: null, content: null, loading: null }\n}\n\n/** Sends a frame to one socket, split into fragments as the relay sends every frame. */\nexport function send(socket: RelaySocket, frame: RelayServerFrame) {\n for (const message of relayServerMessages(frame)) socket.send(message)\n}\n\n/** Sends one frame to every socket, encoding it once. */\nexport function sendAll(sockets: Iterable<RelaySocket>, frame: RelayServerFrame) {\n const messages = relayServerMessages(frame)\n for (const socket of sockets) for (const message of messages) socket.send(message)\n}\n\n/** Whether a room message carries a document update the room applies. */\nexport const updatesDocument = (namespace: string) =>\n namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply\n\n/** Whether handling a message reads or writes the room's document. */\nexport function needsDocument(namespace: string, target: string | null): boolean {\n if (updatesDocument(namespace)) return true\n return target === RELAY_SERVER_PEER && namespace === COLLAB_ACTIONS.syncStep1\n}\n\n/** Whether `update` adds nothing and deletes only content `document` already holds. */\nfunction deletesOnlyKnown(document: Y.Doc, update: Uint8Array): boolean {\n const { from, to } = Y.parseUpdateMetaV2(update)\n if (![...to].every(([client, clock]) => from.get(client) === clock)) return false\n const { ds } = Y.decodeUpdateV2(update)\n for (const [client, deletions] of ds.clients) {\n const held = Y.getState(document.store, client)\n if (deletions.some((deletion) => deletion.clock + deletion.len > held)) return false\n }\n return true\n}\n\n/**\n * Whether the room's document stays within `limit` after `update`. An update that only deletes\n * what the room holds shrinks it, so it always fits; one that deletes what the room has not\n * received waits in the document, so it counts like any other. Otherwise the bound grows by the\n * update; past the limit, the document is measured only if a deletion may have shrunk it since\n * the last measure, so edits near the limit never encode the whole document each time.\n */\nfunction fits(content: RoomContent, update: Uint8Array, limit: number): boolean {\n if (deletesOnlyKnown(content.document, update)) return true\n if (content.bytes + update.byteLength <= limit) return true\n if (!content.deletedSinceMeasure) return false\n content.bytes = Y.encodeStateAsUpdateV2(content.document).byteLength\n content.deletedSinceMeasure = false\n return content.bytes + update.byteLength <= limit\n}\n\n/**\n * Applies a peer's V2 update to the room, inflated first for a sync reply, closing the peer's\n * socket when it is malformed or would grow the document past `limit`. Rooms are saved as V1\n * updates; only what peers exchange is V2.\n */\nexport function applyToRoom(\n content: RoomContent,\n peer: RelayPeer,\n namespace: string,\n payload: Uint8Array,\n limit: number\n): boolean {\n const { document } = content\n try {\n const update = decodeRoomUpdate(payload, {\n limit,\n compressed: namespace === COLLAB_ACTIONS.syncReply\n })\n if (!update || !fits(content, update, limit)) {\n peer.socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration update is too large')\n return false\n }\n Y.applyUpdateV2(document, update, peer.id)\n content.bytes += update.byteLength\n return true\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed document update')\n return false\n }\n}\n\n/**\n * Handles a message addressed to the relay's own peer: a sync request is answered from the\n * room's document, and a sync reply is applied to it.\n */\nexport function answerAsServer(\n content: RoomContent,\n peer: RelayPeer,\n namespace: string,\n payload: Uint8Array,\n limit: number\n) {\n if (namespace === COLLAB_ACTIONS.syncStep1) {\n let reply: Uint8Array\n try {\n reply = encodeSyncReply(content.document, payload)\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed state vector')\n return\n }\n send(peer.socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncReply,\n from: RELAY_SERVER_PEER,\n payload: reply\n })\n } else if (namespace === COLLAB_ACTIONS.syncReply) {\n applyToRoom(content, peer, namespace, payload, limit)\n }\n}\n","import {\n COLLAB_ACTIONS,\n MAX_COLLAB_MESSAGE_BYTES,\n RELAY_CLOSE,\n RELAY_SERVER_PEER,\n type RelayServerFrame\n} from '#cloud/contract'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport * as Y from 'yjs'\n\nimport { DEADLINE_MS, SECOND_MS } from '@open-pencil/std/timing'\n\nimport type { RelayAuthorization } from './authorize'\nimport { stampAwareness } from './awareness'\nimport {\n openRelayConnection,\n type ConnectionRelay,\n type RelayConnection,\n type RelayPeer,\n type RelayRoomFrame,\n type RelaySocket\n} from './connection'\nimport { openRoomLog } from './log'\nimport type { CollaborationStateStore } from './persistence'\nimport type { RelayPeerState } from './resume'\nimport {\n answerAsServer,\n applyToRoom,\n needsDocument,\n newRoom,\n send,\n sendAll,\n updatesDocument,\n type Room,\n type RoomContent\n} from './room'\n\n/** How long a room waits after an edit before saving, so a burst of edits saves once. */\nconst PERSIST_DELAY_MS = 2 * SECOND_MS\n/** How long a room waits to save again after a save failed. */\nconst PERSIST_RETRY_MS = 30 * SECOND_MS\n/** How long a new socket has to present its ticket before the room closes it. */\nconst AUTH_TIMEOUT_MS = DEADLINE_MS.request\n\nexport type { RelayConnection, RelaySocket } from './connection'\n\n/**\n * What a relay failure names: the room's document, and the user whose message met it. A peer\n * that failed to be admitted names only the document a single-document relay serves.\n */\nexport type RelayErrorIds = { documentId?: string; userId?: string }\n\n/** A verified ticket's document, and its person when they signed in rather than came as a guest. */\nfunction ticketIds({ documentId, principal }: RelayAuthorization): RelayErrorIds {\n return principal.kind === 'user' ? { documentId, userId: principal.userId } : { documentId }\n}\n\nexport type CollaborationRelayOptions = {\n authSecret: string\n store: CollaborationStateStore\n /**\n * The one document this relay serves, for runtimes that run a relay per document; tickets for\n * any other document are refused.\n */\n documentId?: string\n /**\n * The most one socket message may carry. An editor's larger frames arrive as fragments joined\n * up to `maximumRoomBytes`; anyone else's frame must fit in one message.\n */\n maximumMessageBytes: number\n /**\n * The most a room's document may hold, and so the most one editor's update may carry:\n * `MAX_COLLAB_MESSAGE_BYTES` unless the runtime holds rooms in less memory.\n */\n maximumRoomBytes?: number\n maximumConnectionsPerRoom: number\n /** The participant limit policy sets for a document, or null for none. */\n maximumParticipants?: (documentId: string) => Promise<number | null>\n /**\n * The document's current collaboration epoch, which a restore advances; a ticket for an earlier\n * room is turned away so nobody rejoins the document as it was.\n */\n currentRoomEpoch?: (documentId: string) => Promise<number | null>\n /** How long after a change the room's document is saved. */\n persistDelayMs?: number\n /**\n * How many logged updates, or how many of their bytes, a room saves before it writes a fresh\n * snapshot in their place; a closing room always does.\n */\n compactAfterUpdates?: number\n compactAfterBytes?: number\n /** How long a room whose last save failed waits before saving again. */\n persistRetryMs?: number\n /** How long a socket may stay open without presenting a ticket. */\n authTimeoutMs?: number\n /** Told of each failure, with the document and, when one asked, the signed-in user. */\n onError?: (message: string, error: unknown, ids?: RelayErrorIds) => void\n}\n\n/** Messages a viewer may send; their document writes never leave the relay. */\nconst VIEWER_ACTIONS = new Set<string>([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness])\n\nexport type CollaborationRelay = ReturnType<typeof createCollaborationRelay>\n\n/**\n * A runtime-neutral relay for collaboration rooms. It forwards room messages between peers and\n * joins every room as a peer itself: it holds the room's document, answers sync requests from\n * it, saves it, drops document writes from viewers, and stamps presence with verified identity.\n */\nexport function createCollaborationRelay(options: CollaborationRelayOptions) {\n const rooms = new Map<string, Room>()\n const opening = new Map<string, Promise<Room>>()\n /** Rooms whose last peer left and whose document is still being saved. */\n const closing = new Map<string, Promise<void>>()\n /** Set by `close()`: a failed save then drops the room instead of retrying. */\n let shuttingDown = false\n const persistDelayMs = options.persistDelayMs ?? PERSIST_DELAY_MS\n const persistRetryMs = options.persistRetryMs ?? PERSIST_RETRY_MS\n const logLimits = {\n updates: options.compactAfterUpdates ?? 500,\n bytes: options.compactAfterBytes ?? 4 * 1024 * 1024\n }\n const maximumRoomBytes = Math.min(\n options.maximumRoomBytes ?? MAX_COLLAB_MESSAGE_BYTES,\n MAX_COLLAB_MESSAGE_BYTES\n )\n const authTimeoutMs = options.authTimeoutMs ?? AUTH_TIMEOUT_MS\n const report =\n options.onError ??\n ((message, error, ids) =>\n logCloud('error', message, { source: 'relay', ...ids, error: loggedError(error) }))\n\n async function openRoom(authorization: RelayAuthorization): Promise<Room> {\n const existing = rooms.get(authorization.roomId)\n if (existing) return existing\n const pending = opening.get(authorization.roomId)\n if (pending) return pending\n const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }\n const created = (async () => {\n // A room reopened while its last save is in flight must load what that save writes, or,\n // when the save failed, take the room it kept.\n await closing.get(authorization.roomId)\n // A room resumed without its document loads it in place; a new one joins the rooms once\n // loaded, so a restore while it loads finds nothing to end and the epoch check turns it away.\n const room = rooms.get(authorization.roomId) ?? newRoom(authorization.roomId, identity)\n await contentOf(room)\n if (!rooms.has(room.id)) rooms.set(room.id, room)\n return room\n })()\n opening.set(authorization.roomId, created)\n try {\n return await created\n } finally {\n opening.delete(authorization.roomId)\n }\n }\n\n /** The room's document and log, loaded from the store the first time something needs them. */\n function contentOf(room: Room): Promise<RoomContent> {\n if (room.content) return Promise.resolve(room.content)\n room.loading ??= openRoomLog(options.store, room.identity, logLimits).then(\n ({ document, log, savedBytes }) => {\n document.on('update', () => schedulePersist(room))\n // The saved log may hold deletions, so the first time the bound reaches the limit, it is\n // measured.\n const content: RoomContent = { document, log, bytes: savedBytes, deletedSinceMeasure: true }\n document.on('afterTransaction', (transaction: Y.Transaction) => {\n if (transaction.deleteSet.clients.size > 0) content.deletedSinceMeasure = true\n })\n room.content = content\n return content\n },\n (error: unknown) => {\n room.loading = null\n throw error\n }\n )\n return room.loading\n }\n\n /** Saves what changed in the room since its last save; false when the store refused it. */\n async function persist(room: Room, closing = false): Promise<boolean> {\n if (room.persistTimer) clearTimeout(room.persistTimer)\n room.persistTimer = null\n // A room nobody needed the document of since it was resumed has nothing new to save, but\n // a closing one loads it anyway, to fold what its earlier wakes logged into a snapshot.\n if (!room.content && !closing) return true\n try {\n const { log } = await contentOf(room)\n await log.save({ closing })\n return true\n } catch (error) {\n report('Saving a collaboration room failed', error, { documentId: room.identity.documentId })\n // The room holds edits the store doesn't have; save again without waiting for another edit.\n // A closing room retries through `saveAndClose`.\n if (!closing && rooms.get(room.id) === room) {\n room.persistTimer ??= setTimeout(() => void persist(room), persistRetryMs)\n }\n return false\n }\n }\n\n function schedulePersist(room: Room) {\n room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs)\n }\n\n function forward(\n room: Room,\n from: RelayPeer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const frame: RelayServerFrame = { type: 'message', namespace, from: from.id, payload }\n const recipients = target\n ? [room.peers.get(target)]\n : [...room.peers.values()].filter((peer) => peer !== from)\n sendAll(deliverable(recipients.flatMap((peer) => (peer ? [peer] : []))), frame)\n }\n\n function handleMessage(\n room: Room,\n content: RoomContent | null,\n peer: RelayPeer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const readOnly = peer.authorization.permission === 'view'\n if (readOnly && !VIEWER_ACTIONS.has(namespace)) return\n // Only the server says the history or the comments changed.\n if (namespace === COLLAB_ACTIONS.versions || namespace === COLLAB_ACTIONS.comments) return\n\n let forwarded = payload\n if (namespace === COLLAB_ACTIONS.awareness) {\n const stamped = stampAwareness(payload, peer.authorization, (clientId) =>\n [...room.peers.values()].some(\n (other) => other !== peer && other.presenceClients.has(clientId)\n )\n )\n const known = peer.presenceClients.size\n for (const clientId of stamped.claimed) peer.presenceClients.add(clientId)\n if (peer.presenceClients.size !== known) remember(peer)\n if (!stamped.update) return\n forwarded = stamped.update\n }\n\n if (target === RELAY_SERVER_PEER) {\n if (content) answerAsServer(content, peer, namespace, payload, maximumRoomBytes)\n return\n }\n if (\n updatesDocument(namespace) &&\n !(content && applyToRoom(content, peer, namespace, payload, maximumRoomBytes))\n ) {\n return\n }\n forward(room, peer, namespace, target, forwarded)\n }\n\n /**\n * Whether the peer's ticket still holds, closing its socket when it lapsed. It is checked when\n * the relay hears from the peer and before it sends the peer anything, never by a timer, so a\n * runtime can set an idle relay aside while sockets stay open.\n */\n function current(peer: RelayPeer): boolean {\n if (Date.now() < peer.authorization.expiresAt) return true\n peer.socket.close(RELAY_CLOSE.expired, 'Collaboration ticket expired')\n return false\n }\n\n /** The sockets of peers whose tickets still hold. */\n function deliverable(peers: Iterable<RelayPeer>): RelaySocket[] {\n return [...peers].filter(current).map((peer) => peer.socket)\n }\n\n /** Sends a server message to every peer in the document's rooms. */\n function announce(documentId: string, namespace: string, payload: Uint8Array) {\n const frame: RelayServerFrame = { type: 'message', namespace, from: RELAY_SERVER_PEER, payload }\n sendAll(\n deliverable(\n [...rooms.values()]\n .filter((room) => room.identity.documentId === documentId)\n .flatMap((room) => [...room.peers.values()])\n ),\n frame\n )\n }\n\n function remember(peer: RelayPeer) {\n peer.socket.remember?.({\n peerId: peer.id,\n authorization: peer.authorization,\n presenceClients: [...peer.presenceClients]\n })\n }\n\n /** Handles a room message from an admitted peer; a promise while the room's document loads. */\n function deliver(peer: RelayPeer, frame: RelayRoomFrame): Promise<void> | undefined {\n const room = rooms.get(peer.authorization.roomId)\n if (!room) {\n peer.socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n return undefined\n }\n if (!current(peer)) return undefined\n const { namespace, target, payload } = frame\n if (room.content || !needsDocument(namespace, target)) {\n handleMessage(room, room.content, peer, namespace, target, payload)\n return undefined\n }\n return contentOf(room).then(\n (content) => {\n // The peer may have left, or its ticket lapsed, while the document loaded.\n if (room.peers.get(peer.id) !== peer || !current(peer)) return undefined\n handleMessage(room, content, peer, namespace, target, payload)\n return undefined\n },\n (error: unknown) => {\n report('Loading a collaboration room failed', error, ticketIds(peer.authorization))\n peer.socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')\n }\n )\n }\n\n async function admit(\n socket: RelaySocket,\n authorization: RelayAuthorization\n ): Promise<RelayPeer | null> {\n let room: Room\n let limit: number | null | undefined\n let epoch: number | null | undefined\n // The room's last peer may have left while it opened, or a restore or takedown ended it; a\n // closed room takes no newcomers. The limit and epoch are read once the room is open, so\n // neither a restore nor a takedown can slip between.\n do {\n room = await openRoom(authorization)\n limit = await options.maximumParticipants?.(authorization.documentId)\n epoch = await options.currentRoomEpoch?.(authorization.documentId)\n } while (rooms.get(room.id) !== room)\n if (epoch != null && authorization.roomEpoch < epoch) {\n socket.close(RELAY_CLOSE.restored, 'The document was restored')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const capacity = Math.min(limit ?? Number.POSITIVE_INFINITY, options.maximumConnectionsPerRoom)\n if (room.peers.size >= capacity) {\n socket.close(RELAY_CLOSE.roomFull, 'Collaboration room is full')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const peer: RelayPeer = {\n id: crypto.randomUUID(),\n socket,\n authorization,\n presenceClients: new Set()\n }\n remember(peer)\n send(socket, {\n type: 'welcome',\n peerId: peer.id,\n peers: [RELAY_SERVER_PEER, ...room.peers.keys()]\n })\n sendAll(deliverable(room.peers.values()), { type: 'join', peerId: peer.id })\n room.peers.set(peer.id, peer)\n // Ask for what the newcomer has that the room lacks, such as edits made offline.\n if (authorization.permission === 'edit') {\n const { document } = await contentOf(room)\n send(socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncStep1,\n from: RELAY_SERVER_PEER,\n payload: Y.encodeStateVector(document)\n })\n }\n return peer\n }\n\n async function saveAndClose(room: Room) {\n if ((await persist(room, true)) || shuttingDown) {\n room.content?.document.destroy()\n return\n }\n // The room holds edits the store doesn't have: keep it for whoever joins next, and save\n // again later, closing it once a save lands while nobody is in it.\n rooms.set(room.id, room)\n room.persistTimer = setTimeout(() => {\n void (room.peers.size > 0 ? persist(room) : leaveRoom(room))\n }, persistRetryMs)\n }\n\n async function leaveRoom(room: Room) {\n if (room.peers.size > 0 || rooms.get(room.id) !== room) return\n rooms.delete(room.id)\n const saved = saveAndClose(room)\n closing.set(room.id, saved)\n try {\n await saved\n } finally {\n if (closing.get(room.id) === saved) closing.delete(room.id)\n }\n }\n\n function depart(peer: RelayPeer) {\n const room = rooms.get(peer.authorization.roomId)\n if (!room?.peers.delete(peer.id)) return\n sendAll(deliverable(room.peers.values()), { type: 'leave', peerId: peer.id })\n void leaveRoom(room)\n }\n\n /**\n * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with\n * the peer it already is.\n */\n const connectionRelay: ConnectionRelay = {\n authSecret: options.authSecret,\n documentId: options.documentId,\n maximumMessageBytes: options.maximumMessageBytes,\n maximumUpdateBytes: maximumRoomBytes,\n authTimeoutMs,\n admit,\n refreshed: remember,\n deliver,\n depart,\n report: (message, error, authorization) => {\n // Before a ticket verified, only the document a per-document relay serves is known.\n const configured = options.documentId === undefined ? {} : { documentId: options.documentId }\n report(message, error, authorization ? ticketIds(authorization) : configured)\n }\n }\n\n return {\n connect(socket: RelaySocket): RelayConnection {\n return openRelayConnection(socket, null, connectionRelay)\n },\n\n /**\n * Takes back a socket whose peer was admitted before the runtime set the relay aside, as the\n * peer it was, without loading the room's document until a message needs it. A peer whose\n * ticket lapsed meanwhile is closed.\n */\n resume(socket: RelaySocket, saved: RelayPeerState): RelayConnection {\n const { authorization } = saved\n const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }\n let room = rooms.get(authorization.roomId)\n if (!room) {\n room = newRoom(authorization.roomId, identity)\n rooms.set(room.id, room)\n }\n const peer: RelayPeer = {\n id: saved.peerId,\n socket,\n authorization,\n presenceClients: new Set(saved.presenceClients)\n }\n room.peers.set(peer.id, peer)\n const connection = openRelayConnection(socket, peer, connectionRelay)\n // After the runtime holds the connection, which its socket's close reports to.\n queueMicrotask(() => current(peer))\n return connection\n },\n\n /**\n * Ends a restored document's rooms: everyone in them is told the document was restored, and\n * their edits to the replaced state are dropped rather than saved.\n */\n startOver(documentId: string) {\n // A map's iteration carries on past entries deleted during it.\n for (const room of rooms.values()) {\n if (room.identity.documentId !== documentId) continue\n rooms.delete(room.id)\n if (room.persistTimer) clearTimeout(room.persistTimer)\n for (const peer of room.peers.values()) {\n peer.socket.close(RELAY_CLOSE.restored, 'The document was restored')\n }\n room.peers.clear()\n room.content?.document.destroy()\n }\n },\n\n /**\n * Ends a taken-down document's rooms for everyone in them, saving what each room holds, so\n * a restore opens them again with every edit. Nobody gets back in meanwhile: tickets are\n * issued only for documents people can reach.\n */\n closeDocument(documentId: string) {\n for (const room of rooms.values()) {\n if (room.identity.documentId !== documentId) continue\n for (const peer of room.peers.values()) {\n peer.socket.close(RELAY_CLOSE.unauthorized, 'The document was taken down')\n }\n room.peers.clear()\n void leaveRoom(room)\n }\n },\n\n /** Tells everyone in a document's rooms that its version history changed. */\n announceVersions(documentId: string) {\n announce(documentId, COLLAB_ACTIONS.versions, new Uint8Array())\n },\n\n /** Tells everyone in a document's rooms that one of its comment threads changed. */\n announceComments(documentId: string, threadId: string) {\n announce(documentId, COLLAB_ACTIONS.comments, new TextEncoder().encode(threadId))\n },\n\n /** Saves every open room and closes its sockets, as the runtime shuts down. */\n async close() {\n shuttingDown = true\n await Promise.all(\n [...rooms.values()].map(async (room) => {\n for (const peer of room.peers.values()) {\n peer.socket.close(1001, 'Server shutting down')\n }\n room.peers.clear()\n await leaveRoom(room)\n })\n )\n // Rooms whose last peer left just before, or during, shutdown are still saving.\n await Promise.all(closing.values())\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { fromUint8Array } from 'js-base64'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type CollaborationRoomIdentity = {\n documentId: string\n roomEpoch: number\n}\n\n/** A room as the store keeps it: its last snapshot and the updates logged after it. */\nexport type SavedRoom = {\n snapshot: Uint8Array | null\n /** The updates after the snapshot, in the order they were logged. */\n updates: Uint8Array[]\n /** The sequence of the last update the snapshot or the log holds; 0 for a new room. */\n sequence: number\n}\n\n/**\n * The relay's saved copy of each room's document, by document and collaboration epoch: a snapshot\n * and an append-only log of the updates after it. Each room has one writer, the relay that holds\n * it, so sequences only grow.\n */\nexport type CollaborationStateStore = {\n load(room: CollaborationRoomIdentity): Promise<SavedRoom>\n /**\n * Logs one update; fails when the sequence is already taken. Writes nothing once a restore moved\n * the document past the room's epoch, since that room never opens again.\n */\n append(room: CollaborationRoomIdentity, sequence: number, update: Uint8Array): Promise<void>\n /**\n * Replaces the snapshot with `state`, which holds every update through `sequence`, and drops\n * those updates; running it again leaves the same room. Like `append`, it changes no room of an\n * epoch a restore replaced.\n */\n compact(room: CollaborationRoomIdentity, sequence: number, state: Uint8Array): Promise<void>\n}\n\n/**\n * Whether the document is still at the room's epoch, holding its row so a restore, which advances\n * the epoch and deletes the replaced rooms' rows, waits for this write or this write sees it.\n */\nasync function holdsEpoch(\n transaction: Transaction<CloudDatabase>,\n room: CollaborationRoomIdentity\n): Promise<boolean> {\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', room.documentId)\n .forShare()\n .executeTakeFirst()\n return document?.collaborationEpoch === room.roomEpoch\n}\n\n/** A snapshot is a Yjs update, as the store hands it back. */\nconst SNAPSHOT_CONTENT_TYPE = 'application/octet-stream'\n\n/**\n * Where a room's snapshots go. Each compaction writes a new file and points the room at it; the one\n * it replaced is no longer referenced, and the object sweep removes it as it does a deleted\n * revision's file.\n */\nfunction snapshotKey(room: CollaborationRoomIdentity): string {\n return `collaboration/${room.documentId}/${room.roomEpoch}/${crypto.randomUUID()}.yjs`\n}\n\n/**\n * A store keeping each room's snapshot as a file in the object store and the updates logged after\n * it in the database, so the database holds only what changed since the last snapshot.\n */\nexport function createCollaborationStateStore(\n database: Kysely<CloudDatabase>,\n objects: Pick<ObjectStore, 'write' | 'read'>\n): CollaborationStateStore {\n return {\n async load(room) {\n const snapshot = await database\n .selectFrom('documentRoomSnapshot')\n .innerJoin('storageObject', 'storageObject.id', 'documentRoomSnapshot.snapshotObjectId')\n .select(['storageObject.objectKey', 'documentRoomSnapshot.throughSequence'])\n .where('documentRoomSnapshot.documentId', '=', room.documentId)\n .where('documentRoomSnapshot.roomEpoch', '=', room.roomEpoch)\n .executeTakeFirst()\n const state = snapshot ? await objects.read(snapshot.objectKey) : null\n if (snapshot && !state) {\n throw new Error(`The snapshot of room ${room.documentId}:${room.roomEpoch} is missing`)\n }\n const through = snapshot?.throughSequence ?? 0\n const updates = await database\n .selectFrom('documentRoomUpdate')\n .select(['sequence', 'data'])\n .where('documentId', '=', room.documentId)\n .where('roomEpoch', '=', room.roomEpoch)\n .where('sequence', '>', through)\n .orderBy('sequence')\n .execute()\n return {\n snapshot: state,\n updates: updates.map((row) => new Uint8Array(row.data)),\n sequence: updates.at(-1)?.sequence ?? through\n }\n },\n\n async append(room, sequence, update) {\n await database.transaction().execute(async (transaction) => {\n if (!(await holdsEpoch(transaction, room))) return\n await transaction\n .insertInto('documentRoomUpdate')\n .values({\n documentId: room.documentId,\n roomEpoch: room.roomEpoch,\n sequence,\n data: update\n })\n .execute()\n })\n },\n\n async compact(room, sequence, state) {\n // The file is recorded before it is written and referenced only once the room points at it,\n // so a compaction that fails anywhere leaves a file nothing refers to, which the object sweep\n // removes; none is ever deleted while a room might still point at it.\n const snapshotObjectId = crypto.randomUUID()\n const objectKey = snapshotKey(room)\n const checksum = fromUint8Array(sha256(state))\n await database\n .insertInto('storageObject')\n .values({\n id: snapshotObjectId,\n objectKey,\n checksum,\n byteSize: state.byteLength,\n contentType: SNAPSHOT_CONTENT_TYPE\n })\n .execute()\n await objects.write({\n key: objectKey,\n bytes: state,\n contentType: SNAPSHOT_CONTENT_TYPE,\n checksum\n })\n await database.transaction().execute(async (transaction) => {\n if (!(await holdsEpoch(transaction, room))) return\n await transaction\n .insertInto('documentRoomSnapshot')\n .values({\n documentId: room.documentId,\n roomEpoch: room.roomEpoch,\n snapshotObjectId,\n throughSequence: sequence,\n updatedAt: new Date()\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'roomEpoch']).doUpdateSet({\n snapshotObjectId,\n throughSequence: sequence,\n updatedAt: new Date()\n })\n )\n .execute()\n await transaction\n .deleteFrom('documentRoomUpdate')\n .where('documentId', '=', room.documentId)\n .where('roomEpoch', '=', room.roomEpoch)\n .where('sequence', '<=', sequence)\n .execute()\n })\n }\n }\n}\n","import { collaborationPrincipalSchema } from '#cloud/contract'\nimport * as v from 'valibot'\n\nconst peerStateSchema = v.object({\n peerId: v.pipe(v.string(), v.uuid()),\n authorization: v.object({\n roomId: v.string(),\n documentId: v.pipe(v.string(), v.uuid()),\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n permission: v.picklist(['view', 'edit']),\n principal: collaborationPrincipalSchema,\n expiresAt: v.number()\n }),\n presenceClients: v.array(v.pipe(v.number(), v.integer()))\n})\n\n/**\n * What a runtime keeps with each admitted socket so the relay can resume its peer after the\n * runtime set the relay aside, as a hibernating Durable Object does: who it is, what its ticket\n * allows, and the presence clients it speaks for.\n */\nexport type RelayPeerState = v.InferOutput<typeof peerStateSchema>\n\n/** A peer's kept state, or null when what the runtime kept is not one. */\nexport function readRelayPeerState(value: unknown): RelayPeerState | null {\n const parsed = v.safeParse(peerStateSchema, value)\n return parsed.success ? parsed.output : null\n}\n","import { cloudCommentURL, type CommentEmailSetting, type CommentPerson } from '#cloud/contract'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { lockForTransaction } from '#cloud/server/db/expressions'\nimport { resolveDocumentCommentAccess } from '#cloud/server/documents/access'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\nimport { fromMarkdown } from 'mdast-util-from-markdown'\nimport { toString } from 'mdast-util-to-string'\n\nimport { DAY_MS } from '@open-pencil/std/timing'\n\n/**\n * How many comment emails one person's comments may send in a day, and how many one account may\n * receive. A comment's words are the author's, so without a budget mentions are a way to send spam.\n */\nexport const COMMENT_EMAIL_BUDGET = {\n windowMs: DAY_MS,\n perSender: 200,\n perRecipient: 50\n} as const\n\n/** What an account hears about when it chose nothing: comments that name it. */\nexport const DEFAULT_COMMENT_EMAILS: CommentEmailSetting = 'mentions'\n\nconst EXCERPT_LENGTH = 280\n\n/**\n * The start of what a comment says, as plain text on one line: its Markdown read, so a mention\n * reads as `@Ana`, a link as its text, and each block apart from the next.\n */\nexport function commentExcerpt(body: string): string {\n const line = fromMarkdown(body)\n .children.map((block) => toString(block))\n .join(' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return line.length > EXCERPT_LENGTH ? `${line.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : line\n}\n\ntype Source = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/**\n * Everyone a document's comments may name: its workspace's members, the people it was shared with\n * directly, and its maker while they are in the workspace. Names only, never addresses.\n */\nexport async function commentPeople(source: Source, documentId: string): Promise<CommentPerson[]> {\n const document = await source\n .selectFrom('document')\n .select(['workspaceId'])\n .where('id', '=', documentId)\n .executeTakeFirst()\n if (!document) return []\n const members = source\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId as userId')\n .where('workspaceMember.workspaceId', '=', document.workspaceId)\n const grantees = source\n .selectFrom('documentGrant')\n .select('documentGrant.userId as userId')\n .where('documentGrant.documentId', '=', documentId)\n .where('documentGrant.revokedAt', 'is', null)\n const ids = uniq(\n [...(await members.execute()), ...(await grantees.execute())].map((row) => row.userId)\n )\n if (ids.length === 0) return []\n const rows = await source\n .selectFrom('user')\n .select((expression) => [userIdText(expression).as('id'), 'user.name', 'user.image'])\n .where(userIdText, 'in', ids)\n .orderBy('user.name')\n .execute()\n return rows.map((row) => ({ id: row.id, name: row.name, image: row.image ?? null }))\n}\n\n/** The accounts of `ids` a comment by `authorId` may name: others who can read the document. */\nasync function readers(\n transaction: Transaction<CloudDatabase>,\n documentId: string,\n ids: readonly string[],\n authorId: string\n): Promise<string[]> {\n const kept: string[] = []\n for (const id of uniq(ids)) {\n if (id === authorId) continue\n if (await resolveDocumentCommentAccess(transaction, id, documentId)) kept.push(id)\n }\n return kept\n}\n\n/**\n * Records whom a comment names, among those who may read it, and answers who is named now that\n * was not before, so an edit tells only the people it adds.\n */\nexport async function recordMentions(\n transaction: Transaction<CloudDatabase>,\n input: { documentId: string; commentId: string; authorId: string; mentions: readonly string[] }\n): Promise<string[]> {\n const named = await readers(transaction, input.documentId, input.mentions, input.authorId)\n if (named.length === 0) return []\n const added = await transaction\n .insertInto('commentMention')\n .values(named.map((userId) => ({ commentId: input.commentId, userId })))\n .onConflict((conflict) => conflict.columns(['commentId', 'userId']).doNothing())\n .returning('userId')\n .execute()\n return added.map((row) => row.userId)\n}\n\n/** Counts an email against both daily budgets, or answers false once either is used. */\nasync function spendCommentEmail(\n transaction: Transaction<CloudDatabase>,\n senderId: string,\n recipientId: string,\n now: Date\n): Promise<boolean> {\n // Always sender first, then recipient, so two transactions never wait on each other in turn.\n await lockForTransaction(transaction, `comment-email-sender:${senderId}`)\n await lockForTransaction(transaction, `comment-email-recipient:${recipientId}`)\n const since = new Date(now.getTime() - COMMENT_EMAIL_BUDGET.windowMs)\n // Both budgets in one read: what the sender's comments sent, and what the recipient received.\n const spent = await transaction\n .selectFrom('commentEmail')\n .select((expression) => [\n expression.fn.countAll<string>().filterWhere('senderId', '=', senderId).as('sent'),\n expression.fn.countAll<string>().filterWhere('recipientId', '=', recipientId).as('received')\n ])\n .where('sentAt', '>', since)\n .where((expression) =>\n expression.or([\n expression('senderId', '=', senderId),\n expression('recipientId', '=', recipientId)\n ])\n )\n .executeTakeFirstOrThrow()\n if (\n Number(spent.sent) >= COMMENT_EMAIL_BUDGET.perSender ||\n Number(spent.received) >= COMMENT_EMAIL_BUDGET.perRecipient\n ) {\n return false\n }\n await transaction\n .insertInto('commentEmail')\n .values({ id: crypto.randomUUID(), senderId, recipientId, sentAt: now })\n .execute()\n return true\n}\n\n/** Who else wrote in a thread and may still read it: whom a reply tells, as they chose. */\nexport async function threadParticipants(\n transaction: Transaction<CloudDatabase>,\n documentId: string,\n threadId: string,\n authorId: string\n): Promise<string[]> {\n const rows = await transaction\n .selectFrom('comment')\n .select('authorId')\n .where('threadId', '=', threadId)\n .where('authorId', 'is not', null)\n .execute()\n return readers(\n transaction,\n documentId,\n rows.flatMap((row) => (row.authorId ? [row.authorId] : [])),\n authorId\n )\n}\n\nexport type CommentNotifier = {\n email: TransactionalEmailService\n publicURL: string\n}\n\n/**\n * Emails the people a new comment concerns, in the transaction that writes it: those it names,\n * and, for a reply, the thread's other writers who asked to hear about every comment. Each hears\n * once, as their setting allows and while the day's budgets last.\n */\nexport async function notifyComment(\n transaction: Transaction<CloudDatabase>,\n notifier: CommentNotifier,\n comment: {\n id: string\n documentId: string\n threadId: string\n authorId: string\n body: string\n mentioned: readonly string[]\n participants: readonly string[]\n }\n): Promise<void> {\n // In account order, so two comments naming the same people take their budget locks in turn.\n const recipients = [\n ...comment.mentioned.map((userId) => ({ userId, reason: 'mention' as const })),\n ...comment.participants\n .filter((userId) => !comment.mentioned.includes(userId))\n .map((userId) => ({ userId, reason: 'reply' as const }))\n ].toSorted((a, b) => a.userId.localeCompare(b.userId))\n if (recipients.length === 0) return\n const ids = recipients.map((recipient) => recipient.userId)\n const author = comment.authorId\n const [users, settings, document] = await Promise.all([\n transaction\n .selectFrom('user')\n .select((expression) => [userIdText(expression).as('id'), 'user.name', 'user.email'])\n .where(userIdText, 'in', [...ids, comment.authorId])\n .execute(),\n transaction\n .selectFrom('notificationSetting')\n .select(['userId', 'commentEmails'])\n .where('userId', 'in', ids)\n .execute(),\n transaction\n .selectFrom('document')\n .select('name')\n .where('id', '=', comment.documentId)\n .executeTakeFirstOrThrow()\n ])\n const byId = new Map(users.map((user) => [user.id, user]))\n const chosen = new Map(settings.map((setting) => [setting.userId, setting.commentEmails]))\n const now = new Date()\n for (const recipient of recipients) {\n const user = byId.get(recipient.userId)\n const setting = chosen.get(recipient.userId) ?? DEFAULT_COMMENT_EMAILS\n const wanted = setting === 'all' || (setting === 'mentions' && recipient.reason === 'mention')\n if (!user || !wanted) continue\n if (!(await spendCommentEmail(transaction, author, recipient.userId, now))) continue\n await notifier.email.enqueue(\n {\n idempotencyKey: `comment-notification/${comment.id}/${recipient.userId}`,\n kind: 'comment-notification',\n recipientEmail: user.email,\n payload: {\n name: user.name || null,\n authorName: byId.get(author)?.name || null,\n documentName: document.name,\n reason: recipient.reason,\n excerpt: commentExcerpt(comment.body),\n actionURL: cloudCommentURL(notifier.publicURL, comment.documentId, comment.threadId),\n settingsURL: new URL('/account/notifications', notifier.publicURL).href\n }\n },\n transaction\n )\n }\n}\n\n/** Which comments an account hears about by email. */\nexport async function readNotificationSettings(\n database: Kysely<CloudDatabase>,\n userId: string\n): Promise<{ commentEmails: CommentEmailSetting }> {\n const row = await database\n .selectFrom('notificationSetting')\n .select('commentEmails')\n .where('userId', '=', userId)\n .executeTakeFirst()\n return { commentEmails: row?.commentEmails ?? DEFAULT_COMMENT_EMAILS }\n}\n\nexport async function writeNotificationSettings(\n database: Kysely<CloudDatabase>,\n userId: string,\n settings: { commentEmails: CommentEmailSetting }\n): Promise<{ commentEmails: CommentEmailSetting }> {\n await database\n .insertInto('notificationSetting')\n .values({ userId, commentEmails: settings.commentEmails, updatedAt: new Date() })\n .onConflict((conflict) =>\n conflict\n .column('userId')\n .doUpdateSet({ commentEmails: settings.commentEmails, updatedAt: new Date() })\n )\n .execute()\n return settings\n}\n","import type { CloudComment, CloudCommentThread, CommentAnchor } from '#cloud/contract'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { groupBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type Source = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport type ThreadRow = {\n id: string\n pageId: string\n pageName: string | null\n nodeId: string | null\n nodeName: string | null\n offsetX: number | null\n offsetY: number | null\n x: number\n y: number\n createdBy: string\n createdAt: Date\n updatedAt: Date\n resolvedAt: Date | null\n resolvedBy: string | null\n}\n\ntype CommentRow = {\n id: string\n threadId: string\n mentions: string[]\n authorId: string | null\n authorName: string | null\n importedAuthorName: string | null\n agent: string | null\n body: string\n createdAt: Date\n editedAt: Date | null\n}\n\nfunction commentOf(row: CommentRow): CloudComment {\n return {\n id: row.id,\n author:\n row.authorId === null\n ? { kind: 'imported', name: row.importedAuthorName ?? '' }\n : { kind: 'user', id: row.authorId, name: row.authorName },\n agent: row.agent,\n body: row.body,\n mentions: row.mentions,\n createdAt: row.createdAt.toISOString(),\n editedAt: row.editedAt?.toISOString() ?? null\n }\n}\n\n/**\n * Whether someone other than `viewer` wrote in the thread since `readAt`, or at all when the viewer\n * never read it; never for a guest, who has no account to keep it for.\n */\nfunction unreadBy(\n comments: readonly CommentRow[],\n viewer: string | null,\n readAt: Date | undefined\n): boolean {\n if (viewer === null) return false\n return comments.some(\n (comment) => comment.authorId !== viewer && (!readAt || comment.createdAt > readAt)\n )\n}\n\nexport function threadOf(\n row: ThreadRow,\n comments: readonly CommentRow[],\n viewer: string | null,\n readAt: Date | undefined\n): CloudCommentThread {\n return {\n id: row.id,\n pageId: row.pageId,\n pageName: row.pageName,\n nodeId: row.nodeId,\n nodeName: row.nodeName,\n offsetX: row.offsetX,\n offsetY: row.offsetY,\n x: row.x,\n y: row.y,\n createdAt: row.createdAt.toISOString(),\n updatedAt: row.updatedAt.toISOString(),\n resolvedAt: row.resolvedAt?.toISOString() ?? null,\n resolvedBy: row.resolvedBy,\n createdBy: row.createdBy,\n unread: unreadBy(comments, viewer, readAt),\n comments: comments.map(commentOf)\n }\n}\n\nexport function anchorValues(anchor: CommentAnchor) {\n return {\n pageId: anchor.pageId,\n pageName: anchor.pageName,\n nodeId: anchor.nodeId,\n nodeName: anchor.nodeName,\n offsetX: anchor.offsetX,\n offsetY: anchor.offsetY,\n x: anchor.x,\n y: anchor.y\n }\n}\n\n/** How many threads the document holds, resolved ones included. */\nexport async function documentThreadCount(\n transaction: Transaction<CloudDatabase>,\n documentId: string\n): Promise<number> {\n const { count } = await transaction\n .selectFrom('commentThread')\n .select((expression) => expression.fn.countAll<string>().as('count'))\n .where('documentId', '=', documentId)\n .executeTakeFirstOrThrow()\n return Number(count)\n}\n\n/** Holds the document's row, so one writer at a time counts and adds its threads. */\nexport async function lockDocument(transaction: Transaction<CloudDatabase>, documentId: string) {\n await transaction\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n}\n\n/** What resolving or reopening sets, or nothing when the thread already is as asked. */\nexport function resolutionChange(\n resolved: boolean | undefined,\n isResolved: boolean,\n userId: string\n) {\n if (resolved === undefined || resolved === isResolved) return {}\n return resolved\n ? { resolvedAt: new Date(), resolvedBy: userId }\n : { resolvedAt: null, resolvedBy: null }\n}\n\n/** Threads with what a reply shows of them, to narrow by document or ID. */\nexport function threads(source: Source) {\n return source\n .selectFrom('commentThread')\n .select([\n 'commentThread.id',\n 'commentThread.pageId',\n 'commentThread.pageName',\n 'commentThread.nodeId',\n 'commentThread.nodeName',\n 'commentThread.offsetX',\n 'commentThread.offsetY',\n 'commentThread.x',\n 'commentThread.y',\n 'commentThread.createdBy',\n 'commentThread.createdAt',\n 'commentThread.updatedAt',\n 'commentThread.resolvedAt',\n 'commentThread.resolvedBy'\n ])\n}\n\n/** The threads' comments, oldest first, each with whom it names. */\nexport async function comments(\n source: Source,\n threadIds: readonly string[]\n): Promise<CommentRow[]> {\n const rows = await source\n .selectFrom('comment')\n .leftJoin('user', (join) => join.onRef(userIdText, '=', 'comment.authorId'))\n .select([\n 'comment.id',\n 'comment.threadId',\n 'comment.authorId',\n 'user.name as authorName',\n 'comment.importedAuthorName',\n 'comment.agent',\n 'comment.body',\n 'comment.createdAt',\n 'comment.editedAt'\n ])\n .where('comment.threadId', 'in', [...threadIds])\n .orderBy('comment.createdAt')\n .orderBy('comment.id')\n .execute()\n if (rows.length === 0) return []\n const mentions = groupBy(\n await source\n .selectFrom('commentMention')\n .select(['commentId', 'userId'])\n .where(\n 'commentId',\n 'in',\n rows.map((row) => row.id)\n )\n .orderBy('createdAt')\n .execute(),\n (mention) => mention.commentId\n )\n return rows.map((row) => ({\n ...row,\n mentions: (mentions[row.id] ?? []).map((mention) => mention.userId)\n }))\n}\n\n/** When `viewer` last read each of the threads. */\nexport async function readsOf(source: Source, viewer: string | null, threadIds: readonly string[]) {\n if (viewer === null || threadIds.length === 0) return new Map<string, Date>()\n const rows = await source\n .selectFrom('commentRead')\n .select(['threadId', 'readAt'])\n .where('userId', '=', viewer)\n .where('threadId', 'in', [...threadIds])\n .execute()\n return new Map(rows.map((row) => [row.threadId, row.readAt]))\n}\n\n/** Records that `userId` has read the thread as it is now. */\nexport async function markRead(source: Source, userId: string, threadId: string) {\n const readAt = new Date()\n await source\n .insertInto('commentRead')\n .values({ userId, threadId, readAt })\n // A request that read the thread earlier but lands later never moves the marker back.\n .onConflict((conflict) =>\n conflict\n .columns(['userId', 'threadId'])\n .doUpdateSet({ readAt })\n .where('commentRead.readAt', '<', readAt)\n )\n .execute()\n}\n\nexport async function findThread(\n source: Source,\n documentId: string,\n threadId: string,\n lock = false\n) {\n let query = threads(source)\n .where('commentThread.documentId', '=', documentId)\n .where('commentThread.id', '=', threadId)\n if (lock) query = query.forUpdate()\n const row = await query.executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n}\n","import {\n MAX_COMMENT_THREADS_PER_DOCUMENT,\n MAX_COMMENTS_PER_THREAD,\n type CloudCommentThread,\n type CommentAccess,\n type CommentThreads,\n type CreateCommentInput,\n type CreateCommentThreadInput,\n type ImportCommentThreadsInput,\n type NotificationSettings,\n type UpdateCommentInput,\n type UpdateCommentThreadInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { resolveDocumentCommentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { chunk, groupBy, isEmptyObject } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport {\n commentPeople,\n notifyComment,\n recordMentions,\n readNotificationSettings,\n threadParticipants,\n writeNotificationSettings,\n type CommentNotifier\n} from './notify'\nimport {\n anchorValues,\n comments,\n documentThreadCount,\n findThread,\n lockDocument,\n markRead,\n readsOf,\n resolutionChange,\n threadOf,\n threads,\n type ThreadRow,\n type Source\n} from './rows'\n\n/** A document holds as many threads, or a thread as many comments, as it may. */\nexport class CommentLimitError extends Error {\n override readonly name = 'CommentLimitError'\n}\n\n/** A new thread or comment named an ID something else already has. */\nexport class CommentConflictError extends Error {\n override readonly name = 'CommentConflictError'\n}\n\n/**\n * Whose request it is and what they may do, settled before any comment is touched: a member or\n * grantee through `forMember`, or whoever follows a share link through `forShare`.\n */\nexport type CommentActor = Omit<CommentAccess, 'accountId'> & {\n documentId: string\n /** Null for a guest on a link, who may only read. */\n userId: string | null\n}\n\n/** A request's input as callers may write it: naming nobody when it lists no mentions. */\ntype Mentioning<Input extends { mentions: string[] }> = Omit<Input, 'mentions'> & {\n mentions?: readonly string[]\n}\ntype NewThread = Mentioning<CreateCommentThreadInput>\ntype NewComment = Mentioning<CreateCommentInput>\ntype CommentEdit = Mentioning<UpdateCommentInput>\n\n/** Rows one insert writes, within PostgreSQL's parameters per statement. */\nconst INSERT_BATCH = 500\n\n/**\n * A thread's comment times as a file gave them, each after the one before, so the first one is\n * the thread's first wherever the file wrote two at the same moment.\n */\nfunction importedTimes(times: readonly string[]): Date[] {\n const result: Date[] = []\n for (const time of times) {\n const at = new Date(time)\n const previous = result.at(-1)\n result.push(previous && at <= previous ? new Date(previous.getTime() + 1) : at)\n }\n return result\n}\n\nfunction requireCommenter(actor: CommentActor): string {\n if (!actor.canComment || actor.userId === null) throw new DocumentForbiddenError()\n return actor.userId\n}\n\n/**\n * The comments of Cloud documents. Everyone who can read a document reads its comments; everyone\n * signed in who can read writes them. A comment is changed only by its author, and deleted by its\n * author or an editor; a thread's pin is moved by whoever started it or an editor, and anyone who\n * comments resolves or reopens it. Deleting a thread's first comment deletes the thread.\n */\nexport function createCommentService(\n database: Kysely<CloudDatabase>,\n options: {\n sharing?: Pick<DocumentSharingService, 'resolveShare'>\n /** Called once a thread changes, so the document's live rooms fetch it again. */\n onCommentsChanged?: (documentId: string, threadId: string) => void\n /** Emails the people a comment concerns; without it nobody hears by email. */\n notifier?: CommentNotifier\n } = {}\n) {\n /**\n * Records whom a comment names and emails them, and, for a reply, the thread's other writers\n * who asked to hear about everything.\n */\n async function tell(\n transaction: Transaction<CloudDatabase>,\n actor: CommentActor,\n comment: { commentId: string; threadId: string; body: string },\n mentions: readonly string[],\n { reply = false } = {}\n ) {\n const authorId = requireCommenter(actor)\n const mentioned = await recordMentions(transaction, {\n documentId: actor.documentId,\n commentId: comment.commentId,\n authorId,\n mentions\n })\n if (!options.notifier) return\n const participants = reply\n ? await threadParticipants(transaction, actor.documentId, comment.threadId, authorId)\n : []\n await notifyComment(transaction, options.notifier, {\n id: comment.commentId,\n documentId: actor.documentId,\n threadId: comment.threadId,\n authorId,\n body: comment.body,\n mentioned,\n participants\n })\n }\n\n function announce(documentId: string, threadId: string): void {\n try {\n options.onCommentsChanged?.(documentId, threadId)\n } catch (error) {\n logCloud('error', 'Announcing a comment change failed', { error: loggedError(error) })\n }\n }\n\n async function readThread(\n source: Source,\n row: ThreadRow,\n viewer: string | null\n ): Promise<CloudCommentThread> {\n const reads = await readsOf(source, viewer, [row.id])\n return threadOf(row, await comments(source, [row.id]), viewer, reads.get(row.id))\n }\n\n /**\n * Marks the thread changed now, and read by whoever changed it, and answers it as it is after\n * the change.\n */\n async function touched(\n transaction: Transaction<CloudDatabase>,\n actor: CommentActor,\n threadId: string\n ): Promise<CloudCommentThread> {\n await transaction\n .updateTable('commentThread')\n .set({ updatedAt: new Date() })\n .where('id', '=', threadId)\n .execute()\n if (actor.userId !== null) await markRead(transaction, actor.userId, threadId)\n return readThread(\n transaction,\n await findThread(transaction, actor.documentId, threadId),\n actor.userId\n )\n }\n\n async function findComment(\n source: Source,\n threadId: string,\n commentId: string\n ): Promise<{ authorId: string | null; first: boolean }> {\n const rows = await source\n .selectFrom('comment')\n .select(['id', 'authorId'])\n .where('threadId', '=', threadId)\n .orderBy('createdAt')\n .orderBy('id')\n .execute()\n const index = rows.findIndex((comment) => comment.id === commentId)\n const found = rows[index]\n if (!found) throw new DocumentNotFoundError()\n return { authorId: found.authorId, first: index === 0 }\n }\n\n /** A comment of a thread, with the thread held until the transaction ends. */\n async function lockedComment(\n transaction: Transaction<CloudDatabase>,\n actor: CommentActor,\n threadId: string,\n commentId: string\n ) {\n await findThread(transaction, actor.documentId, threadId, true)\n return findComment(transaction, threadId, commentId)\n }\n\n /** Every thread on the document, oldest first, with what the asker may do. */\n async function list(actor: CommentActor): Promise<CommentThreads> {\n const rows = await threads(database)\n .where('commentThread.documentId', '=', actor.documentId)\n .orderBy('commentThread.createdAt')\n .orderBy('commentThread.id')\n .execute()\n const ids = rows.map((row) => row.id)\n const byThread =\n rows.length > 0 ? groupBy(await comments(database, ids), (c) => c.threadId) : {}\n const reads = await readsOf(database, actor.userId, ids)\n return {\n threads: rows.map((row) =>\n threadOf(row, byThread[row.id] ?? [], actor.userId, reads.get(row.id))\n ),\n access: {\n canComment: actor.canComment,\n canModerate: actor.canModerate,\n accountId: actor.userId\n }\n }\n }\n\n return {\n /** A member's or grantee's access to a document's comments. */\n async forMember(userId: string, documentId: string): Promise<CommentActor> {\n const access = await resolveDocumentCommentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return { ...access, documentId, userId }\n },\n\n /**\n * Access through a share link: everyone with it reads; people signed in also comment, and\n * moderate when the link lets them edit. A guest on any link only reads.\n */\n async forShare(\n shareId: string,\n secret: string,\n actor: { userId: string; name: string; email: string } | undefined\n ): Promise<CommentActor> {\n if (!options.sharing) throw new DocumentNotFoundError()\n const resolution = await options.sharing.resolveShare(shareId, { secret }, actor)\n const userId = resolution.principal.kind === 'user' ? resolution.principal.userId : null\n return {\n documentId: resolution.documentId,\n userId,\n canComment: userId !== null,\n canModerate: userId !== null && resolution.permission === 'edit'\n }\n },\n\n list,\n\n async get(actor: CommentActor, threadId: string): Promise<CloudCommentThread> {\n return readThread(\n database,\n await findThread(database, actor.documentId, threadId),\n actor.userId\n )\n },\n\n /** Records that the asker read the thread as it is now; a guest keeps no such record. */\n async markRead(actor: CommentActor, threadId: string): Promise<void> {\n if (actor.userId === null) return\n await findThread(database, actor.documentId, threadId)\n await markRead(database, actor.userId, threadId)\n },\n\n /** Which comments the account hears about by email. */\n notificationSettings: (userId: string) => readNotificationSettings(database, userId),\n setNotificationSettings: (userId: string, settings: NotificationSettings) =>\n writeNotificationSettings(database, userId, settings),\n\n /** Whom the asker may name in the document's comments. */\n async people(actor: CommentActor) {\n requireCommenter(actor)\n return { people: await commentPeople(database, actor.documentId) }\n },\n\n async createThread(actor: CommentActor, input: NewThread): Promise<CloudCommentThread> {\n const userId = requireCommenter(actor)\n const threadId = input.id ?? crypto.randomUUID()\n const thread = await database.transaction().execute(async (transaction) => {\n // One writer at a time per document, so the count below holds until the insert.\n await lockDocument(transaction, actor.documentId)\n const existing = await transaction\n .selectFrom('commentThread')\n .select(['documentId', 'createdBy'])\n .where('id', '=', threadId)\n .executeTakeFirst()\n if (existing) {\n // The same request again, its answer lost on the way: the thread it made.\n if (existing.documentId !== actor.documentId || existing.createdBy !== userId) {\n throw new CommentConflictError()\n }\n return readThread(\n transaction,\n await findThread(transaction, actor.documentId, threadId),\n actor.userId\n )\n }\n if (\n (await documentThreadCount(transaction, actor.documentId)) >=\n MAX_COMMENT_THREADS_PER_DOCUMENT\n ) {\n throw new CommentLimitError()\n }\n const now = new Date()\n await transaction\n .insertInto('commentThread')\n .values({\n id: threadId,\n documentId: actor.documentId,\n ...anchorValues(input),\n createdBy: userId,\n createdAt: now,\n updatedAt: now\n })\n .execute()\n const commentId = crypto.randomUUID()\n await transaction\n .insertInto('comment')\n .values({\n id: commentId,\n threadId,\n authorId: userId,\n agent: input.agent ?? null,\n body: input.body,\n createdAt: now\n })\n .execute()\n await markRead(transaction, userId, threadId)\n await tell(\n transaction,\n actor,\n { commentId, threadId, body: input.body },\n input.mentions ?? []\n )\n return readThread(\n transaction,\n await findThread(transaction, actor.documentId, threadId),\n actor.userId\n )\n })\n announce(actor.documentId, threadId)\n return thread\n },\n\n /**\n * Brings in the threads a file held as it moved to Cloud, for someone who may edit it. Their\n * authors stay the names the file gave; the importer may move and resolve them as a starter.\n */\n async importThreads(\n actor: CommentActor,\n input: ImportCommentThreadsInput\n ): Promise<CommentThreads> {\n const userId = requireCommenter(actor)\n if (!actor.canModerate) throw new DocumentForbiddenError()\n const ids: string[] = []\n if (input.threads.length > 0) {\n await database.transaction().execute(async (transaction) => {\n await lockDocument(transaction, actor.documentId)\n const held = await documentThreadCount(transaction, actor.documentId)\n if (held + input.threads.length > MAX_COMMENT_THREADS_PER_DOCUMENT) {\n throw new CommentLimitError()\n }\n const now = new Date()\n const rows = input.threads.map((thread) => ({\n thread,\n id: crypto.randomUUID(),\n createdAt: new Date(thread.createdAt)\n }))\n const threadRows = rows.map(({ thread, id, createdAt }) => ({\n id,\n documentId: actor.documentId,\n ...anchorValues(thread),\n createdBy: userId,\n createdAt,\n updatedAt: now,\n resolvedAt: thread.resolved ? now : null,\n resolvedBy: thread.resolved ? userId : null\n }))\n for (const batch of chunk(threadRows, INSERT_BATCH)) {\n await transaction.insertInto('commentThread').values(batch).execute()\n }\n const imported = rows.flatMap(({ thread, id }) =>\n importedTimes(thread.comments.map((comment) => comment.createdAt)).map(\n (createdAt, index) => ({\n id: crypto.randomUUID(),\n threadId: id,\n authorId: null,\n importedAuthorName: thread.comments[index]?.authorName ?? '',\n body: thread.comments[index]?.body ?? '',\n createdAt\n })\n )\n )\n // A statement takes so many parameters; a big file's comments go in a few.\n for (const batch of chunk(imported, INSERT_BATCH)) {\n await transaction.insertInto('comment').values(batch).execute()\n }\n // The importer has read what they brought.\n for (const { id } of rows) {\n await markRead(transaction, userId, id)\n ids.push(id)\n }\n })\n }\n for (const id of ids) announce(actor.documentId, id)\n return list(actor)\n },\n\n async updateThread(\n actor: CommentActor,\n threadId: string,\n input: UpdateCommentThreadInput\n ): Promise<CloudCommentThread> {\n const userId = requireCommenter(actor)\n const thread = await database.transaction().execute(async (transaction) => {\n const row = await findThread(transaction, actor.documentId, threadId, true)\n if (input.anchor && row.createdBy !== userId && !actor.canModerate) {\n throw new DocumentForbiddenError()\n }\n const changes = {\n ...(input.anchor ? anchorValues(input.anchor) : {}),\n ...resolutionChange(input.resolved, row.resolvedAt !== null, userId)\n }\n // Resolving what is already resolved, and nothing else, changes nothing.\n if (isEmptyObject(changes)) return readThread(transaction, row, actor.userId)\n await transaction\n .updateTable('commentThread')\n .set(changes)\n .where('id', '=', threadId)\n .execute()\n return touched(transaction, actor, threadId)\n })\n announce(actor.documentId, threadId)\n return thread\n },\n\n async deleteThread(actor: CommentActor, threadId: string): Promise<void> {\n const userId = requireCommenter(actor)\n await database.transaction().execute(async (transaction) => {\n const row = await findThread(transaction, actor.documentId, threadId, true)\n if (row.createdBy !== userId && !actor.canModerate) throw new DocumentForbiddenError()\n await transaction.deleteFrom('commentThread').where('id', '=', threadId).execute()\n })\n announce(actor.documentId, threadId)\n },\n\n async reply(\n actor: CommentActor,\n threadId: string,\n input: NewComment\n ): Promise<CloudCommentThread> {\n const userId = requireCommenter(actor)\n const commentId = input.id ?? crypto.randomUUID()\n const thread = await database.transaction().execute(async (transaction) => {\n await findThread(transaction, actor.documentId, threadId, true)\n const existing = await transaction\n .selectFrom('comment')\n .select(['threadId', 'authorId'])\n .where('id', '=', commentId)\n .executeTakeFirst()\n if (existing) {\n if (existing.threadId !== threadId || existing.authorId !== userId) {\n throw new CommentConflictError()\n }\n return readThread(\n transaction,\n await findThread(transaction, actor.documentId, threadId),\n actor.userId\n )\n }\n const { count } = await transaction\n .selectFrom('comment')\n .select((expression) => expression.fn.countAll<string>().as('count'))\n .where('threadId', '=', threadId)\n .executeTakeFirstOrThrow()\n if (Number(count) >= MAX_COMMENTS_PER_THREAD) throw new CommentLimitError()\n await transaction\n .insertInto('comment')\n .values({\n id: commentId,\n threadId,\n authorId: userId,\n agent: input.agent ?? null,\n body: input.body\n })\n .execute()\n await tell(\n transaction,\n actor,\n { commentId, threadId, body: input.body },\n input.mentions ?? [],\n {\n reply: true\n }\n )\n return touched(transaction, actor, threadId)\n })\n announce(actor.documentId, threadId)\n return thread\n },\n\n /** Changes what a comment says; only its author may, so no one puts words in another's mouth. */\n async updateComment(\n actor: CommentActor,\n threadId: string,\n commentId: string,\n input: CommentEdit\n ): Promise<CloudCommentThread> {\n const userId = requireCommenter(actor)\n const thread = await database.transaction().execute(async (transaction) => {\n const comment = await lockedComment(transaction, actor, threadId, commentId)\n if (comment.authorId !== userId) throw new DocumentForbiddenError()\n await transaction\n .updateTable('comment')\n .set({ body: input.body, editedAt: new Date() })\n .where('id', '=', commentId)\n .execute()\n // An edit tells only the people it names that it did not before.\n await tell(\n transaction,\n actor,\n { commentId, threadId, body: input.body },\n input.mentions ?? []\n )\n return touched(transaction, actor, threadId)\n })\n announce(actor.documentId, threadId)\n return thread\n },\n\n /** Deletes a comment for good; the thread goes with its first one. Null once it is gone. */\n async deleteComment(\n actor: CommentActor,\n threadId: string,\n commentId: string\n ): Promise<CloudCommentThread | null> {\n const userId = requireCommenter(actor)\n const thread = await database.transaction().execute(async (transaction) => {\n const comment = await lockedComment(transaction, actor, threadId, commentId)\n if (comment.authorId !== userId && !actor.canModerate) throw new DocumentForbiddenError()\n if (comment.first) {\n await transaction.deleteFrom('commentThread').where('id', '=', threadId).execute()\n return null\n }\n await transaction.deleteFrom('comment').where('id', '=', commentId).execute()\n return touched(transaction, actor, threadId)\n })\n announce(actor.documentId, threadId)\n return thread\n }\n }\n}\n\nexport type CommentService = ReturnType<typeof createCommentService>\n","import {\n createCommentSchema,\n createCommentThreadSchema,\n importCommentThreadsSchema,\n notificationSettingsSchema,\n sharedCommentsRequestSchema,\n sharedCreateCommentSchema,\n sharedCreateCommentThreadSchema,\n sharedUpdateCommentSchema,\n sharedUpdateCommentThreadSchema,\n updateCommentSchema,\n updateCommentThreadSchema,\n type SharedCommentsRequest\n} from '#cloud/contract'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents'\nimport { shareActor } from '#cloud/server/sharing/actor'\nimport { sharingDomainError } from '#cloud/server/sharing/http'\nimport {\n documentCommentParams,\n documentParams,\n documentThreadParams,\n shareCommentParams,\n shareParams,\n shareThreadParams,\n validatedJSON\n} from '#cloud/server/validation'\nimport { omit } from 'es-toolkit'\nimport { Hono, type Context } from 'hono'\nimport type { BlankEnv } from 'hono/types'\nimport type * as v from 'valibot'\n\nimport {\n CommentConflictError,\n CommentLimitError,\n type CommentActor,\n type CommentService\n} from './service'\n\nfunction commentDomainError(context: Context, error: unknown): Response | null {\n if (error instanceof CommentLimitError) {\n return context.json({ error: { code: 'comment_limit_reached' as const } }, 409)\n }\n if (error instanceof CommentConflictError) {\n return context.json({ error: { code: 'comment_conflict' as const } }, 409)\n }\n return null\n}\n\nasync function answer(\n context: Context,\n run: () => Promise<Response>,\n domainError: (context: Context, error: unknown) => Response | null\n): Promise<Response> {\n try {\n return await run()\n } catch (error) {\n const response = commentDomainError(context, error) ?? domainError(context, error)\n if (response) return response\n throw error\n }\n}\n\n/** Answers a thread, or no content when deleting its comment deleted the thread. */\nfunction threadOrGone(context: Context, thread: Awaited<ReturnType<CommentService['get']>> | null) {\n return thread ? context.json({ thread }) : context.body(null, 204)\n}\n\n/** A route's context once its share, thread, and request body, read by `Schema`, are validated. */\ntype SharedThreadContext<Schema extends v.GenericSchema> = Context<\n BlankEnv,\n string,\n {\n in: { param: { shareId: string; threadId: string }; json: v.InferInput<Schema> }\n out: { param: { shareId: string; threadId: string }; json: v.InferOutput<Schema> }\n }\n>\n\n/** A document's comments for its members and the people it is shared with directly. */\nexport function createCommentRoutes(service: CommentService) {\n const as = (context: Context<DocumentRouteEnvironment>, documentId: string) =>\n service.forMember(context.get('actor').userId, documentId)\n const run = (context: Context<DocumentRouteEnvironment>, respond: () => Promise<Response>) =>\n answer(context, respond, documentDomainError)\n\n return new Hono<DocumentRouteEnvironment>()\n .get('/account/notifications', async (context) =>\n context.json(await service.notificationSettings(context.get('actor').userId))\n )\n .put('/account/notifications', validatedJSON(notificationSettingsSchema), async (context) =>\n context.json(\n await service.setNotificationSettings(\n context.get('actor').userId,\n context.req.valid('json')\n )\n )\n )\n .get('/documents/:documentId/threads/people', documentParams, (context) =>\n run(context, async () =>\n context.json(await service.people(await as(context, context.req.valid('param').documentId)))\n )\n )\n .get('/documents/:documentId/threads', documentParams, (context) =>\n run(context, async () =>\n context.json(await service.list(await as(context, context.req.valid('param').documentId)))\n )\n )\n .post(\n '/documents/:documentId/threads',\n documentParams,\n validatedJSON(createCommentThreadSchema),\n (context) =>\n run(context, async () => {\n const actor = await as(context, context.req.valid('param').documentId)\n const thread = await service.createThread(actor, context.req.valid('json'))\n return context.json({ thread }, 201)\n })\n )\n .post(\n '/documents/:documentId/threads/import',\n documentParams,\n validatedJSON(importCommentThreadsSchema),\n (context) =>\n run(context, async () => {\n const actor = await as(context, context.req.valid('param').documentId)\n return context.json(await service.importThreads(actor, context.req.valid('json')), 201)\n })\n )\n .get('/documents/:documentId/threads/:threadId', documentThreadParams, (context) =>\n run(context, async () => {\n const { documentId, threadId } = context.req.valid('param')\n return context.json({ thread: await service.get(await as(context, documentId), threadId) })\n })\n )\n .post('/documents/:documentId/threads/:threadId/read', documentThreadParams, (context) =>\n run(context, async () => {\n const { documentId, threadId } = context.req.valid('param')\n await service.markRead(await as(context, documentId), threadId)\n return context.body(null, 204)\n })\n )\n .patch(\n '/documents/:documentId/threads/:threadId',\n documentThreadParams,\n validatedJSON(updateCommentThreadSchema),\n (context) =>\n run(context, async () => {\n const { documentId, threadId } = context.req.valid('param')\n const actor = await as(context, documentId)\n return context.json({\n thread: await service.updateThread(actor, threadId, context.req.valid('json'))\n })\n })\n )\n .delete('/documents/:documentId/threads/:threadId', documentThreadParams, (context) =>\n run(context, async () => {\n const { documentId, threadId } = context.req.valid('param')\n await service.deleteThread(await as(context, documentId), threadId)\n return context.body(null, 204)\n })\n )\n .post(\n '/documents/:documentId/threads/:threadId/comments',\n documentThreadParams,\n validatedJSON(createCommentSchema),\n (context) =>\n run(context, async () => {\n const { documentId, threadId } = context.req.valid('param')\n const actor = await as(context, documentId)\n const thread = await service.reply(actor, threadId, context.req.valid('json'))\n return context.json({ thread }, 201)\n })\n )\n .patch(\n '/documents/:documentId/threads/:threadId/comments/:commentId',\n documentCommentParams,\n validatedJSON(updateCommentSchema),\n (context) =>\n run(context, async () => {\n const { documentId, threadId, commentId } = context.req.valid('param')\n const actor = await as(context, documentId)\n return context.json({\n thread: await service.updateComment(\n actor,\n threadId,\n commentId,\n context.req.valid('json')\n )\n })\n })\n )\n .delete(\n '/documents/:documentId/threads/:threadId/comments/:commentId',\n documentCommentParams,\n (context) =>\n run(context, async () => {\n const { documentId, threadId, commentId } = context.req.valid('param')\n const actor = await as(context, documentId)\n return threadOrGone(context, await service.deleteComment(actor, threadId, commentId))\n })\n )\n}\n\n/**\n * The same comments through a share link, whose secret every request carries in its body.\n * Guests read; people signed in to the server also write. Reads are POSTs for the same reason.\n */\nexport function createSharedCommentRoutes(\n service: CommentService,\n resolveSession?: CloudSessionResolver\n) {\n /** Answers for whoever follows the link, with the secret the request's body carries. */\n async function shared(\n context: Context,\n shareId: string,\n { share }: SharedCommentsRequest,\n respond: (actor: CommentActor) => Promise<Response>\n ): Promise<Response> {\n return answer(\n context,\n async () =>\n respond(\n await service.forShare(\n shareId,\n share.secret,\n await shareActor(context.req.raw, resolveSession)\n )\n ),\n sharingDomainError\n )\n }\n\n /** A route that acts on a shared thread for whoever opened the share, answering with no content. */\n function sharedThreadAction(act: (actor: CommentActor, threadId: string) => Promise<void>) {\n return (context: SharedThreadContext<typeof sharedCommentsRequestSchema>) => {\n const { shareId, threadId } = context.req.valid('param')\n return shared(context, shareId, context.req.valid('json'), async (actor) => {\n await act(actor, threadId)\n return context.body(null, 204)\n })\n }\n }\n\n /**\n * A route that changes a shared thread with the edit its request carries, for whoever opened the\n * share, answering with the thread.\n */\n function sharedThreadChange<Schema extends v.GenericSchema<unknown, SharedCommentsRequest>>(\n change: (\n actor: CommentActor,\n threadId: string,\n edit: Omit<v.InferOutput<Schema>, 'share'>\n ) => Promise<unknown>,\n status: 200 | 201 = 200\n ) {\n return (context: SharedThreadContext<Schema>) => {\n const { shareId, threadId } = context.req.valid('param')\n const request = context.req.valid('json')\n return shared(context, shareId, request, async (actor) =>\n context.json({ thread: await change(actor, threadId, omit(request, ['share'])) }, status)\n )\n }\n }\n\n return new Hono()\n .post(\n '/shares/:shareId/threads/list',\n shareParams,\n validatedJSON(sharedCommentsRequestSchema),\n (context) =>\n shared(\n context,\n context.req.valid('param').shareId,\n context.req.valid('json'),\n async (actor) => context.json(await service.list(actor))\n )\n )\n .post(\n '/shares/:shareId/threads',\n shareParams,\n validatedJSON(sharedCreateCommentThreadSchema),\n (context) => {\n const { share, ...input } = context.req.valid('json')\n return shared(context, context.req.valid('param').shareId, { share }, async (actor) =>\n context.json({ thread: await service.createThread(actor, input) }, 201)\n )\n }\n )\n .post(\n '/shares/:shareId/threads/:threadId/get',\n shareThreadParams,\n validatedJSON(sharedCommentsRequestSchema),\n (context) => {\n const { shareId, threadId } = context.req.valid('param')\n return shared(context, shareId, context.req.valid('json'), async (actor) =>\n context.json({ thread: await service.get(actor, threadId) })\n )\n }\n )\n .post(\n '/shares/:shareId/threads/:threadId/read',\n shareThreadParams,\n validatedJSON(sharedCommentsRequestSchema),\n sharedThreadAction((actor, threadId) => service.markRead(actor, threadId))\n )\n .patch(\n '/shares/:shareId/threads/:threadId',\n shareThreadParams,\n validatedJSON(sharedUpdateCommentThreadSchema),\n sharedThreadChange<typeof sharedUpdateCommentThreadSchema>((actor, threadId, edit) =>\n service.updateThread(actor, threadId, edit)\n )\n )\n .delete(\n '/shares/:shareId/threads/:threadId',\n shareThreadParams,\n validatedJSON(sharedCommentsRequestSchema),\n sharedThreadAction((actor, threadId) => service.deleteThread(actor, threadId))\n )\n .post(\n '/shares/:shareId/threads/:threadId/comments',\n shareThreadParams,\n validatedJSON(sharedCreateCommentSchema),\n sharedThreadChange<typeof sharedCreateCommentSchema>(\n (actor, threadId, comment) => service.reply(actor, threadId, comment),\n 201\n )\n )\n .patch(\n '/shares/:shareId/threads/:threadId/comments/:commentId',\n shareCommentParams,\n validatedJSON(sharedUpdateCommentSchema),\n (context) => {\n const { shareId, threadId, commentId } = context.req.valid('param')\n const { share, ...input } = context.req.valid('json')\n return shared(context, shareId, { share }, async (actor) =>\n context.json({ thread: await service.updateComment(actor, threadId, commentId, input) })\n )\n }\n )\n .delete(\n '/shares/:shareId/threads/:threadId/comments/:commentId',\n shareCommentParams,\n validatedJSON(sharedCommentsRequestSchema),\n (context) => {\n const { shareId, threadId, commentId } = context.req.valid('param')\n return shared(context, shareId, context.req.valid('json'), async (actor) =>\n threadOrGone(context, await service.deleteComment(actor, threadId, commentId))\n )\n }\n )\n}\n","import {\n COMMUNITY_THUMBNAIL_PATH,\n communityDownloadQuerySchema,\n requestImageLinksSchema\n} from '#cloud/contract'\nimport { documentDomainError } from '#cloud/server/documents'\nimport {\n documentRevisionParams,\n documentParams,\n validatedJSON,\n validatedQuery\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\n\nimport type { CommunityService } from './service'\n\nconst notFound = (context: Context) => context.json({ error: { code: 'not_found' as const } }, 404)\n\n/** Answers a missing or hidden gallery document as not found, like any document outside it. */\nasync function communityRoute(context: Context, action: () => Promise<Response>) {\n try {\n return await action()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\n/**\n * The community gallery's data for anyone, signed in or not: the list, a document or one of its\n * named versions to open read-only, and the links of its images. A deployment without a gallery\n * answers not found.\n */\nexport function createCommunityRoutes(community: CommunityService) {\n return new Hono()\n .get('/community', async (context) => {\n if (!community.enabled) return notFound(context)\n // The gallery changes on a publish; a few minutes' copy spares the database repeat visits.\n context.header('Cache-Control', 'public, max-age=300')\n return context.json({ documents: await community.list() })\n })\n .get(\n '/community/:documentId/document',\n documentParams,\n validatedQuery(communityDownloadQuerySchema),\n (context) =>\n communityRoute(context, async () => {\n const { documentId } = context.req.valid('param')\n return context.json(\n await community.download(documentId, context.req.valid('query').version)\n )\n })\n )\n .post(\n '/community/:documentId/images',\n documentParams,\n validatedJSON(requestImageLinksSchema),\n (context) =>\n communityRoute(context, async () =>\n context.json(\n await community.imageLinks(\n context.req.valid('param').documentId,\n context.req.valid('json').checksums\n )\n )\n )\n )\n}\n\n/**\n * Gallery thumbnails, for pages and apps on any origin. Each address names the revision it shows,\n * so a copy never goes stale, but it is cached only as long as the listing is: a document taken\n * down or out of the gallery stops showing everywhere within minutes.\n */\nexport function createCommunityThumbnailRoutes(community: CommunityService) {\n return new Hono().get(\n `${COMMUNITY_THUMBNAIL_PATH}/:documentId/:revisionId`,\n documentRevisionParams,\n (context) =>\n communityRoute(context, async () => {\n const { documentId, revisionId } = context.req.valid('param')\n const thumbnail = await community.thumbnail(documentId, revisionId)\n if (!thumbnail) return notFound(context)\n context.header('Cache-Control', 'public, max-age=300')\n context.header('Content-Type', 'image/png')\n context.header('X-Content-Type-Options', 'nosniff')\n context.header('Content-Security-Policy', \"default-src 'none'; sandbox\")\n context.header('Cross-Origin-Resource-Policy', 'cross-origin')\n return context.body(new Uint8Array(thumbnail))\n })\n )\n}\n","import {\n communityThumbnailPath,\n type CommunityDocument,\n type CommunityDownload,\n type CommunityVersion,\n type DocumentVersion\n} from '#cloud/contract'\nimport { isBannedNow, userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError, type DocumentService } from '#cloud/server/documents'\nimport type { DocumentVersionService } from '#cloud/server/documents/versions'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { Kysely } from 'kysely'\n\nimport { extractFigThumbnailFromReader } from '@open-pencil/fig'\n\nconst communityVersion = (version: DocumentVersion): CommunityVersion => ({\n id: version.id,\n name: version.name ?? '',\n description: version.description || null,\n createdAt: version.createdAt,\n current: version.current\n})\n\n/**\n * The deployment's community gallery: the documents of the workspace its config names, which\n * anyone may open read-only without signing in or a link. Nothing marks a document as published;\n * saving it to the workspace publishes it and moving it out takes it down. A document the\n * workspace's members could not open either — deleted, taken down by an administrator, never\n * saved, or made by a banned account — is not in the gallery.\n */\nexport function createCommunityService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n documents: Pick<DocumentService, 'downloadShared' | 'imageLinksShared'>,\n versions: Pick<DocumentVersionService, 'namedSharedIn' | 'downloadNamedShared'>,\n workspaceId: string | null\n) {\n function published() {\n return database\n .selectFrom('document')\n .innerJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'document.id',\n 'document.name',\n 'document.kind',\n 'document.updatedAt',\n 'document.currentRevisionId as revisionId',\n 'storageObject.objectKey',\n 'storageObject.byteSize'\n ])\n .where('document.workspaceId', '=', workspaceId ?? '')\n .where('document.deletedAt', 'is', null)\n .where('document.disabledAt', 'is', null)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('user')\n .select('user.id')\n .whereRef(userIdText, '=', 'document.createdBy')\n .where(isBannedNow)\n )\n )\n )\n }\n\n /** A document of the gallery, or not found for any other, so nothing outside it shows. */\n async function find(documentId: string) {\n if (!workspaceId) throw new DocumentNotFoundError()\n const row = await published().where('document.id', '=', documentId).executeTakeFirst()\n if (!row?.revisionId) throw new DocumentNotFoundError()\n return { ...row, revisionId: row.revisionId }\n }\n\n return {\n /** Whether the deployment has a gallery at all. */\n enabled: workspaceId !== null,\n\n /** The gallery's documents, most recently changed first, each with its named versions. */\n async list(): Promise<CommunityDocument[]> {\n if (!workspaceId) return []\n const rows = (await published().orderBy('document.updatedAt', 'desc').execute()).flatMap(\n ({ revisionId, ...row }) => (revisionId ? [{ ...row, revisionId }] : [])\n )\n const named = await versions.namedSharedIn(\n workspaceId,\n rows.map((row) => ({ id: row.id, currentRevisionId: row.revisionId }))\n )\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n kind: row.kind,\n updatedAt: new Date(row.updatedAt).toISOString(),\n revisionId: row.revisionId,\n thumbnailPath: communityThumbnailPath(row.id, row.revisionId),\n versions: (named.get(row.id) ?? []).map(communityVersion)\n }))\n },\n\n /** A gallery document as it is now, or one of its named versions, with where to download it. */\n async download(documentId: string, versionId?: string): Promise<CommunityDownload> {\n await find(documentId)\n if (!versionId) return { document: await documents.downloadShared(documentId), version: null }\n const named = await versions.downloadNamedShared(documentId, versionId)\n return { document: named.document, version: communityVersion(named.version) }\n },\n\n /** Links for the images a gallery document's live room names. */\n async imageLinks(documentId: string, checksums: string[]) {\n await find(documentId)\n return documents.imageLinksShared(documentId, checksums)\n },\n\n /**\n * The thumbnail a gallery document's stored file carries, read from storage in ranges, for\n * the revision it is now; null when that revision is not current any more or has none.\n */\n async thumbnail(documentId: string, revisionId: string): Promise<Uint8Array | null> {\n const row = await find(documentId)\n if (row.revisionId !== revisionId) return null\n return extractFigThumbnailFromReader({\n size: Number(row.byteSize),\n read: async (start, endExclusive) => {\n const bytes = await objects.readRange(row.objectKey, start, endExclusive)\n if (!bytes) throw new DocumentNotFoundError()\n return bytes\n }\n })\n }\n }\n}\n\nexport type CommunityService = ReturnType<typeof createCommunityService>\n","import {\n duplicateDocumentVersionSchema,\n saveDocumentVersionSchema,\n updateDocumentVersionSchema\n} from '#cloud/contract'\nimport { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents/routes'\nimport {\n documentParams,\n documentVersionParams,\n validatedJSON,\n validatedQuery\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport * as v from 'valibot'\n\nimport type { DocumentVersionService } from './service'\n\nconst pageSchema = v.object({\n before: v.optional(v.pipe(v.string(), v.uuid())),\n limit: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)))\n})\n\nasync function answer(context: Context, run: () => Promise<Response>): Promise<Response> {\n try {\n return await run()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\n/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */\nexport function createDocumentVersionRoutes(service: DocumentVersionService) {\n return new Hono<DocumentRouteEnvironment>()\n .get('/documents/:documentId/versions', documentParams, validatedQuery(pageSchema), (context) =>\n answer(context, async () =>\n context.json(\n await service.list(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('query')\n )\n )\n )\n )\n .post(\n '/documents/:documentId/versions',\n documentParams,\n validatedJSON(saveDocumentVersionSchema),\n (context) =>\n answer(context, async () =>\n context.json(\n {\n version: await service.save(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/versions/:versionId',\n documentVersionParams,\n validatedJSON(updateDocumentVersionSchema),\n (context) =>\n answer(context, async () =>\n context.json({\n version: await service.update(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId,\n context.req.valid('json')\n )\n })\n )\n )\n .get('/documents/:documentId/versions/:versionId', documentVersionParams, (context) =>\n answer(context, async () =>\n context.json(\n await service.download(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId\n )\n )\n )\n )\n .post('/documents/:documentId/versions/:versionId/restore', documentVersionParams, (context) =>\n answer(context, async () =>\n context.json(\n await service.restore(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId\n )\n )\n )\n )\n .post(\n '/documents/:documentId/versions/:versionId/duplicate',\n documentVersionParams,\n validatedJSON(duplicateDocumentVersionSchema),\n (context) =>\n answer(context, async () =>\n context.json(\n {\n document: await service.duplicate(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId,\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n}\n","import type {\n DocumentVersionDownload,\n DocumentSummary,\n DocumentVersion,\n DocumentVersions,\n DuplicateDocumentVersionInput,\n SaveDocumentVersionInput,\n UpdateDocumentVersionInput\n} from '#cloud/contract'\nimport { workspaceRoleCan } from '#cloud/server/auth/access-control'\nimport { userIdText, type CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport {\n copyRevisionImages,\n DOWNLOAD_LIFETIME_MS,\n revisionImageDownloads\n} from '#cloud/server/documents/images'\nimport { findDocument, insertDocument, workspaceRole } from '#cloud/server/documents/repository'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport { logCloud, loggedError } from '#cloud/server/logging'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { announceVersions, keepRevision } from './checkpoint'\nimport { historyStart } from './history'\n\nconst DEFAULT_PAGE_SIZE = 50\nconst MAXIMUM_PAGE_SIZE = 100\n\ntype VersionRow = {\n id: string\n revisionId: string\n kind: 'checkpoint' | 'named'\n name: string | null\n description: string | null\n createdAt: Date\n createdBy: string\n createdByName: string | null\n restoredFromVersionId: string | null\n}\n\nfunction versionOf(row: VersionRow, currentRevisionId: string | null): DocumentVersion {\n return {\n id: row.id,\n revisionId: row.revisionId,\n kind: row.kind,\n name: row.name,\n description: row.description,\n createdAt: row.createdAt.toISOString(),\n createdBy: { id: row.createdBy, name: row.createdByName },\n restoredFromVersionId: row.restoredFromVersionId,\n current: row.revisionId === currentRevisionId\n }\n}\n\n/**\n * A document's version history: its checkpoints and named versions, newest first, and what can be\n * done with one. Anyone who can open the document sees its history; editors name and restore.\n */\nexport function createDocumentVersionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: {\n policy?: CloudPolicy\n deploymentMode?: CloudPolicyContext['deploymentMode']\n /** Called once a restore lands, so the document's live room starts over. */\n onRestored?: (documentId: string) => void\n /** Called once the history changes: a version named, renamed, or turned back into an autosave. */\n onVersionsChanged?: (documentId: string) => void\n } = {}\n) {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n function versions() {\n return database\n .selectFrom('documentVersion')\n .leftJoin('user', (join) => join.onRef(userIdText, '=', 'documentVersion.createdBy'))\n .select([\n 'documentVersion.id',\n 'documentVersion.revisionId',\n 'documentVersion.kind',\n 'documentVersion.name',\n 'documentVersion.description',\n 'documentVersion.createdAt',\n 'documentVersion.createdBy',\n 'user.name as createdByName',\n 'documentVersion.restoredFromVersionId'\n ])\n }\n\n /** The document the person may see the history of, and where that history starts. */\n async function openHistory(userId: string, documentId: string, edit: boolean) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (edit && !canEditDocument(access)) throw new DocumentForbiddenError()\n const document = await getDocumentSummaryRow(database, documentId)\n if (!document) throw new DocumentNotFoundError()\n return {\n document,\n start: await historyStart(\n database,\n options.policy,\n deploymentMode,\n document.workspaceId,\n new Date()\n )\n }\n }\n\n async function findVersion(documentId: string, versionId: string, start: Date | null) {\n let query = versions()\n .where('documentVersion.documentId', '=', documentId)\n .where('documentVersion.id', '=', versionId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n const row = await query.executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n /** The stored file of a revision; read under the document's lock before reusing it. */\n async function storedRevision(\n source: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n revisionId: string\n ) {\n const stored = await source\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.storageObjectId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', revisionId)\n .executeTakeFirst()\n if (!stored) throw new DocumentNotFoundError()\n return stored\n }\n\n /** A document's history for a caller that already let the reader in, and where it starts. */\n async function sharedHistory(documentId: string) {\n const document = await getDocumentSummaryRow(database, documentId)\n if (!document) throw new DocumentNotFoundError()\n const start = await historyStart(\n database,\n options.policy,\n deploymentMode,\n document.workspaceId,\n new Date()\n )\n return { document, start }\n }\n\n /** A version's stored file, with where to download it and the images it names. */\n async function downloadVersion(\n document: Awaited<ReturnType<typeof sharedHistory>>['document'],\n version: VersionRow\n ): Promise<DocumentVersionDownload> {\n const stored = await storedRevision(database, version.revisionId)\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document: {\n document: documentSummary(document),\n revisionId: version.revisionId,\n byteSize: Number(stored.byteSize),\n checksum: stored.checksum,\n contentType: stored.contentType,\n download: await objects.createDownload({ key: stored.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, version.revisionId, expiresAt)\n },\n version: versionOf(version, document.currentRevisionId)\n }\n }\n\n return {\n async list(\n userId: string,\n documentId: string,\n page: { before?: string; limit?: number } = {}\n ): Promise<DocumentVersions> {\n const { document, start } = await openHistory(userId, documentId, false)\n const limit = Math.min(Math.max(page.limit ?? DEFAULT_PAGE_SIZE, 1), MAXIMUM_PAGE_SIZE)\n let query = versions().where('documentVersion.documentId', '=', documentId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n if (page.before) {\n const cursor = await findVersion(documentId, page.before, start)\n query = query.where((expression) =>\n expression.or([\n expression('documentVersion.createdAt', '<', cursor.createdAt),\n expression.and([\n expression('documentVersion.createdAt', '=', cursor.createdAt),\n expression('documentVersion.id', '<', cursor.id)\n ])\n ])\n )\n }\n const rows = await query\n .orderBy('documentVersion.createdAt', 'desc')\n .orderBy('documentVersion.id', 'desc')\n .limit(limit + 1)\n .execute()\n const shown = rows.slice(0, limit)\n return {\n versions: shown.map((row) => versionOf(row, document.currentRevisionId)),\n nextCursor: rows.length > limit ? (shown.at(-1)?.id ?? null) : null\n }\n },\n\n /** Names the document as it is now, as Save to version history does. */\n async save(\n userId: string,\n documentId: string,\n input: SaveDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document } = await openHistory(userId, documentId, true)\n const revisionId = document.currentRevisionId\n if (!revisionId) throw new DocumentNotFoundError()\n const description = input.description || null\n await database\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId,\n revisionId,\n kind: 'named',\n name: input.name,\n description,\n createdBy: userId,\n restoredFromVersionId: null\n })\n .onConflict((conflict) =>\n conflict\n .column('revisionId')\n .doUpdateSet({ kind: 'named', name: input.name, description })\n )\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n const row = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return versionOf(row, revisionId)\n },\n\n /** Names a version, renames it, or with a null name deletes its info so it is a checkpoint. */\n async update(\n userId: string,\n documentId: string,\n versionId: string,\n input: UpdateDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document, start } = await openHistory(userId, documentId, true)\n await findVersion(documentId, versionId, start)\n await database\n .updateTable('documentVersion')\n .set(\n input.name\n ? { kind: 'named', name: input.name, description: input.description || null }\n : { kind: 'checkpoint', name: null, description: null }\n )\n .where('id', '=', versionId)\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n return versionOf(await findVersion(documentId, versionId, start), document.currentRevisionId)\n },\n\n async download(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<DocumentVersionDownload> {\n const { document, start } = await openHistory(userId, documentId, false)\n return downloadVersion(document, await findVersion(documentId, versionId, start))\n },\n\n /**\n * The named versions of several documents of one workspace, newest first, each list keyed by\n * its document, for a caller that already let the reader in, such as the community gallery;\n * the workspace's history limit still applies, and one query reads them all.\n */\n async namedSharedIn(\n workspaceId: string,\n documents: { id: string; currentRevisionId: string | null }[]\n ): Promise<Map<string, DocumentVersion[]>> {\n const named = new Map(documents.map((document) => [document.id, [] as DocumentVersion[]]))\n if (documents.length === 0) return named\n const start = await historyStart(\n database,\n options.policy,\n deploymentMode,\n workspaceId,\n new Date()\n )\n let query = versions()\n .select('documentVersion.documentId')\n .where('documentVersion.documentId', 'in', [...named.keys()])\n .where('documentVersion.kind', '=', 'named')\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n const rows = await query.orderBy('documentVersion.createdAt', 'desc').execute()\n const current = new Map(\n documents.map((document) => [document.id, document.currentRevisionId])\n )\n for (const row of rows) {\n named.get(row.documentId)?.push(versionOf(row, current.get(row.documentId) ?? null))\n }\n return named\n },\n\n /** A named version with where to download it, for a caller that already let the reader in. */\n async downloadNamedShared(\n documentId: string,\n versionId: string\n ): Promise<DocumentVersionDownload> {\n const { document, start } = await sharedHistory(documentId)\n const version = await findVersion(documentId, versionId, start)\n if (version.kind !== 'named') throw new DocumentNotFoundError()\n return downloadVersion(document, version)\n },\n\n /**\n * Makes a version the document's current state without losing anything: the state it replaces\n * is kept as a checkpoint, the restored state becomes a new revision of the same stored file,\n * and the document's live room starts over so everyone has the restored version.\n */\n async restore(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<{ document: DocumentSummary; version: DocumentVersion }> {\n const { start } = await openHistory(userId, documentId, true)\n const version = await findVersion(documentId, versionId, start)\n const revisionId = crypto.randomUUID()\n const now = new Date()\n await database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select(['currentRevisionId', 'deletedAt'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!locked || locked.deletedAt) throw new DocumentNotFoundError()\n // Compaction locks the document too, so the version's file cannot go while it is reused.\n const stored = await storedRevision(transaction, version.revisionId)\n if (locked.currentRevisionId) {\n const current = await transaction\n .selectFrom('documentRevision')\n .select('createdBy')\n .where('id', '=', locked.currentRevisionId)\n .executeTakeFirstOrThrow()\n await keepRevision(transaction, {\n documentId,\n revisionId: locked.currentRevisionId,\n createdBy: current.createdBy,\n createdAt: now\n })\n }\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId,\n parentRevisionId: locked.currentRevisionId,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1),\n collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1)\n })\n .where('id', '=', documentId)\n .execute()\n // The rooms of the replaced state never open again, so what the relay saved of them goes.\n await transaction\n .deleteFrom('documentRoomUpdate')\n .where('documentId', '=', documentId)\n .execute()\n await transaction\n .deleteFrom('documentRoomSnapshot')\n .where('documentId', '=', documentId)\n .execute()\n // A moment after the state it replaces, so the history lists it first.\n await keepRevision(transaction, {\n documentId,\n revisionId,\n createdBy: userId,\n createdAt: new Date(now.getTime() + 1),\n restoredFromVersionId: versionId\n })\n })\n // The restore stands whatever the hook does; a stale ticket is still turned away by its epoch.\n try {\n options.onRestored?.(documentId)\n } catch (error) {\n logCloud('error', 'Ending the rooms of a restored document failed', {\n error: loggedError(error)\n })\n }\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n const restored = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return { document, version: versionOf(restored, revisionId) }\n },\n\n /** Makes a new document in the same workspace from a version, sharing its stored file. */\n async duplicate(\n userId: string,\n documentId: string,\n versionId: string,\n input: DuplicateDocumentVersionInput\n ): Promise<DocumentSummary> {\n const { document, start } = await openHistory(userId, documentId, false)\n const role = await workspaceRole(database, userId, document.workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!workspaceRoleCan(role, { document: ['create'] })) throw new DocumentForbiddenError()\n const version = await findVersion(documentId, versionId, start)\n const copyId = crypto.randomUUID()\n const revisionId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n // Deleted-document cleanup removes files its document alone uses; holding the source\n // until the copy refers to the file means cleanup either finishes first or sees the copy.\n const source = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'cleanupClaimId'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!source || source.deletedAt || source.cleanupClaimId) throw new DocumentNotFoundError()\n const stored = await storedRevision(transaction, version.revisionId)\n await insertDocument(transaction, {\n id: copyId,\n workspaceId: document.workspaceId,\n name: input.name,\n kind: document.kind,\n createdBy: userId\n })\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: copyId,\n parentRevisionId: null,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: revisionId, version: 1 })\n .where('id', '=', copyId)\n .execute()\n await keepRevision(transaction, {\n documentId: copyId,\n revisionId,\n createdBy: userId,\n createdAt: new Date()\n })\n })\n const copy = await findDocument(database, userId, copyId)\n if (!copy) throw new DocumentNotFoundError()\n return copy\n }\n }\n}\n\nexport type DocumentVersionService = ReturnType<typeof createDocumentVersionService>\n","import type { CloudAPIEnvironment } from '#cloud/server/api/types'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport { createBillingRoutes, type BillingTokenService } from '#cloud/server/billing'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration'\nimport {\n createCollaborationRoutes,\n createPublicCollaborationRoutes\n} from '#cloud/server/collaboration'\nimport {\n createCommentRoutes,\n createSharedCommentRoutes,\n type CommentService\n} from '#cloud/server/comments'\nimport { createCommunityRoutes, type CommunityService } from '#cloud/server/community'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentService } from '#cloud/server/documents'\nimport { createDocumentRoutes, DocumentNotFoundError } from '#cloud/server/documents'\nimport {\n createDocumentVersionRoutes,\n type DocumentVersionService\n} from '#cloud/server/documents/versions'\nimport type { EntitlementService } from '#cloud/server/policy'\nimport { createPublicReportRoutes, type DocumentReportService } from '#cloud/server/reports'\nimport { createServicesRoutes, type ServicesTokenService } from '#cloud/server/services'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport {\n createDocumentSharingRoutes,\n createPublicDocumentRoutes,\n createPublicSharingRoutes\n} from '#cloud/server/sharing'\nimport { workspaceParams } from '#cloud/server/validation'\nimport type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'\nimport { createWorkspaceRoutes } from '#cloud/server/workspaces'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CloudAPIServices = {\n database?: Kysely<CloudDatabase>\n rateLimitSecret?: string\n collaboration: CollaborationTicketService\n documents: DocumentService\n versions: DocumentVersionService\n comments: CommentService\n /** The community gallery, which anyone may read. */\n community: CommunityService\n sharing: DocumentSharingService\n /** Reports about documents shared by link. */\n reports: DocumentReportService\n resolveSession?: CloudSessionResolver\n entitlements?: EntitlementService\n /** Signs service tokens; without it the deployment offers no services. */\n servicesTokens?: ServicesTokenService\n /** Signs billing tokens; without it the deployment sells nothing. */\n billingTokens?: BillingTokenService\n workspaces: WorkspaceService\n workspaceMembers: WorkspaceMemberService\n}\n\nexport function createPublicCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/', createPublicReportRoutes(services.reports, services.resolveSession))\n .route('/', createPublicSharingRoutes(services.sharing, services.resolveSession))\n .route(\n '/',\n createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)\n )\n .route('/', createSharedCommentRoutes(services.comments, services.resolveSession))\n .route('/', createPublicCollaborationRoutes(services.collaboration, services.resolveSession))\n .route('/', createCommunityRoutes(services.community))\n}\n\nexport function createCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/public', createPublicCloudAPIRouter(services))\n .get('/account/entitlements', async (context) => {\n if (!services.entitlements)\n return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({\n entitlements: await services.entitlements.account(context.get('actor').userId)\n })\n })\n .get('/workspaces/:workspaceId/entitlements', workspaceParams, async (context) => {\n if (!services.entitlements)\n return context.json({ error: { code: 'not_found' as const } }, 404)\n try {\n return context.json({\n entitlements: await services.entitlements.workspace(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n })\n } catch (error) {\n // A workspace the account left, or one that has gone, since the editor listed it.\n if (error instanceof DocumentNotFoundError)\n return context.json({ error: { code: 'not_found' as const } }, 404)\n throw error\n }\n })\n .get('/session', (context) => context.json({ user: context.get('actor') }))\n .route(\n '/',\n createServicesRoutes(\n services.servicesTokens,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createBillingRoutes(\n services.billingTokens,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createCollaborationRoutes(\n services.collaboration,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createDocumentRoutes(\n services.documents,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route('/', createDocumentVersionRoutes(services.versions))\n .route('/', createCommentRoutes(services.comments))\n .route(\n '/',\n createDocumentSharingRoutes(\n services.sharing,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/workspaces',\n createWorkspaceRoutes(\n services.workspaces,\n services.workspaceMembers,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n}\n\nexport type CloudAPI = ReturnType<typeof createCloudAPIRouter>\nexport type PublicCloudAPI = ReturnType<typeof createPublicCloudAPIRouter>\n","import { createCloudIdentityResolver, createCloudSessionResolver } from '#cloud/server/auth'\nimport type { Context } from 'hono'\n\nimport type { CloudServices } from './services'\n\n/**\n * The routes a personal access token reaches: workspaces and their documents, uploads, versions,\n * sharing, and Trash, and who it signs in as. Anything else, such as services tokens that spend\n * credits or administration, takes a session, including routes added later.\n */\nconst ACCESS_TOKEN_API_PATHS = [\n '/api/session',\n '/api/workspaces',\n '/api/documents',\n '/api/uploads',\n '/api/shared-documents',\n '/api/trash'\n]\nconst acceptsAccessToken = (path: string) =>\n ACCESS_TOKEN_API_PATHS.some((prefix) => path === prefix || path.startsWith(`${prefix}/`))\n\n/** Who a request comes from: anyone signed in, an account that may use the server, or may leave. */\nexport function createRequestResolvers(services: CloudServices) {\n return {\n resolveIdentity: services.resolveIdentity ?? createCloudIdentityResolver(services.auth),\n resolveSession: services.resolveSession ?? createCloudSessionResolver(services.auth),\n resolveAccountSession:\n services.resolveAccountSession ??\n (services.resolveSession\n ? services.resolveSession\n : (request: Request) => services.auth.resolveAccountSession(request.headers)),\n twoStepConfirmed:\n services.twoStepConfirmed ??\n (services.resolveIdentity\n ? async () => true\n : (request: Request) => services.auth.twoStepConfirmed(request.headers))\n }\n}\n\n/** The checks routes put in front of themselves to name the request's actor. */\nexport function createRequestChecks(\n services: CloudServices,\n resolvers: ReturnType<typeof createRequestResolvers>\n) {\n const { resolveSession, resolveAccountSession } = resolvers\n return {\n requireActiveSession: async (context: Context, next: () => Promise<void>) => {\n // A route that lets an account leave before accepting the terms named it already.\n if (context.get('actor')) return next()\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n },\n /**\n * The API's caller: a session, or else a personal access token on the routes that take one\n * (`ACCESS_TOKEN_API_PATHS`); account routes never get here.\n */\n requireActiveActor: async (context: Context, next: () => Promise<void>) => {\n if (context.get('actor')) return next()\n const actor =\n (await resolveSession(context.req.raw)) ??\n (acceptsAccessToken(context.req.path)\n ? await services.auth.resolveAccessToken(context.req.raw.headers)\n : null)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n },\n /**\n * An account that may leave: one that has terms to accept can still download its documents\n * and delete itself, which nothing else lets it do until it accepts.\n */\n requireAccountSession: async (context: Context, next: () => Promise<void>) => {\n const actor = await resolveAccountSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n },\n /** Reading one document, which downloading everything before leaving needs, without terms. */\n allowLeavingRead: async (context: Context, next: () => Promise<void>) => {\n if (context.req.method === 'GET') {\n const actor = await resolveAccountSession(context.req.raw)\n if (actor) context.set('actor', actor)\n }\n return next()\n }\n }\n}\n","import { CLOUD_DISCOVERY_PATH } from '#cloud/contract'\nimport type { MiddlewareHandler } from 'hono'\nimport { cors } from 'hono/cors'\n\n/** The community gallery's addresses, which anyone may read from any page. */\nconst COMMUNITY_API_PATH = '/api/community'\n\n/**\n * Whether an address is a public read any page may make: the server's discovery, and the\n * community gallery's list, documents, and thumbnails. They need no account, so they carry none.\n */\nfunction isOpenRead(method: string, path: string): boolean {\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') return false\n return (\n path === CLOUD_DISCOVERY_PATH ||\n path === COMMUNITY_API_PATH ||\n path.startsWith(`${COMMUNITY_API_PATH}/`)\n )\n}\n\n/**\n * Cross-origin access to the server. Its own pages and the origins it trusts send their account\n * with every request. Any other page, such as the documentation site's landing showing the tour,\n * may read the discovery and the gallery without one, and nothing else.\n */\nexport function createCloudCORS(allowedOrigins: ReadonlySet<string>): MiddlewareHandler {\n const trusted = cors({\n origin: (origin) => (allowedOrigins.has(origin) ? origin : null),\n allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],\n allowHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 600\n })\n const openRead = cors({ origin: '*', allowMethods: ['GET', 'HEAD'], maxAge: 600 })\n return (context, next) => {\n const origin = context.req.header('Origin')\n const anyPage = origin !== undefined && !allowedOrigins.has(origin)\n // A preflight names the method it asks for; a request is its own.\n const method = context.req.header('Access-Control-Request-Method') ?? context.req.method\n return anyPage && isOpenRead(method, context.req.path)\n ? openRead(context, next)\n : trusted(context, next)\n }\n}\n","import { CLOUD_EDITOR_VERSION_HEADER, isEditorVersionAtLeast } from '#cloud/contract'\nimport type { MiddlewareHandler } from 'hono'\n\n/**\n * Refuses requests from a desktop editor older than the server's minimum, which would otherwise\n * keep writing with a model the server no longer accepts. Requests that name no version, from\n * browser editors, the CLI or MCP, pass.\n */\nexport function requireMinimumEditor(minimum: string | undefined): MiddlewareHandler {\n return async (context, next) => {\n const version = context.req.header(CLOUD_EDITOR_VERSION_HEADER)\n if (minimum && version && !isEditorVersionAtLeast(version, minimum)) {\n return context.json(\n { error: { code: 'editor_outdated' as const }, minimumEditorVersion: minimum },\n 426\n )\n }\n return next()\n }\n}\n","import { CLOUD_DISCOVERY_PATH } from '#cloud/contract'\n\nexport function shouldPreventIndexing(path: string, policy: 'allow' | 'deny'): boolean {\n return (\n policy === 'deny' ||\n path.startsWith('/api/') ||\n path.startsWith('/admin') ||\n path.startsWith('/auth') ||\n path.startsWith('/account') ||\n path === '/app' ||\n path === '/sign-in' ||\n path === '/sign-up' ||\n path === '/join' ||\n path === CLOUD_DISCOVERY_PATH ||\n // A community document in the editor; its page at `/community/:id` is the one to index.\n /^\\/community\\/[^/]+\\/open\\/?$/.test(path)\n )\n}\n\nexport function withIndexingPolicy(\n response: Response,\n path: string,\n policy: 'allow' | 'deny'\n): Response {\n if (!shouldPreventIndexing(path, policy)) return response\n const headers = new Headers(response.headers)\n headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n}\n\n/** What `/robots.txt` answers: everything closed, or only the server's own pages and API. */\nexport function robotsText(policy: 'allow' | 'deny'): string {\n return policy === 'deny'\n ? 'User-agent: *\\nDisallow: /\\n'\n : 'User-agent: *\\nDisallow: /admin\\nDisallow: /account\\nDisallow: /app\\nDisallow: /api\\nDisallow: /auth\\nDisallow: /sign-in\\nDisallow: /sign-up\\nDisallow: /join\\nDisallow: /.well-known\\n'\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n CLOUD_RATE_LIMITS,\n createActorRateLimiter,\n createTrustedIPRateLimiter,\n routeHasOwnBudget,\n type RateLimitPolicy\n} from '#cloud/server/rate-limit'\nimport type { Kysely } from 'kysely'\n\n/**\n * The app's rate limiters. The public ones count by trusted client IP and answer an exhausted\n * budget as not found, so a capability's existence never leaks; the authenticated one counts by\n * actor and leaves reads and routes with a budget of their own alone.\n */\nexport function createAppRateLimiters(database: Kysely<CloudDatabase>, config: CloudServerConfig) {\n /** A limiter for requests without an account, by trusted client IP. */\n const publicLimiter = (\n policy: RateLimitPolicy,\n options: Parameters<typeof createTrustedIPRateLimiter>[5]\n ) =>\n createTrustedIPRateLimiter(\n database,\n config.authSecret,\n policy,\n { trustedHeaders: config.authTrustedIPHeaders },\n (context) => context.json({ error: { code: 'not_found' as const } }, 404),\n options\n )\n\n return {\n publicRateLimiter: publicLimiter(CLOUD_RATE_LIMITS.publicCapability, {\n resource: (context) => context.req.path,\n // Guests refresh collaboration tickets on their own budget, `publicCollaborationLimiter`.\n skip: routeHasOwnBudget\n }),\n publicCollaborationLimiter: publicLimiter(CLOUD_RATE_LIMITS.collaborationTicket, {\n resource: (context) => context.req.path,\n route: true\n }),\n // The gallery's own budget, across its paths, in place of the per-path public one.\n communityLimiter: publicLimiter(CLOUD_RATE_LIMITS.communityRead, { route: true }),\n authenticatedMutationLimiter: createActorRateLimiter(\n database,\n config.authSecret,\n CLOUD_RATE_LIMITS.authenticatedMutation,\n // Reads are free, and a route with a budget of its own, such as creating documents, counts\n // against that instead.\n (context) => context.req.method === 'GET' || routeHasOwnBudget(context)\n )\n }\n}\n","import type { AccountSecurityErrorCode } from '#cloud/contract'\nimport type { CloudIdentityResolver, CloudSessionResolver } from '#cloud/server/auth'\nimport { APIError } from 'better-auth'\nimport type { Context } from 'hono'\n\nconst ACCOUNT_SECURITY_ERROR_CODES: Record<string, AccountSecurityErrorCode> = {\n INVALID_PASSWORD: 'current_password_invalid',\n PASSWORD_TOO_SHORT: 'password_too_short',\n PASSWORD_TOO_LONG: 'password_too_long',\n FAILED_TO_UNLINK_LAST_ACCOUNT: 'last_authentication_method',\n SESSION_NOT_FRESH: 'session_not_fresh',\n // Better Auth's own word for a session too old to delete the account without its password.\n SESSION_EXPIRED: 'session_not_fresh',\n CREDENTIAL_ACCOUNT_NOT_FOUND: 'session_not_fresh',\n ACCOUNT_SOLE_ADMIN: 'account_sole_admin',\n LAST_ADMIN_REQUIRED: 'last_admin_required',\n CHANGE_EMAIL_DISABLED: 'email_change_unavailable',\n CURRENT_SESSION: 'current_session',\n EMAIL_UNCHANGED: 'email_unchanged',\n // A second factor's code that does not match (`verifySecondFactor`).\n INVALID_CODE: 'code_invalid'\n}\n\nasync function accountAction<Value>(operation: () => Promise<Value>, context: Context) {\n try {\n return await operation()\n } catch (error) {\n if (!(error instanceof APIError)) throw error\n return context.json(\n {\n error: {\n code:\n ACCOUNT_SECURITY_ERROR_CODES[error.body?.code ?? ''] ?? 'authentication_method_failed'\n }\n },\n error.statusCode as 400 | 401 | 403 | 404 | 409 | 422 | 429 | 500\n )\n }\n}\n\nfunction completedMFAResponse(result: Response | undefined, context: Context): Response {\n if (!(result instanceof Response)) return context.json({ ok: true as const })\n if (!result.ok) return result\n const headers = new Headers(result.headers)\n headers.set('Content-Type', 'application/json')\n return new Response(JSON.stringify({ ok: true }), { status: 200, headers })\n}\n\nexport function createAccountActions(resolveSession: CloudSessionResolver) {\n return {\n accountAction,\n activeAccountAction: async <Value>(\n context: Context,\n operation: () => Promise<Value>\n ): Promise<Value | Response> => {\n if (!(await resolveSession(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return accountAction(operation, context)\n },\n verifiedMFAAction: async (\n context: Context,\n identityResolver: CloudIdentityResolver,\n verify: () => Promise<Response | undefined>\n ): Promise<Response> => {\n if (!(await identityResolver(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n const result = await accountAction(verify, context)\n return completedMFAResponse(result instanceof Response ? result : undefined, context)\n }\n }\n}\n","import type { EnrollmentService } from '#cloud/admin'\nimport {\n cloudPasswordChangeSchema,\n cloudMFAEnableSchema,\n cloudMFAVerifySchema,\n cloudPasskeyDeleteSchema,\n cloudSocialLinkSchema,\n cloudUnlinkAuthenticationMethodSchema,\n cloudEmailChangeSchema,\n cloudProfileUpdateSchema,\n cloudLocaleUpdateSchema,\n cloudPictureUploadSchema,\n CLOUD_PICTURE_MAX_BYTES,\n cloudSessionRevokeSchema,\n cloudAccountDeleteSchema,\n cloudTermsAcceptanceSchema,\n type CloudAccountStatus\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport {\n createAccountAuthenticationService,\n type CloudAuthAdapter,\n type CloudIdentityResolver,\n type CloudSessionResolver\n} from '#cloud/server/auth'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport { PictureInvalidError, type UserPictureService } from '#cloud/server/pictures'\nimport { validatedJSON } from '#cloud/server/validation'\nimport type { WorkspaceService } from '#cloud/server/workspaces'\nimport { Hono, type MiddlewareHandler } from 'hono'\nimport { bodyLimit } from 'hono/body-limit'\nimport { toUint8Array } from 'js-base64'\n\nimport { createAccountActions } from './actions'\nimport type { AccountDeletionService } from './deletion'\nimport type { TermsService } from './terms'\n\n/** Room for a Base64 picture and the JSON around it. */\nconst PICTURE_BODY_BYTES = Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4 + 1024\n\nexport type AccountRouteDependencies = {\n auth: CloudAuthAdapter\n config: CloudServerConfig\n pictures: UserPictureService\n enrollment: EnrollmentService\n workspaces: WorkspaceService\n deletion: AccountDeletionService\n terms: TermsService\n resolveIdentity: CloudIdentityResolver\n resolveSession: CloudSessionResolver\n /** Whether the request's session proved its account's second step, or the account has none. */\n twoStepConfirmed: (request: Request) => Promise<boolean>\n requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>\n /** Lets an account with terms to accept reach what leaving needs; see `resolveAccountSession`. */\n requireAccountSession: MiddlewareHandler<CloudAPIEnvironment>\n authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>\n}\n\nexport function createAccountRoutes(services: AccountRouteDependencies) {\n const {\n enrollment,\n workspaces,\n resolveIdentity,\n resolveSession,\n twoStepConfirmed,\n requireActiveSession,\n authenticatedMutationLimiter\n } = services\n const accountAuthentication = createAccountAuthenticationService(services.auth, services.config)\n const { accountAction, activeAccountAction, verifiedMFAAction } =\n createAccountActions(resolveSession)\n return (\n new Hono<CloudAPIEnvironment>()\n .get('/api/account/status', async (context) => {\n const identity = await resolveIdentity(context.req.raw)\n if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n let enrollmentStatus = await enrollment.statusForEmail(identity.email)\n if (services.config.enrollmentMode === 'approval' && !enrollmentStatus) {\n await enrollment.request({ email: identity.email, name: identity.name })\n enrollmentStatus = 'pending'\n }\n // Waiting or declined, from enrollment; null once the account may use the server.\n const enrollmentState =\n services.config.enrollmentMode !== 'approval' || enrollmentStatus === 'approved'\n ? null\n : (enrollmentStatus ?? 'pending')\n // The second step comes after approval, and terms after it: an account still waiting has\n // nothing to prove or accept yet.\n let state: CloudAccountStatus['state'] = enrollmentState ?? 'active'\n if (!enrollmentState && !(await twoStepConfirmed(context.req.raw))) {\n state = 'two-step'\n } else if (!enrollmentState && !(await services.terms.hasAccepted(identity.userId))) {\n state = 'terms'\n }\n if (state === 'active') await workspaces.ensurePersonal(identity)\n return context.json({ user: identity, state })\n })\n .post('/api/account/terms', validatedJSON(cloudTermsAcceptanceSchema), async (context) => {\n const identity = await resolveIdentity(context.req.raw)\n if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n if (!services.terms.requiredVersion) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n // Accepting is for the version shown; one that changed meanwhile is read again first.\n if (!(await services.terms.accept(identity.userId, context.req.valid('json').version))) {\n return context.json({ error: { code: 'terms_changed' as const } }, 409)\n }\n return context.json({ ok: true as const })\n })\n // A session still proving its second step reads which ways it has, and proves one.\n .get('/api/account/mfa', async (context) => {\n const actor = await resolveIdentity(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const mfa = await services.auth.mfaStatus(context.req.raw.headers)\n return mfa\n ? context.json({ mfa })\n : context.json({ error: { code: 'unauthorized' as const } }, 401)\n })\n .post(\n '/api/account/mfa/totp/enable',\n validatedJSON(cloudMFAEnableSchema),\n async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.enableTOTP(context.req.raw.headers, context.req.valid('json').password)\n )\n return result instanceof Response ? result : context.json(result)\n }\n )\n .post('/api/account/mfa/totp/verify', validatedJSON(cloudMFAVerifySchema), (context) =>\n verifiedMFAAction(context, resolveIdentity, () =>\n services.auth.verifyTOTP(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post('/api/account/mfa/recovery/verify', validatedJSON(cloudMFAVerifySchema), (context) =>\n verifiedMFAAction(context, resolveIdentity, () =>\n services.auth.verifyRecoveryCode(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post(\n '/api/account/mfa/recovery/regenerate',\n validatedJSON(cloudMFAEnableSchema),\n async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.generateRecoveryCodes(\n context.req.raw.headers,\n context.req.valid('json').password\n )\n )\n return result instanceof Response ? result : context.json({ backupCodes: result })\n }\n )\n .post(\n '/api/account/mfa/totp/disable',\n validatedJSON(cloudMFAEnableSchema),\n async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n if (passkeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () =>\n services.auth.disableTOTP(\n context.req.raw.headers,\n context.req.valid('json').password\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .get('/api/account/mfa/passkeys', async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ passkeys: await services.auth.listPasskeys(context.req.raw.headers) })\n })\n .post(\n '/api/account/mfa/passkeys/delete',\n validatedJSON(cloudPasskeyDeleteSchema),\n async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const { id } = context.req.valid('json')\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n // An administrator keeps at least one second factor: TOTP or another passkey.\n const status = await services.auth.mfaStatus(context.req.raw.headers)\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n const otherPasskeys = passkeys.filter((passkey) => passkey.id !== id)\n if (!status?.totpEnabled && otherPasskeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () => services.auth.deletePasskey(context.req.raw.headers, id),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/authentication/*', requireActiveSession)\n .use('/api/account/authentication/*', authenticatedMutationLimiter)\n .post(\n '/api/account/authentication/change-password',\n validatedJSON(cloudPasswordChangeSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.changePassword(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post(\n '/api/account/authentication/link-social',\n validatedJSON(cloudSocialLinkSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.startSocialLink(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n if (result instanceof Response) return result\n // The provider's callback checks the state cookie this sets.\n for (const cookie of result.headers.getSetCookie()) {\n context.header('Set-Cookie', cookie, { append: true })\n }\n return context.json({ url: result.url })\n }\n )\n .post(\n '/api/account/authentication/unlink',\n validatedJSON(cloudUnlinkAuthenticationMethodSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.unlink(\n context.req.raw.headers,\n context.req.valid('json').methodId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/profile', requireActiveSession)\n .use('/api/account/profile/*', requireActiveSession)\n .use('/api/account/sessions', requireActiveSession)\n .use('/api/account/sessions/*', requireActiveSession)\n .use('/api/account/sign-ins', requireActiveSession)\n .use('/api/account/deletion', services.requireAccountSession)\n .use('/api/account/delete', services.requireAccountSession)\n .use('/api/account/delete', authenticatedMutationLimiter)\n .use('/api/account/profile', authenticatedMutationLimiter)\n // An account awaiting approval or the terms is written to too, so any signed-in one may.\n .use('/api/account/locale', async (context, next) => {\n const actor = await resolveIdentity(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n })\n .use('/api/account/locale', authenticatedMutationLimiter)\n .use('/api/account/profile/*', authenticatedMutationLimiter)\n .use('/api/account/sessions/*', authenticatedMutationLimiter)\n .get('/api/account/profile', async (context) => {\n const profile = await services.auth.profile(context.req.raw.headers)\n if (!profile) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({\n profile: {\n ...profile,\n createdAt: profile.createdAt.toISOString(),\n emailChangeAvailable: services.auth.emailChangeAvailable\n }\n })\n })\n .post('/api/account/profile', validatedJSON(cloudProfileUpdateSchema), async (context) => {\n const result = await accountAction(\n () => services.auth.updateProfile(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n // The app says which language it uses after signing in and whenever the person changes it.\n .put('/api/account/locale', validatedJSON(cloudLocaleUpdateSchema), async (context) => {\n const result = await accountAction(\n () => services.auth.setLocale(context.req.raw.headers, context.req.valid('json').locale),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .put(\n '/api/account/profile/picture',\n bodyLimit({\n maxSize: PICTURE_BODY_BYTES,\n onError: (context) => context.json({ error: { code: 'picture_invalid' as const } }, 413)\n }),\n validatedJSON(cloudPictureUploadSchema),\n async (context) => {\n const bytes = toUint8Array(context.req.valid('json').data)\n try {\n const image = await services.pictures.upload(context.get('actor').userId, bytes)\n return context.json({ image })\n } catch (error) {\n if (!(error instanceof PictureInvalidError)) throw error\n return context.json({ error: { code: 'picture_invalid' as const } }, 400)\n }\n }\n )\n .delete('/api/account/profile/picture', async (context) => {\n await services.pictures.remove(context.get('actor').userId)\n return context.json({ ok: true as const })\n })\n .post(\n '/api/account/profile/email',\n validatedJSON(cloudEmailChangeSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.changeEmail(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .get('/api/account/sessions', async (context) => {\n const sessions = await services.auth.sessions(context.req.raw.headers)\n if (!sessions) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ sessions })\n })\n .post(\n '/api/account/sessions/revoke',\n validatedJSON(cloudSessionRevokeSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n services.auth.revokeSession(\n context.req.raw.headers,\n context.req.valid('json').sessionId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post('/api/account/sessions/revoke-others', async (context) => {\n const result = await accountAction(\n () => services.auth.revokeOtherSessions(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/sign-ins', async (context) => {\n const signIns = await services.auth.signIns(context.req.raw.headers)\n if (!signIns) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ signIns })\n })\n .get('/api/account/deletion', async (context) => {\n return context.json({ deletion: await services.deletion.plan(context.get('actor').userId) })\n })\n .post('/api/account/delete', validatedJSON(cloudAccountDeleteSchema), async (context) => {\n const result = await accountAction(\n () =>\n services.auth.deleteAccount(\n context.req.raw.headers,\n context.req.valid('json').password\n ),\n context\n )\n if (result instanceof Response) return result\n // The session is gone with the account; the cookie that named it goes too.\n for (const cookie of result.getSetCookie()) {\n context.header('Set-Cookie', cookie, { append: true })\n }\n return context.json({ ok: true as const })\n })\n .get('/api/account/authentication', async (context) => {\n const result = await accountAction(\n () => accountAuthentication.methods(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json(result)\n })\n )\n}\n\n/** The account routes' types, for the portal's typed client. */\nexport type CloudAccountRoutes = ReturnType<typeof createAccountRoutes>\n","import { cloudAccessTokenCreateSchema, cloudAccessTokenRevokeSchema } from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport type { CloudAuthAdapter, CloudSessionResolver } from '#cloud/server/auth'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono, type MiddlewareHandler } from 'hono'\n\nimport { createAccountActions } from './actions'\n\nexport type AccessTokenRouteDependencies = {\n auth: CloudAuthAdapter\n resolveSession: CloudSessionResolver\n /** A session's, never a token's: account routes resolve sessions alone. */\n requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>\n authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>\n}\n\n/**\n * The account's personal access tokens: listed, made, and revoked from a signed-in session only,\n * so a token never sees or makes others. Making one needs a recent sign-in.\n */\nexport function createAccessTokenRoutes(services: AccessTokenRouteDependencies) {\n const { accountAction } = createAccountActions(services.resolveSession)\n return new Hono<CloudAPIEnvironment>()\n .use('/api/account/tokens', services.requireActiveSession)\n .use('/api/account/tokens/*', services.requireActiveSession)\n .use('/api/account/tokens/*', services.authenticatedMutationLimiter)\n .get('/api/account/tokens', async (context) => {\n const tokens = await services.auth.listAccessTokens(context.req.raw.headers)\n if (!tokens) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ tokens })\n })\n .post(\n '/api/account/tokens/create',\n validatedJSON(cloudAccessTokenCreateSchema),\n async (context) => {\n const result = await accountAction(\n () => services.auth.createAccessToken(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json(result, 201)\n }\n )\n .post(\n '/api/account/tokens/revoke',\n validatedJSON(cloudAccessTokenRevokeSchema),\n async (context) => {\n const result = await accountAction(\n () =>\n services.auth.revokeAccessToken(context.req.raw.headers, context.req.valid('json').id),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n}\n\nexport type CloudAccessTokenRoutes = ReturnType<typeof createAccessTokenRoutes>\n","import { staticEntitlementsSchema } from '#cloud/server/policy/schema'\nimport * as v from 'valibot'\n\nexport const setAccountEntitlementsSchema = v.object({\n values: staticEntitlementsSchema,\n /** Who decided these values, such as `billing`; stored as the row's source. */\n source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),\n /** Increases with every decision the writer makes, such as a billing event's timestamp. */\n externalVersion: v.pipe(v.number(), v.safeInteger(), v.minValue(0))\n})\n","import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'\nimport { accountParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport { bearerAuth } from 'hono/bearer-auth'\n\nimport { setAccountEntitlementsSchema } from './schema'\nimport type { InternalService } from './service'\n\n/** The internal API on HTTP, for runtimes without a private transport to their services. */\nexport function createInternalRoutes(service: InternalService, serviceToken: string) {\n const digest = hashCapability(serviceToken)\n const unauthorized = { error: { code: 'unauthorized' as const } }\n return new Hono()\n .use(\n '*',\n bearerAuth({\n verifyToken: (token) => capabilityHashMatches(digest, token),\n noAuthenticationHeader: { message: unauthorized },\n invalidAuthenticationHeader: { message: unauthorized },\n invalidToken: { message: unauthorized }\n })\n )\n .put(\n '/accounts/:userId/entitlements',\n accountParams,\n validatedJSON(setAccountEntitlementsSchema),\n async (context) => {\n const { userId } = context.req.valid('param')\n const result = await service.setAccountEntitlements(userId, context.req.valid('json'))\n if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ applied: result.applied })\n }\n )\n .get('/accounts/:userId/seats', accountParams, async (context) => {\n const seats = await service.accountSeats(context.req.valid('param').userId)\n if (seats === null) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ seats })\n })\n}\n","import { accountSeats } from '#cloud/server/billing/seats'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createAccountEntitlementRepository } from '#cloud/server/policy'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport { setAccountEntitlementsSchema } from './schema'\n\nexport type SetAccountEntitlementsInput = v.InferInput<typeof setAccountEntitlementsSchema>\n\nexport function parseSetAccountEntitlements(input: unknown) {\n return v.parse(setAccountEntitlementsSchema, input)\n}\n\n/**\n * What services beside Cloud, such as billing, may change. Runtimes expose it to them through\n * their own transport: an authenticated HTTP route on Node, a service binding on Workers.\n */\nexport function createInternalService(database: Kysely<CloudDatabase>) {\n const entitlements = createAccountEntitlementRepository(database)\n return {\n /**\n * Sets an account's plan, which every workspace it owns takes. `found` is false for an\n * unknown account; `applied` is false for an outdated version.\n */\n async setAccountEntitlements(\n userId: string,\n input: SetAccountEntitlementsInput\n ): Promise<{ found: boolean; applied: boolean }> {\n const { values, source, externalVersion } = parseSetAccountEntitlements(input)\n const account = await entitlements.account(userId)\n if (!account) return { found: false, applied: false }\n const { applied } = await entitlements.setVersioned(account, values, source, externalVersion)\n return { found: true, applied }\n },\n\n /**\n * How many people can edit across the workspaces an account owns, which billing charges a\n * seat for; `null` for an unknown account.\n */\n async accountSeats(userId: string): Promise<number | null> {\n const account = await entitlements.account(userId)\n return account ? accountSeats(database, userId) : null\n }\n }\n}\n\nexport type InternalService = ReturnType<typeof createInternalService>\n","import {\n createAdminAuditService,\n createAdminDocumentService,\n createAdminEmailService,\n createAdminOperationsService,\n createAdminReportService,\n createAdminUserService,\n createCloudAdminRoutes\n} from '#cloud/admin'\nimport { createAccountDeletionService } from '#cloud/server/account/deletion'\nimport { createAccountRoutes } from '#cloud/server/account/routes'\nimport { createTermsService } from '#cloud/server/account/terms'\nimport { createAccessTokenRoutes } from '#cloud/server/account/tokens'\nimport { createCloudAPIRouter, createPublicCloudAPIRouter } from '#cloud/server/api'\nimport { createAuthenticationEmailService } from '#cloud/server/auth'\nimport { signInProviders } from '#cloud/server/auth/methods'\nimport { createInternalRoutes, createInternalService } from '#cloud/server/internal'\nimport { Hono } from 'hono'\n\nimport type { createRequestChecks, createRequestResolvers } from './checks'\nimport type { createAppRateLimiters } from './limiters'\nimport type { CloudAppServices, CloudServices } from './services'\n\n/** The routers the app mounts, each over the services, checks, and limiters it needs. */\nexport function createAppRouters(\n services: CloudServices,\n app: CloudAppServices,\n resolvers: ReturnType<typeof createRequestResolvers>,\n checks: ReturnType<typeof createRequestChecks>,\n limiters: ReturnType<typeof createAppRateLimiters>,\n allowedOrigins: ReadonlySet<string>\n) {\n const { config, database } = services\n const { resolveIdentity, resolveSession, twoStepConfirmed } = resolvers\n const admin = createCloudAdminRoutes(\n {\n email: createAdminEmailService(database, services.transactionalEmail, {\n publicURL: config.publicURL\n }),\n enrollment: app.enrollment,\n users: createAdminUserService(database, services.auth, {\n requireMFA: config.deploymentAdminMFARequired,\n approval: config.enrollmentMode === 'approval',\n signInProviders: signInProviders(config),\n pictures: app.pictures,\n notify: services.transactionalEmail\n ? createAuthenticationEmailService(services.transactionalEmail, config.publicURL)\n : undefined\n }),\n audit: createAdminAuditService(database),\n operations: createAdminOperationsService(database, config),\n documents: createAdminDocumentService(database, {\n closeRooms: services.onDocumentTakenDown,\n purgeGraceMs: config.documentPurgeGraceMs,\n communityWorkspaceId: config.community?.workspaceId ?? null,\n objects: services.objects,\n documents: app.documents,\n email: services.transactionalEmail,\n publicURL: config.publicURL,\n contactEmail: config.legal?.abuseEmail\n }),\n reports: createAdminReportService(\n database,\n { email: services.transactionalEmail, contactEmail: config.legal?.abuseEmail },\n { communityWorkspaceId: config.community?.workspaceId ?? null }\n )\n },\n allowedOrigins,\n {\n database,\n secret: config.authSecret,\n auth: services.auth,\n requireMFA: config.deploymentAdminMFARequired\n }\n )\n const account = createAccountRoutes({\n auth: services.auth,\n terms: createTermsService(database, config),\n pictures: app.pictures,\n config,\n enrollment: app.enrollment,\n workspaces: app.workspaces,\n deletion: createAccountDeletionService(database),\n resolveIdentity,\n resolveSession,\n twoStepConfirmed,\n requireActiveSession: checks.requireActiveSession,\n requireAccountSession: checks.requireAccountSession,\n authenticatedMutationLimiter: limiters.authenticatedMutationLimiter\n })\n const accessTokens = createAccessTokenRoutes({\n auth: services.auth,\n resolveSession,\n requireActiveSession: checks.requireActiveSession,\n authenticatedMutationLimiter: limiters.authenticatedMutationLimiter\n })\n const shared = {\n collaboration: app.collaboration,\n documents: app.documents,\n versions: app.versions,\n comments: app.comments,\n community: app.community,\n entitlements: app.entitlements,\n sharing: app.sharing,\n reports: app.reports,\n workspaces: app.workspaces,\n workspaceMembers: app.workspaceMembers,\n resolveSession\n }\n const cloudAPI = createCloudAPIRouter({\n ...shared,\n database,\n rateLimitSecret: config.authSecret,\n servicesTokens: app.servicesTokens,\n billingTokens: app.billingTokens\n })\n const publicCloudAPI = createPublicCloudAPIRouter(shared)\n // Services such as billing authenticate with their own token, not a session.\n const internalAPI = config.internalServiceToken\n ? createInternalRoutes(createInternalService(database), config.internalServiceToken)\n : new Hono()\n return { admin, account, accessTokens, cloudAPI, publicCloudAPI, internalAPI }\n}\n","import { createEnrollmentService, type EnrollmentService } from '#cloud/admin'\nimport type {\n CloudAuthAdapter,\n CloudIdentityResolver,\n CloudSessionResolver\n} from '#cloud/server/auth'\nimport { enrollmentEmailOptions } from '#cloud/server/auth'\nimport { createBillingTokenService, createSeatNotifier } from '#cloud/server/billing'\nimport { createCollaborationTicketService } from '#cloud/server/collaboration'\nimport { createCommentService } from '#cloud/server/comments'\nimport { createCommunityService } from '#cloud/server/community'\nimport { CloudConfigError, type CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createDocumentService } from '#cloud/server/documents'\nimport { createDocumentVersionService } from '#cloud/server/documents/versions'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { reportCloudError, type CloudErrorReporter } from '#cloud/server/errors'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { ForwardedRequestId } from '#cloud/server/logging'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createUserPictures } from '#cloud/server/pictures'\nimport {\n createConfiguredCloudPolicy,\n createDefaultCloudPolicy,\n createEntitlementService,\n EntitlementOpenFeatureProvider,\n type CloudPolicy,\n type EntitlementSource\n} from '#cloud/server/policy'\nimport { createDocumentReportService } from '#cloud/server/reports'\nimport { createServicesTokenService, type ServicesSigningKey } from '#cloud/server/services'\nimport { createDocumentSharingService } from '#cloud/server/sharing'\nimport { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'\nimport type { Kysely } from 'kysely'\n\nexport type CloudServices = {\n config: CloudServerConfig\n database: Kysely<CloudDatabase>\n auth: CloudAuthAdapter\n objects: ObjectStore\n resolveIdentity?: CloudIdentityResolver\n resolveSession?: CloudSessionResolver\n /**\n * An approved account even before it accepted the current terms, for leaving: reading its\n * documents and deleting the account. Defaults to `resolveSession` when that is given.\n */\n resolveAccountSession?: CloudSessionResolver\n /**\n * Whether the request's session proved its account's second step, or the account has none.\n * Defaults to the auth adapter's, or to yes when `resolveIdentity` stands in for signing in.\n */\n twoStepConfirmed?: (request: Request) => Promise<boolean>\n invitationDelivery?: InvitationDelivery\n invitationOutbox?: InvitationOutbox\n transactionalEmail?: TransactionalEmailService\n enrollment?: EnrollmentService\n entitlementSource?: EntitlementSource\n policy?: CloudPolicy\n /** The imported `servicesSigningKey`, required when the config names one. See `loadServicesSigningKey`. */\n servicesSigningKey?: ServicesSigningKey\n /**\n * Where clients reach this runtime's collaboration relay. Without one, Cloud rooms fall back to\n * peer-to-peer and writes are not enforced by the server.\n */\n relayURL?: string\n /** Ends a restored document's live rooms, on the relay this runtime runs, if any. */\n onDocumentRestored?: (documentId: string) => void\n /** Ends a taken-down document's live rooms, saving them for when it is restored. */\n onDocumentTakenDown?: (documentId: string) => void\n /** Tells a document's live rooms its version history changed, on the relay this runtime runs. */\n onDocumentVersionsChanged?: (documentId: string) => void\n /** Tells a document's live rooms one of its comment threads changed, on this runtime's relay. */\n onDocumentCommentsChanged?: (documentId: string, threadId: string) => void\n /**\n * Keeps work a request started running after its answer, as Workers' `waitUntil` does; without\n * it the work runs on its own, as Node lets it.\n */\n runInBackground?: (task: Promise<unknown>) => void\n /** Logs errors no route handled, and reports them when the deployment configures error tracking. */\n reportError?: CloudErrorReporter\n /** The request ID this runtime trusts from what stands in front of it, such as `cf-ray`. */\n forwardedRequestId?: ForwardedRequestId\n}\n\n/** The domain services the app's routes are built from, over the runtime's injected services. */\nexport function createAppServices(services: CloudServices) {\n const { config, database, objects } = services\n const workspaces = createWorkspaceService(database)\n const pictures = createUserPictures(database, { publicURL: config.publicURL })\n const billingTokens =\n services.servicesSigningKey && config.billingEndpoint\n ? createBillingTokenService({\n issuer: new URL(config.publicURL).origin,\n signingKey: services.servicesSigningKey,\n lifetimeSeconds: config.servicesTokenLifetimeSeconds\n })\n : undefined\n // Billing charges for the people who can edit, so it hears when they change.\n const seatNotifier =\n billingTokens && config.billingEndpoint\n ? createSeatNotifier({ database, endpoint: config.billingEndpoint, tokens: billingTokens })\n : undefined\n const onSeatsChanged = seatNotifier\n ? (accountIds: readonly string[]) => {\n const task = seatNotifier.notify(accountIds).catch((error: unknown) => {\n void reportCloudError(services.reportError, 'Telling billing about seats failed', error, {\n source: 'background'\n })\n })\n if (services.runInBackground) services.runInBackground(task)\n }\n : undefined\n const workspaceMembers = createWorkspaceMemberService(database, {\n email: services.transactionalEmail,\n publicURL: config.publicURL,\n onSeatsChanged\n })\n const enrollment =\n services.enrollment ??\n createEnrollmentService(database, enrollmentEmailOptions(config, services.transactionalEmail))\n const policy =\n services.policy ??\n (services.entitlementSource\n ? createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(services.entitlementSource))\n : createConfiguredCloudPolicy(config, database))\n const documents = createDocumentService(database, objects, {\n policy,\n technicalMaximumUploadBytes: config.technicalLimits.maximumUploadBytes,\n onVersionsChanged: services.onDocumentVersionsChanged,\n trash: {\n retentionMs: config.documentRetentionMs,\n purgeGraceMs: config.documentPurgeGraceMs,\n leaseDurationMs: config.cleanupLeaseDurationMs,\n reportError: services.reportError\n },\n reportError: services.reportError\n })\n const versions = createDocumentVersionService(database, objects, {\n policy,\n deploymentMode: config.deployment,\n onRestored: services.onDocumentRestored,\n onVersionsChanged: services.onDocumentVersionsChanged\n })\n const community = createCommunityService(\n database,\n objects,\n documents,\n versions,\n config.community?.workspaceId ?? null\n )\n const entitlements = createEntitlementService(\n database,\n policy,\n config.technicalLimits.maximumUploadBytes,\n config.technicalLimits.maximumConnectionsPerRoom\n )\n const sharing = createDocumentSharingService(database, {\n delivery: services.invitationDelivery,\n outbox: services.invitationOutbox,\n continuationSecret: config.authSecret,\n publicURL: config.publicURL,\n policy,\n deploymentMode: config.deployment,\n workspaceInvitations: workspaceMembers\n })\n const collaboration = createCollaborationTicketService({\n database,\n sharing,\n authSecret: config.authSecret,\n relayURL: services.relayURL,\n policy,\n deploymentMode: config.deployment\n })\n if (config.servicesSigningKey && !services.servicesSigningKey) {\n throw new CloudConfigError('Services need the signing key imported by loadServicesSigningKey')\n }\n const servicesTokens = services.servicesSigningKey\n ? createServicesTokenService({\n database,\n policy,\n deploymentMode: config.deployment,\n issuer: new URL(config.publicURL).origin,\n signingKey: services.servicesSigningKey,\n lifetimeSeconds: config.servicesTokenLifetimeSeconds\n })\n : undefined\n const comments = createCommentService(database, {\n sharing,\n onCommentsChanged: services.onDocumentCommentsChanged,\n notifier: services.transactionalEmail\n ? { email: services.transactionalEmail, publicURL: config.publicURL }\n : undefined\n })\n const reports = createDocumentReportService(database, {\n sharing,\n email: services.transactionalEmail,\n adminRecipients: config.enrollmentAdminNotificationEmails,\n publicURL: config.publicURL\n })\n return {\n workspaces,\n pictures,\n workspaceMembers,\n enrollment,\n policy,\n documents,\n versions,\n community,\n entitlements,\n sharing,\n collaboration,\n servicesTokens,\n billingTokens,\n comments,\n reports\n }\n}\n\nexport type CloudAppServices = ReturnType<typeof createAppServices>\n","import {\n CLOUD_API_MAX_BODY_BYTES,\n CLOUD_DISCOVERY_PATH,\n CLOUD_PROTOCOL_VERSION,\n CLOUD_SERVICES_JWKS_PATH\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport { AUTH_BASE_PATH } from '#cloud/server/auth'\nimport { createCommunityThumbnailRoutes } from '#cloud/server/community'\nimport { cloudDiscoveryFromConfig } from '#cloud/server/config'\nimport { cloudErrorHandler } from '#cloud/server/errors'\nimport { cloudRequestId } from '#cloud/server/logging'\nimport { createPictureRoutes } from '#cloud/server/pictures'\nimport { Hono } from 'hono'\nimport { bodyLimit } from 'hono/body-limit'\n\nimport { createRequestChecks, createRequestResolvers } from './checks'\nimport { createCloudCORS } from './cors'\nimport { requireMinimumEditor } from './editors'\nimport { robotsText, shouldPreventIndexing } from './indexing'\nimport { createAppRateLimiters } from './limiters'\nimport { createAppRouters } from './routes'\nimport { createAppServices, type CloudServices } from './services'\n\nexport { shouldPreventIndexing, withIndexingPolicy } from './indexing'\nexport type { CloudServices } from './services'\n\n/** Where administration is mounted. */\nconst ADMIN_API_PATH = '/api/admin'\n\n/**\n * The Cloud server over a runtime's services. The order the routes and checks are registered in\n * is what guards them: rate limiters come before the routes they count, the public API before\n * the checks that require an account, and administration before the general write limiter.\n */\nexport function createCloudApp(services: CloudServices) {\n const { config } = services\n const discovery = cloudDiscoveryFromConfig(config)\n const allowedOrigins = new Set(\n [config.publicURL, ...config.trustedOrigins].map((origin) => new URL(origin).origin)\n )\n const cloudCORS = createCloudCORS(allowedOrigins)\n const app = createAppServices(services)\n const resolvers = createRequestResolvers(services)\n const checks = createRequestChecks(services, resolvers)\n const limiters = createAppRateLimiters(services.database, config)\n const routers = createAppRouters(services, app, resolvers, checks, limiters, allowedOrigins)\n\n return (\n new Hono<CloudAPIEnvironment>()\n .onError(cloudErrorHandler(services.reportError))\n .use('*', cloudRequestId(services.forwardedRequestId))\n // Discovery is public, so any editor's page may read it without credentials: an editor on\n // another address learns whether the server lists it before it signs in.\n .use(CLOUD_DISCOVERY_PATH, cloudCORS)\n .use('/api/*', cloudCORS)\n .use('/api/*', requireMinimumEditor(config.minimumEditorVersion))\n .use(\n '/api/*',\n bodyLimit({\n maxSize: CLOUD_API_MAX_BODY_BYTES,\n onError: (context) => context.json({ error: { code: 'invalid_request' as const } }, 413)\n })\n )\n .use('*', async (context, next) => {\n await next()\n if (shouldPreventIndexing(context.req.path, config.indexingPolicy)) {\n context.header('X-Robots-Tag', 'noindex, nofollow, noarchive')\n }\n })\n .get('/robots.txt', (context) => {\n context.header('Content-Type', 'text/plain; charset=utf-8')\n return context.body(robotsText(config.indexingPolicy))\n })\n .get('/health', (context) =>\n context.json({\n status: 'ok' as const,\n protocolVersion: CLOUD_PROTOCOL_VERSION\n })\n )\n .get('/ready', async (context) => {\n try {\n await services.database.selectFrom('workspace').select('id').limit(1).execute()\n const objects = await services.objects.checkReadiness()\n if (!objects.ok) {\n return context.json(\n { status: 'unavailable' as const, dependency: 'object_storage' as const },\n 503\n )\n }\n return context.json({\n status: 'ready' as const,\n objectStorage: {\n checksumVerification: objects.checksumVerification,\n multipartUpload: services.objects.capabilities.multipartUpload\n }\n })\n } catch {\n return context.json({ status: 'unavailable' as const }, 503)\n }\n })\n .get(CLOUD_DISCOVERY_PATH, (context) => context.json(discovery))\n .get(CLOUD_SERVICES_JWKS_PATH, async (context) =>\n app.servicesTokens ? context.json(app.servicesTokens.jwks()) : context.notFound()\n )\n .on(['GET', 'POST'], `${AUTH_BASE_PATH}/*`, (context) =>\n services.auth.handler(context.req.raw)\n )\n .route('/', routers.account)\n .route('/', routers.accessTokens)\n .route('/', createPictureRoutes(app.pictures))\n .use('/api/shares/:shareId/collaboration-ticket', limiters.publicCollaborationLimiter)\n .use('/api/public/*', limiters.publicRateLimiter)\n .use('/api/shares/*', limiters.publicRateLimiter)\n .use('/api/invitations/*', limiters.publicRateLimiter)\n .use('/api/community/*', limiters.communityLimiter, limiters.publicRateLimiter)\n .route('/', createCommunityThumbnailRoutes(app.community))\n .route('/api', routers.publicCloudAPI)\n .route('/api/internal', routers.internalAPI)\n .use('/api/documents/:documentId', checks.allowLeavingRead)\n .use('/api/*', checks.requireActiveActor)\n .route(ADMIN_API_PATH, routers.admin)\n .use('/api/*', limiters.authenticatedMutationLimiter)\n .route('/api', routers.cloudAPI)\n )\n}\n\nexport type CloudApp = ReturnType<typeof createCloudApp>\n","import { createCloudDatabase } from '#cloud/server'\nimport { PostgresDialect } from 'kysely'\nimport { Pool, type PoolConfig } from 'pg'\n\n/**\n * How long a query serving a request may run before PostgreSQL cancels it. Rate limits and\n * sessions live in PostgreSQL, so one stuck query would otherwise hold its connection, and every\n * request waiting for one, indefinitely.\n */\nexport const POSTGRES_STATEMENT_TIMEOUT_MS = 30_000\n\nexport type PostgresCloudDatabaseOptions = {\n connectionString: string\n pool?: Omit<PoolConfig, 'connectionString' | 'statement_timeout' | 'query_timeout'>\n /**\n * How long one statement may run, `POSTGRES_STATEMENT_TIMEOUT_MS` unless set; null for no limit\n * of this server's own, as migrations need and as Hyperdrive takes, which keeps no session\n * settings and ends queries past its own limit. PostgreSQL cancels a statement past it, so its\n * connection is free again for the next query.\n */\n statementTimeoutMs?: number | null\n}\n\nexport function createPostgresCloudDatabase(options: PostgresCloudDatabaseOptions) {\n const statementTimeoutMs =\n options.statementTimeoutMs === undefined\n ? POSTGRES_STATEMENT_TIMEOUT_MS\n : options.statementTimeoutMs\n return createCloudDatabase({\n dialect: new PostgresDialect({\n pool: new Pool({\n ...options.pool,\n ...(statementTimeoutMs === null ? {} : { statement_timeout: statementTimeoutMs }),\n connectionString: options.connectionString\n })\n })\n })\n}\n","import type { CloudServerConfig } from '#cloud/server'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport {\n AbortMultipartUploadCommand,\n CompleteMultipartUploadCommand,\n CopyObjectCommand,\n CreateMultipartUploadCommand,\n DeleteObjectCommand,\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n S3Client,\n UploadPartCommand\n} from '@aws-sdk/client-s3'\n// eslint-disable-next-line @open-pencil/structure/no-mixed-case-acronym-identifiers -- Upstream export spelling.\nimport { getSignedUrl as getSignedURL } from '@aws-sdk/s3-request-presigner'\n\nconst CHECKSUM_METADATA_KEY = 'openpencil-sha256'\nconst READINESS_BODY = new TextEncoder().encode('openpencil-ready')\nconst READINESS_CHECKSUM = 'Hq6g3mmWpyBNobXoWZIz/d0/d8KLjJyEKqNnJh6KXjA='\nconst MULTIPART_THRESHOLD = 32 * 1024 * 1024\nconst MULTIPART_PART_SIZE = 16 * 1024 * 1024\nconst MAX_MULTIPART_PARTS = 10_000\n\ntype S3ErrorMetadata = {\n $metadata?: {\n httpStatusCode?: number\n }\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n '$metadata' in error &&\n (error as S3ErrorMetadata).$metadata?.httpStatusCode === 404\n )\n}\n\nfunction encryption(config: CloudServerConfig) {\n return config.s3ServerSideEncryption\n ? {\n ServerSideEncryption: config.s3ServerSideEncryption,\n ...(config.s3KmsKeyId ? { SSEKMSKeyId: config.s3KmsKeyId } : {})\n }\n : {}\n}\n\nexport function createS3ObjectStore(config: CloudServerConfig): ObjectStore {\n const client = new S3Client({\n endpoint: config.s3Endpoint,\n region: config.s3Region,\n forcePathStyle: config.s3ForcePathStyle,\n requestChecksumCalculation: 'WHEN_REQUIRED',\n responseChecksumValidation: 'WHEN_REQUIRED',\n credentials: {\n accessKeyId: config.s3AccessKeyId,\n secretAccessKey: config.s3SecretAccessKey,\n ...(config.s3SessionToken ? { sessionToken: config.s3SessionToken } : {})\n }\n })\n const nativeSHA256 = config.s3ChecksumVerification === 'native'\n\n async function headObject(key: string) {\n return client.send(\n new HeadObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n ...(nativeSHA256 ? { ChecksumMode: 'ENABLED' as const } : {})\n })\n )\n }\n\n /**\n * Copies a file under the deleted prefix before it goes, so it outlives the delete until the\n * bucket's lifecycle rule expires it. A file already gone, as when a cleanup pass retries, has\n * nothing to keep.\n */\n async function keepDeleted(key: string, prefix: string): Promise<void> {\n try {\n await client.send(\n new CopyObjectCommand({\n Bucket: config.s3Bucket,\n Key: `${prefix}${key}`,\n CopySource: `${config.s3Bucket}/${key.split('/').map(encodeURIComponent).join('/')}`,\n MetadataDirective: 'COPY',\n ...encryption(config)\n })\n )\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n }\n\n return {\n capabilities: {\n nativeSHA256,\n multipartUpload: true,\n conditionalWrites: false\n },\n\n async checkReadiness() {\n const key = `.openpencil/readiness/${crypto.randomUUID()}`\n try {\n await client.send(\n new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n Body: READINESS_BODY,\n ContentType: 'application/octet-stream',\n ChecksumSHA256: nativeSHA256 ? READINESS_CHECKSUM : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: READINESS_CHECKSUM },\n ...encryption(config)\n })\n )\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n return {\n ok: object.ContentLength === READINESS_BODY.byteLength && checksum === READINESS_CHECKSUM,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata'\n }\n } finally {\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n }\n },\n\n async createDownload(input) {\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const url = await getSignedURL(\n client,\n new GetObjectCommand({ Bucket: config.s3Bucket, Key: input.key }),\n { expiresIn }\n )\n return {\n url,\n method: 'GET',\n headers: {},\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async createUpload(input) {\n if (input.byteSize > MULTIPART_THRESHOLD) {\n const created = await client.send(\n new CreateMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n )\n if (!created.UploadId) throw new Error('S3 did not return a multipart upload ID')\n const partCount = Math.ceil(input.byteSize / MULTIPART_PART_SIZE)\n if (partCount > MAX_MULTIPART_PARTS) throw new Error('Object requires too many S3 parts')\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const parts = await Promise.all(\n Array.from({ length: partCount }, async (_, index) => {\n const partNumber = index + 1\n return {\n partNumber,\n url: await getSignedURL(\n client,\n new UploadPartCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: created.UploadId,\n PartNumber: partNumber\n }),\n { expiresIn }\n ),\n method: 'PUT' as const,\n headers: {}\n }\n })\n )\n return {\n kind: 'multipart',\n uploadId: created.UploadId,\n partSize: MULTIPART_PART_SIZE,\n parts,\n expiresAt: input.expiresAt.toISOString()\n }\n }\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const command = new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n const url = await getSignedURL(client, command, {\n expiresIn,\n unhoistableHeaders: new Set([\n ...(nativeSHA256 ? ['x-amz-checksum-sha256'] : []),\n `x-amz-meta-${CHECKSUM_METADATA_KEY}`\n ])\n })\n return {\n kind: 'single',\n url,\n method: 'PUT',\n headers: {\n 'Content-Type': input.contentType,\n ...(nativeSHA256 ? { 'x-amz-checksum-sha256': input.checksum } : {}),\n [`x-amz-meta-${CHECKSUM_METADATA_KEY}`]: input.checksum\n },\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async completeUpload(input) {\n await client.send(\n new CompleteMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId,\n MultipartUpload: {\n Parts: input.parts.map((part) => ({ ETag: part.etag, PartNumber: part.partNumber }))\n }\n })\n )\n },\n\n async abortUpload(input) {\n try {\n await client.send(\n new AbortMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId\n })\n )\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n },\n\n async head(key) {\n try {\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n if (object.ContentLength == null || !checksum || !object.ContentType) return null\n return {\n byteSize: object.ContentLength,\n checksum,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata',\n contentType: object.ContentType\n }\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n },\n\n async delete(key) {\n if (config.s3DeletedPrefix) await keepDeleted(key, config.s3DeletedPrefix)\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n },\n\n async write(input) {\n await client.send(\n new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n Body: input.bytes,\n ContentType: input.contentType,\n ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n )\n },\n\n async read(key) {\n try {\n const object = await client.send(\n new GetObjectCommand({ Bucket: config.s3Bucket, Key: key })\n )\n return object.Body ? await object.Body.transformToByteArray() : null\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n },\n\n async readRange(key, start, endExclusive) {\n if (endExclusive <= start) return new Uint8Array()\n try {\n const object = await client.send(\n new GetObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n Range: `bytes=${start}-${endExclusive - 1}`\n })\n )\n return object.Body ? await object.Body.transformToByteArray() : null\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n }\n }\n}\n","import {\n CLOUD_COMMUNITY_PATH,\n cloudCommunityPagePath,\n communityDocumentsSchema,\n type CommunityDocument\n} from '#cloud/contract'\n// eslint-disable-next-line @open-pencil/structure/no-mixed-case-acronym-identifiers -- Upstream export spelling.\nimport { createHead, transformHtmlTemplate as transformHTMLTemplate } from 'unhead/server'\nimport * as v from 'valibot'\n\n/** What a community page says about itself to link previews and search engines. */\nexport type PageMeta = {\n title: string\n description: string\n url: string\n image?: string\n}\n\ntype API = { fetch(request: Request): Response | Promise<Response> }\n\n/**\n * Why a community page shows no tags: there is no gallery or no such document (404), or the API\n * could not answer, such as when it limited the visitor, whose status and retry advice the page\n * keeps.\n */\nexport type CommunityPageFailure = { status: number; retryAfter: string | null }\n\n/**\n * The gallery's documents, read through the server's own API as the visitor asked for the page,\n * so the request counts against the visitor's limits, or why they could not be read.\n */\nasync function communityDocuments(\n api: API,\n page: Request\n): Promise<CommunityDocument[] | CommunityPageFailure> {\n const url = new URL(`/api${CLOUD_COMMUNITY_PATH}`, page.url)\n const response = await api.fetch(new Request(url, { headers: page.headers }))\n if (!response.ok) {\n return { status: response.status, retryAfter: response.headers.get('Retry-After') }\n }\n const body = v.safeParse(communityDocumentsSchema, await response.json())\n return body.success ? body.output.documents : { status: 502, retryAfter: null }\n}\n\nconst NOT_FOUND: CommunityPageFailure = { status: 404, retryAfter: null }\n\n/**\n * The tags for the gallery, or for one of its documents when `documentId` names one, or why the\n * page has none: no gallery or no such document, or an API that could not answer.\n */\nexport async function communityPageMeta(\n api: API,\n page: Request,\n documentId: string | undefined\n): Promise<PageMeta | CommunityPageFailure> {\n const documents = await communityDocuments(api, page)\n if (!Array.isArray(documents)) return documents\n const { origin, host } = new URL(page.url)\n if (documentId === undefined) {\n const first = documents.at(0)\n return {\n title: `Community · ${host}`,\n description: 'Files to open, explore, and copy into your own workspace.',\n url: new URL(CLOUD_COMMUNITY_PATH, origin).href,\n image: first ? new URL(first.thumbnailPath, origin).href : undefined\n }\n }\n const document = documents.find((entry) => entry.id === documentId)\n if (!document) return NOT_FOUND\n return {\n title: `${document.name} · Community · ${host}`,\n description:\n document.versions.at(0)?.description ??\n `${document.name}, a file to open in OpenPencil and copy into your own workspace.`,\n url: new URL(cloudCommunityPagePath(document.id), origin).href,\n image: new URL(document.thumbnailPath, origin).href\n }\n}\n\n/** The page with the gallery's title, description, preview, and canonical address in its head. */\nexport async function withPageMeta(html: string, meta: PageMeta): Promise<string> {\n const head = createHead()\n head.push({\n title: meta.title,\n meta: [\n { name: 'description', content: meta.description },\n { property: 'og:type', content: 'website' },\n { property: 'og:title', content: meta.title },\n { property: 'og:description', content: meta.description },\n { property: 'og:url', content: meta.url },\n ...(meta.image\n ? [\n { property: 'og:image', content: meta.image },\n { name: 'twitter:card', content: 'summary_large_image' }\n ]\n : [])\n ],\n link: [{ rel: 'canonical', href: meta.url }]\n })\n return transformHTMLTemplate(head, html)\n}\n","import { CLOUD_PORTAL_COMMUNITY_PAGES, CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'\nimport {\n cloudErrorHandler,\n cloudRequestId,\n withIndexingPolicy,\n type CloudErrorReporter,\n type ForwardedRequestId\n} from '#cloud/server'\nimport { Hono } from 'hono'\n\nimport { communityPageMeta, withPageMeta } from './community'\n\n/** A file of the Cloud site (`bun run build:cloud`): the editor and the portal. */\nexport type SiteFile = {\n body: ReadableStream | Uint8Array<ArrayBuffer>\n type: string\n /** Overrides the cache policy built files get, for a site whose files change in place. */\n cacheControl?: string\n}\n\n/** Reads the built site's file at a URL path, or null when there is none. */\nexport type SiteFiles = (path: string, request: Request) => Promise<SiteFile | null>\n\nconst PORTAL_PAGE = '/cloud.html'\nconst EDITOR_PAGE = '/index.html'\n\n/**\n * What the site's pages may run: only the site's own scripts and Turnstile's on the portal, so an\n * injected script tag or one from another host never runs. The pages carry no inline script (the\n * boot splash loads its own file). The editor compiles design JSX and code-tool snippets with\n * `Function` and runs WebAssembly and workers from blobs, which the policy keeps; plugins and AI\n * providers reach other hosts through `fetch`, which it leaves be. Desktop sign-in approval and\n * the editor must never be framed by another site.\n */\nexport const SITE_CONTENT_SECURITY_POLICY = [\n \"script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval' blob: https://challenges.cloudflare.com\",\n \"worker-src 'self' blob:\",\n \"object-src 'none'\",\n \"base-uri 'self'\",\n \"frame-ancestors 'none'\"\n].join('; ')\n\nconst PAGE_HEADERS = {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-cache',\n 'Content-Security-Policy': SITE_CONTENT_SECURITY_POLICY,\n // Browsers take this only over HTTPS; a deployment on plain HTTP is unaffected.\n 'Strict-Transport-Security': 'max-age=31536000',\n 'Referrer-Policy': 'no-referrer',\n 'X-Content-Type-Options': 'nosniff'\n}\n\nexport type CloudServerOptions = {\n /** The built site; without it, the server answers only its API. */\n site?: SiteFiles\n indexingPolicy: 'allow' | 'deny'\n /** Reports errors reading the site's files, when the deployment configures error tracking. */\n reportError?: CloudErrorReporter\n /** The request ID the runtime trusts from what stands in front of it; see `cloudRequestId`. */\n forwardedRequestId?: ForwardedRequestId\n}\n\nfunction cacheControl(path: string): string {\n if (path.startsWith('/assets/')) return 'public, max-age=31536000, immutable'\n return 'public, max-age=3600'\n}\n\n/**\n * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API\n * everywhere else, and, where the API has nothing, the site's files, or the editor's\n * `index.html` for any other page, whose router knows the editor's own addresses.\n */\nexport function createCloudServer(\n api: { fetch(request: Request): Response | Promise<Response> },\n { site, indexingPolicy, reportError, forwardedRequestId }: CloudServerOptions\n) {\n const server = new Hono()\n .onError(cloudErrorHandler(reportError))\n .use(cloudRequestId(forwardedRequestId))\n server.use(async (c, next) => {\n await next()\n c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)\n })\n if (site) {\n const pages = CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])\n server.on(['GET', 'HEAD'], pages, async (c) => {\n const page = await site(PORTAL_PAGE, c.req.raw)\n return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()\n })\n // The gallery's pages say what they show to link previews and search engines, which read the\n // page as served rather than as its script draws it.\n server.on(['GET', 'HEAD'], [...CLOUD_PORTAL_COMMUNITY_PAGES], async (c) => {\n const page = await site(PORTAL_PAGE, c.req.raw)\n if (!page) return c.notFound()\n const meta = await communityPageMeta(api, c.req.raw, c.req.param('documentId'))\n const html = await new Response(page.body).text()\n if ('title' in meta) return c.body(await withPageMeta(html, meta), 200, PAGE_HEADERS)\n // The page still loads and says what went wrong; the status and retry advice stay the API's.\n const headers = meta.retryAfter\n ? { ...PAGE_HEADERS, 'Retry-After': meta.retryAfter }\n : PAGE_HEADERS\n return new Response(html, { status: meta.status, headers })\n })\n server.on(['GET', 'HEAD'], '*', async (c, next) => {\n await next()\n if (c.res.status !== 404) return\n const file = await site(c.req.path, c.req.raw)\n if (file) {\n c.res = file.type.startsWith('text/html')\n ? new Response(file.body, { headers: PAGE_HEADERS })\n : new Response(file.body, {\n headers: {\n 'Content-Type': file.type,\n 'Cache-Control': file.cacheControl ?? cacheControl(c.req.path),\n 'X-Content-Type-Options': 'nosniff'\n }\n })\n return\n }\n if (!c.req.header('Accept')?.includes('text/html')) return\n const editor = await site(EDITOR_PAGE, c.req.raw)\n if (editor) c.res = new Response(editor.body, { headers: PAGE_HEADERS })\n })\n }\n server.all('*', (c) => api.fetch(c.req.raw))\n return server\n}\n","import { PostHog, type PostHogOptions } from 'posthog-node'\n\n/** Where a server caught an error, and for a request, its method, matched route, and ID. */\nexport type ErrorReportContext<Source extends string = string> = {\n source: Source\n method?: string\n route?: string\n /** The request's ID, as `cloudRequestId` named it; logs carry it too. */\n requestId?: string\n /** What failed, as the server's log says it; not sent to PostHog, whose report has the error. */\n message?: string\n /** The signed-in user the error happened for, by account ID. */\n userId?: string\n /** The records involved, by kind, such as `{ documentId }`; IDs only, never their contents. */\n resources?: Readonly<Record<string, string>>\n}\n\n/** Sends a caught error where it is seen; it never rejects. */\nexport type ErrorReporter<Source extends string = string> = (\n error: unknown,\n context: ErrorReportContext<Source>\n) => Promise<void>\n\n/** A record kind as PostHog's properties name it: `documentId` as `document_id`. */\nfunction propertyName(kind: string): string {\n return kind.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)\n}\n\n/** The context's record IDs as report properties. */\nfunction resourceProperties(resources: Readonly<Record<string, string>> = {}) {\n return Object.fromEntries(Object.entries(resources).map(([kind, id]) => [propertyName(kind), id]))\n}\n\nexport type PostHogErrorReporterOptions = {\n /** The project API key, or how to read it; a key that cannot be read yet is read again later. */\n key: string | (() => Promise<string>)\n host: string\n /** Sent with every report: which service and deployment report. */\n properties: Record<string, string>\n /**\n * Also send the context's account and record IDs: the user as the report's `distinct_id`, the\n * records as `document_id` and the like. Off, a report names neither, as it always did.\n */\n includeIds?: boolean\n /** The property that names the context's `source`, such as `cloud_source`. */\n sourceProperty: string\n /** Names the service in its own log, such as `Cloud`. */\n logName: string\n fetch?: PostHogOptions['fetch']\n}\n\n/**\n * Reports errors to PostHog error tracking, each as it is caught, as a `$exception` with no person\n * profile and no GeoIP. A report carries `properties`, the source, and a request's method and\n * matched route and ID; with `includeIds`, also the account and record IDs involved. Never a name,\n * an email, an address, or what a request carried.\n */\nexport function createPostHogErrorReporter<Source extends string>(\n options: PostHogErrorReporterOptions\n): ErrorReporter<Source> {\n const { key, logName } = options\n const connect = async () => {\n const client = new PostHog(typeof key === 'string' ? key : await key(), {\n host: options.host,\n disableGeoip: true,\n // The SDK's own fetch unless a caller passes one.\n ...(options.fetch && { fetch: options.fetch })\n })\n // The SDK resolves a capture that PostHog refused and emits the refusal instead.\n client.on('error', (failure: unknown) => {\n console.error(`[${logName}] PostHog refused an error report:`, failure)\n })\n return client\n }\n let connecting: Promise<PostHog> | undefined\n const posthog = async () => {\n connecting ??= connect()\n try {\n return await connecting\n } catch (failure) {\n connecting = undefined\n throw failure\n }\n }\n return async (error, context) => {\n try {\n const client = await posthog()\n const ids = options.includeIds === true\n // Undefined request fields are left out of the event's JSON.\n await client.captureExceptionImmediate(error, ids ? context.userId : undefined, {\n ...options.properties,\n [options.sourceProperty]: context.source,\n http_method: context.method,\n http_route: context.route,\n request_id: context.requestId,\n ...(ids ? resourceProperties(context.resources) : {}),\n // A user's ID names the report's user, never a person profile in PostHog.\n $process_person_profile: false\n })\n } catch (failure) {\n console.error(`[${logName}] Reporting an error failed:`, failure)\n }\n }\n}\n","import { createPostHogErrorReporter } from '#cloud/errors'\nimport type { CloudServerConfig } from '#cloud/server'\nimport type { CloudErrorReporter } from '#cloud/server/errors'\nimport type { PostHogOptions } from 'posthog-node'\n\n/** Which runtime serves the deployment, as its error reports name it. */\nexport type CloudRuntimeName = 'node' | 'cloudflare'\n\n/**\n * Reports server errors to the PostHog project the deployment's `[error_tracking]` names, or\n * returns nothing when it names none. Reports carry the runtime, the deployment, and where the\n * error was caught, and the account and record IDs involved when `include_ids` is set; never a\n * name, an email, an address, or what a request carried.\n */\nexport function createCloudErrorReporter(\n config: CloudServerConfig,\n runtime: CloudRuntimeName,\n options: Pick<PostHogOptions, 'fetch'> = {}\n): CloudErrorReporter | undefined {\n const tracking = config.errorTracking\n if (!tracking) return undefined\n return createPostHogErrorReporter({\n key: tracking.projectAPIKey,\n host: tracking.host,\n properties: {\n cloud_runtime: runtime,\n cloud_deployment: config.deployment,\n cloud_host: new URL(config.publicURL).host\n },\n sourceProperty: 'cloud_source',\n includeIds: tracking.includeIds,\n logName: 'Cloud',\n fetch: options.fetch\n })\n}\n","import type { CloudLogWriter, ForwardedRequestId } from '#cloud/server'\n\n/** Workers Logs indexes the keys of an object passed to `console`, so the line goes as one. */\nexport const writeWorkersLogLine: CloudLogWriter = (line) => {\n console[line.level](line)\n}\n\n/** Cloudflare's ray ID, such as `8f1e2d3c4b5a6978-FRA`. */\nconst RAY_ID = /^[0-9a-f]{16}(-[A-Z]{3})?$/\n\n/** Names a request by the ray ID Cloudflare's edge set on it, which a client cannot choose. */\nexport const cloudflareRayId: ForwardedRequestId = (headers) => {\n const ray = headers.get('cf-ray')\n return ray && RAY_ID.test(ray) ? ray : undefined\n}\n","import { createCloudErrorReporter } from '#cloud/runtime/posthog/errors'\nimport {\n createLoggingErrorReporter,\n loadServicesSigningKey,\n parseCloudDeploymentTOML,\n type ServicesSigningKey,\n type CloudEnvironment,\n type CloudErrorReporter,\n type CloudServerConfig\n} from '#cloud/server'\n\nimport { writeWorkersLogLine } from './logging'\nimport type { CollaborationRelayRPC } from './relay'\n\n/** The bindings `deploy/cloudflare/wrangler.jsonc` gives the Worker and its relay objects. */\nexport type CloudflareCloudBindings = {\n /** PostgreSQL, through Hyperdrive. */\n HYPERDRIVE: Hyperdrive\n /** The collaboration relay, one object per document. */\n RELAY: DurableObjectNamespace<CollaborationRelayRPC>\n /** The built site, `dist-cloud`: the editor and the portal. */\n ASSETS: Fetcher\n /** Required by `[email] transport = \"cloudflare\"`. */\n EMAIL?: SendEmail\n}\n\n/** The bindings, plus the variables and secrets the deployment TOML names. */\nexport type CloudflareCloudEnvironment = CloudflareCloudBindings & Record<string, unknown>\n\nexport type PreparedCloudflareCloud = {\n config: CloudServerConfig\n servicesSigningKey: ServicesSigningKey | undefined\n /** Logs errors, and sends them to error tracking when the deployment configures it. */\n reportError: CloudErrorReporter\n}\n\n/** The Worker's string variables and secrets, with `DATABASE_URL` from Hyperdrive. */\nfunction configEnvironment(env: CloudflareCloudEnvironment): CloudEnvironment {\n return {\n ...Object.fromEntries(\n Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n ),\n DATABASE_URL: env.HYPERDRIVE.connectionString\n }\n}\n\n/**\n * Reads the deployment TOML once per isolate: its config and services signing key stay the same for the\n * Worker's lifetime. A failure is not kept, so the next request tries again.\n */\n/** Logs errors from before a config parsed, which has no error tracking to send them to. */\nconst logOnly = createLoggingErrorReporter(writeWorkersLogLine)\n\nexport function cloudflareCloudSetup(source: string) {\n let prepared: Promise<PreparedCloudflareCloud> | null = null\n /** Set once an attempt's config parses, so its later setup steps that fail can be reported. */\n let reportError: CloudErrorReporter | undefined\n const prepare = (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {\n prepared ??= (async () => {\n // An attempt whose config fails to parse has no project to report to, not an earlier one's.\n reportError = undefined\n const config = parseCloudDeploymentTOML(source, configEnvironment(env))\n reportError = createLoggingErrorReporter(\n writeWorkersLogLine,\n createCloudErrorReporter(config, 'cloudflare')\n )\n return { config, servicesSigningKey: await loadServicesSigningKey(config), reportError }\n })().catch((error: unknown) => {\n prepared = null\n throw error\n })\n return prepared\n }\n return {\n prepare,\n /**\n * The reporter of the latest attempt once its config parsed, which also sends to error tracking\n * when the config has it; before that, one that only logs.\n */\n reporter: () => reportError ?? logOnly\n }\n}\n","import { cloudflareRayId } from './logging'\n\n/**\n * The Worker variable that takes a deployment off the air, as the Deploy Cloud workflow's\n * `maintenance` input sets it: every request answers 503 and scheduled cleanup does nothing, while\n * the deploy itself restarts the rooms' objects and closes their sockets. A database restore runs\n * under it (deploy/openpencil/README.md).\n */\nexport const MAINTENANCE_VARIABLE = 'OPENPENCIL_CLOUD_MAINTENANCE'\n\nexport function inMaintenance(env: Record<string, unknown>): boolean {\n return env[MAINTENANCE_VARIABLE] === 'on'\n}\n\n/** How a relay socket open when maintenance began is closed: the service restarts. */\nexport const MAINTENANCE_CLOSE_CODE = 1012\n\n/**\n * What every request gets meanwhile; clients retry, and nothing reaches the database. It names the\n * request as other responses do, by its ray ID.\n */\nexport function maintenanceResponse(request: Request): Response {\n return new Response('OpenPencil Cloud is down for maintenance.', {\n status: 503,\n headers: {\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Retry-After': '300',\n 'X-Request-Id': cloudflareRayId(request.headers) ?? crypto.randomUUID()\n }\n })\n}\n","import { RELAY_CLOSE } from '#cloud/contract'\nimport {\n readRelayPeerState,\n type CollaborationRelay,\n type RelayConnection,\n type RelaySocket\n} from '#cloud/server'\n\n/** What the relay's sockets need from the Durable Object that holds them. */\nexport type RelaySocketHost = {\n /** The sockets the object still holds, as `DurableObjectState.getWebSockets` lists them. */\n sockets(): WebSocket[]\n /** Creates the relay for the document the object serves, once per wake. */\n createRelay(documentId: string): Promise<CollaborationRelay>\n}\n\n/** A socket message's bytes; text is passed on as bytes for the relay to refuse. */\nfunction bytes(data: unknown): Uint8Array {\n if (data instanceof ArrayBuffer) return new Uint8Array(data)\n return new TextEncoder().encode(typeof data === 'string' ? data : '')\n}\n\n/**\n * A hibernatable socket as the relay sees it. The peer's state rides on the socket as its\n * attachment, so a relay woken from hibernation can resume the peer.\n */\nfunction relaySocket(socket: WebSocket): RelaySocket {\n // A closing socket throws on send and close, which would stop a broadcast to the others.\n const open = () => socket.readyState === WebSocket.OPEN\n return {\n send(data) {\n if (open()) socket.send(data)\n },\n close(code, reason) {\n if (open()) socket.close(code, reason)\n },\n remember(state) {\n socket.serializeAttachment(state)\n }\n }\n}\n\n/**\n * The relay a Durable Object wakes to and its sockets' connections to it. Sockets are accepted\n * for hibernation, so an idle object is evicted while they stay open, each keeping its peer; the\n * relay it wakes to resumes them, loading a room's document only once a message needs it.\n */\nexport function createRelaySockets(host: RelaySocketHost) {\n let relay: Promise<CollaborationRelay> | null = null\n /** Each socket's connection to the relay, since the object last woke. */\n const connections = new Map<WebSocket, RelayConnection>()\n\n /** The relay, created once per wake; it takes back every socket the object still holds. */\n function open(documentId: string): Promise<CollaborationRelay> {\n const opened = (relay ??= host.createRelay(documentId).then((created) => {\n for (const socket of host.sockets()) {\n if (connections.has(socket)) continue\n const state = readRelayPeerState(socket.deserializeAttachment())\n // A socket the relay never admitted has no peer to resume, and its ticket is long due.\n if (state) connections.set(socket, created.resume(relaySocket(socket), state))\n else socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n }\n return created\n }))\n opened.catch(() => {\n if (relay === opened) relay = null\n })\n return opened\n }\n\n /**\n * The socket's connection, waking the relay for the document its peer is in, or null for a\n * stray socket. A socket that closed while the object hibernated may already be missing from\n * the ones the woken relay takes back, so its peer is resumed here, if only to leave.\n */\n async function connectionOf(socket: WebSocket): Promise<RelayConnection | null> {\n const known = connections.get(socket)\n if (known) return known\n const state = readRelayPeerState(socket.deserializeAttachment())\n if (!state) return null\n const woken = await open(state.authorization.documentId)\n const connection = connections.get(socket) ?? woken.resume(relaySocket(socket), state)\n connections.set(socket, connection)\n return connection\n }\n\n return {\n open,\n /** Whether a relay is awake, or anyone is still connected to wake one for. */\n get active() {\n return relay !== null || host.sockets().length > 0\n },\n\n /** Connects a socket the object just accepted, which presents its ticket next. */\n accept(socket: WebSocket, woken: CollaborationRelay) {\n connections.set(socket, woken.connect(relaySocket(socket)))\n },\n\n async message(socket: WebSocket, message: string | ArrayBuffer) {\n const connection = await connectionOf(socket)\n if (connection) connection.receive(bytes(message))\n else socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n },\n\n /** Lets the socket's peer leave its room, so the room closes once it empties. */\n async closed(socket: WebSocket) {\n const connection = await connectionOf(socket)\n connections.delete(socket)\n connection?.closed()\n }\n }\n}\n","import { RELAY_DOCUMENT_PARAM, RELAY_HEARTBEAT } from '#cloud/contract'\nimport { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'\nimport { createS3ObjectStore } from '#cloud/runtime/s3/objects'\nimport {\n createCollaborationRelay,\n createCollaborationStateStore,\n createConfiguredCloudPolicy,\n relayDocumentLookups,\n reportCloudError,\n type CollaborationRelay,\n type CollaborationRelayOptions\n} from '#cloud/server'\nimport { DurableObject } from 'cloudflare:workers'\nimport type { Context } from 'hono'\nimport * as v from 'valibot'\n\nimport type { CloudflareCloudEnvironment, PreparedCloudflareCloud } from '../environment'\nimport { inMaintenance, MAINTENANCE_CLOSE_CODE, maintenanceResponse } from '../maintenance'\nimport { createRelaySockets } from './sockets'\n\n/** What the Worker calls on a document's relay object. */\nexport interface CollaborationRelayRPC extends DurableObject<CloudflareCloudEnvironment> {\n /** Ends the document's live rooms after a restore, without saving them. */\n startOver(documentId: string): Promise<void>\n /** Ends a taken-down document's live rooms, saving them. */\n closeDocument(documentId: string): Promise<void>\n /** Tells the document's live rooms its version history changed. */\n announceVersions(documentId: string): Promise<void>\n /** Tells the document's live rooms one of its comment threads changed. */\n announceComments(documentId: string, threadId: string): Promise<void>\n}\n\n/** The Durable Object class a Worker exports for collaboration rooms. */\nexport type CollaborationRelayObjectClass = new (\n ctx: DurableObjectState,\n env: CloudflareCloudEnvironment\n) => CollaborationRelayRPC\n\nconst documentIdSchema = v.pipe(v.string(), v.uuid())\n\n/**\n * The most a room's document may hold on Cloudflare. A Durable Object has 128 MB of memory for\n * the document, the update joining it, and the snapshot written from it, so a room past this is\n * turned away and its editors save without one.\n */\nexport const CLOUDFLARE_MAXIMUM_ROOM_BYTES = 32 * 1024 * 1024\n\n/**\n * The document's relay object. With a jurisdiction, objects are created and keep their storage\n * only inside it; an object named outside one is a different object, so a deployment never\n * changes its jurisdiction while rooms are live.\n */\nexport function relayFor(\n env: CloudflareCloudEnvironment,\n documentId: string,\n jurisdiction?: DurableObjectJurisdiction\n) {\n const namespace = jurisdiction ? env.RELAY.jurisdiction(jurisdiction) : env.RELAY\n return namespace.get(namespace.idFromName(documentId))\n}\n\n/**\n * Sends a relay socket to its document's relay object. The ticket's URL names the document; the\n * object refuses tickets for any other.\n */\nexport function relayRoute(jurisdiction?: DurableObjectJurisdiction) {\n return async (c: Context<{ Bindings: CloudflareCloudEnvironment }>): Promise<Response> => {\n if (c.req.header('Upgrade')?.toLowerCase() !== 'websocket') {\n return c.text('Expected a WebSocket upgrade', 426)\n }\n const documentId = c.req.query(RELAY_DOCUMENT_PARAM)\n if (!v.is(documentIdSchema, documentId)) return c.text('Missing document', 400)\n return relayFor(c.env, documentId, jurisdiction).fetch(c.req.raw)\n }\n}\n\n/** The relay over the deployment's PostgreSQL and object store. */\nfunction configuredRelay(\n { config }: PreparedCloudflareCloud,\n documentId: string,\n onError: NonNullable<CollaborationRelayOptions['onError']>\n): CollaborationRelay {\n // Hyperdrive keeps no session settings and ends queries past its own limit.\n const database = createPostgresCloudDatabase({\n connectionString: config.databaseURL,\n statementTimeoutMs: null\n })\n return createCollaborationRelay({\n authSecret: config.authSecret,\n documentId,\n store: createCollaborationStateStore(database, createS3ObjectStore(config)),\n maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,\n maximumRoomBytes: CLOUDFLARE_MAXIMUM_ROOM_BYTES,\n maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,\n onError,\n ...relayDocumentLookups(\n database,\n createConfiguredCloudPolicy(config, database),\n config.deployment\n )\n })\n}\n\n/**\n * The Durable Object class holding one document's live rooms: every epoch of the document meets\n * on one relay, so a restore or a version change reaches all of them in one call. Its sockets\n * hibernate with it (see `createRelaySockets`).\n */\nexport function createCloudflareRelayObject(\n prepare: (env: CloudflareCloudEnvironment) => Promise<PreparedCloudflareCloud>\n): CollaborationRelayObjectClass {\n return class CollaborationRelayObject\n extends DurableObject<CloudflareCloudEnvironment>\n implements CollaborationRelayRPC\n {\n constructor(ctx: DurableObjectState, env: CloudflareCloudEnvironment) {\n super(ctx, env)\n // Peers check the relay still hears them; the runtime answers without waking the object.\n ctx.setWebSocketAutoResponse(\n new WebSocketRequestResponsePair(RELAY_HEARTBEAT.ping, RELAY_HEARTBEAT.pong)\n )\n }\n\n readonly #sockets = createRelaySockets({\n sockets: () => this.ctx.getWebSockets(),\n createRelay: async (documentId) => {\n const prepared = await prepare(this.env)\n return configuredRelay(\n prepared,\n documentId,\n (message, error, { userId, ...resources } = {}) =>\n this.ctx.waitUntil(\n reportCloudError(prepared.reportError, message, error, {\n source: 'relay',\n resources,\n ...(userId && { userId })\n })\n )\n )\n }\n })\n\n /** Accepts a socket that `relayRoute` sent here. */\n override async fetch(request: Request): Promise<Response> {\n if (inMaintenance(this.env)) return maintenanceResponse(request)\n const documentId = new URL(request.url).searchParams.get(RELAY_DOCUMENT_PARAM)\n if (!v.is(documentIdSchema, documentId)) return new Response(null, { status: 400 })\n const relay = await this.#sockets.open(documentId)\n const { 0: client, 1: server } = new WebSocketPair()\n this.ctx.acceptWebSocket(server)\n this.#sockets.accept(server, relay)\n return new Response(null, { status: 101, webSocket: client })\n }\n\n override async webSocketMessage(socket: WebSocket, message: string | ArrayBuffer) {\n // A socket from before maintenance began reaches the room no more: its editor reconnects\n // once maintenance ends, and nothing it sends meanwhile is written.\n if (inMaintenance(this.env)) {\n socket.close(MAINTENANCE_CLOSE_CODE, 'Down for maintenance')\n return\n }\n await this.#sockets.message(socket, message)\n }\n\n // Under maintenance a closing socket leaves its room as it is: closing the room would save\n // its state into a database that may be mid-restore.\n override async webSocketClose(socket: WebSocket) {\n if (inMaintenance(this.env)) return\n await this.#sockets.closed(socket)\n }\n\n override async webSocketError(socket: WebSocket) {\n if (inMaintenance(this.env)) return\n await this.#sockets.closed(socket)\n }\n\n async startOver(documentId: string) {\n if (!this.#sockets.active) return\n ;(await this.#sockets.open(documentId)).startOver(documentId)\n }\n\n async closeDocument(documentId: string) {\n if (!this.#sockets.active) return\n ;(await this.#sockets.open(documentId)).closeDocument(documentId)\n }\n\n async announceVersions(documentId: string) {\n if (!this.#sockets.active) return\n ;(await this.#sockets.open(documentId)).announceVersions(documentId)\n }\n\n async announceComments(documentId: string, threadId: string) {\n if (!this.#sockets.active) return\n ;(await this.#sockets.open(documentId)).announceComments(documentId, threadId)\n }\n }\n}\n","import type { SiteFiles } from '#cloud/runtime/site/server'\n\n/** The built site's files from the Worker's static assets. */\nexport function assetSiteFiles(assets: Fetcher): SiteFiles {\n return async (path, request) => {\n const file = await assets.fetch(new URL(path, request.url))\n if (!file.ok || !file.body) return null\n return {\n body: file.body,\n type: file.headers.get('Content-Type') ?? 'application/octet-stream'\n }\n }\n}\n","import { DOMParser, Node } from '@xmldom/xmldom'\n\n/**\n * Gives the AWS SDK the XML parser it reads S3's answers with. Wrangler bundles the SDK's browser\n * build, which parses XML with the browser's `DOMParser` and `Node`; workerd has neither, so every\n * S3 error would surface as a `ReferenceError` instead of its code. A runtime that has a\n * `DOMParser` keeps its own.\n */\nexport function provideXMLParser(): void {\n if ('DOMParser' in globalThis) return\n Object.assign(globalThis, { DOMParser, Node })\n}\n","import { defaultRelayURL, RELAY_PATH } from '#cloud/contract'\nimport { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'\nimport { createS3ObjectStore } from '#cloud/runtime/s3/objects'\nimport { createCloudServer } from '#cloud/runtime/site/server'\nimport {\n cleanupPassOptions,\n cloudErrorHandler,\n cloudRequestId,\n createCleanupServices,\n createCloudApp,\n createCloudAuthenticationRuntime,\n createConfiguredCloudPolicy,\n createInvitationOutbox,\n createTransactionalEmailService,\n reportCloudError,\n runCleanup,\n type CloudErrorReporter,\n type CloudErrorSource,\n type TransactionalEmailService\n} from '#cloud/server'\nimport { Hono } from 'hono'\n\nimport { createCloudflareEmailTransport } from './email'\nimport {\n cloudflareCloudSetup,\n type CloudflareCloudEnvironment,\n type PreparedCloudflareCloud\n} from './environment'\nimport { cloudflareRayId } from './logging'\nimport { inMaintenance, maintenanceResponse } from './maintenance'\nimport { createCloudflareRelayObject, relayFor, relayRoute } from './relay'\nimport { assetSiteFiles } from './site'\nimport { provideXMLParser } from './xml'\n\nfunction emailTransport({ config }: PreparedCloudflareCloud, env: CloudflareCloudEnvironment) {\n if (config.emailTransport !== 'cloudflare') return undefined\n if (!env.EMAIL) throw new Error('[email] transport = \"cloudflare\" needs the EMAIL binding')\n return createCloudflareEmailTransport(env.EMAIL)\n}\n\n/** A reporter whose reports keep the Worker running until they are sent. */\nfunction keptAlive(\n reporter: CloudErrorReporter | undefined,\n context: Pick<ExecutionContext, 'waitUntil'>\n): CloudErrorReporter | undefined {\n if (!reporter) return undefined\n return (error, errorContext) => {\n const reported = reporter(error, errorContext)\n context.waitUntil(reported)\n return reported\n }\n}\n\n/**\n * What one request or cron run needs. Workers can't share connections between requests, so each\n * gets its own database client, closed once its background work settles.\n */\nfunction cloudServices(\n prepared: PreparedCloudflareCloud,\n env: CloudflareCloudEnvironment,\n context: Pick<ExecutionContext, 'waitUntil'>\n) {\n const { config } = prepared\n const reporter = keptAlive(prepared.reportError, context)\n const reportError = (message: string, error: unknown, source: CloudErrorSource) =>\n reportCloudError(reporter, message, error, { source })\n // Hyperdrive keeps no session settings and ends queries past its own limit.\n const database = createPostgresCloudDatabase({\n connectionString: config.databaseURL,\n statementTimeoutMs: null\n })\n const objects = createS3ObjectStore(config)\n const transport = emailTransport(prepared, env)\n const queued = createTransactionalEmailService(database, {\n encryptionSecret: config.authSecret,\n from: config.emailFrom ?? '',\n replyTo: config.emailReplyTo,\n transport\n })\n // Mail is sent once the request is done rather than by a polling worker, so sign-in links\n // don't wait for the next cron run.\n let enqueued = false\n const email: TransactionalEmailService = {\n ...queued,\n enqueue(input, transaction) {\n enqueued = true\n return queued.enqueue(input, transaction)\n }\n }\n const background: Promise<unknown>[] = []\n const runInBackground = (task: Promise<unknown>) => {\n background.push(\n task.catch((error: unknown) => reportError('Background work failed', error, 'background'))\n )\n }\n const deliver = () =>\n email.deliverPending({\n batchSize: config.emailBatchSize,\n leaseDurationMs: config.emailLeaseDurationMs,\n maximumAttempts: config.emailMaximumAttempts\n })\n return {\n config,\n database,\n objects,\n email,\n transport,\n runInBackground,\n deliver,\n reporter,\n /** Sends what the request queued and closes the database after everything it started. */\n finish() {\n context.waitUntil(\n Promise.allSettled(background)\n .then(() => (enqueued && transport ? deliver() : undefined))\n .catch((error: unknown) => reportError('Sending email failed', error, 'email'))\n .then(() => database.destroy())\n )\n }\n }\n}\n\n/** Cleanup, and email that failed to send after its request or that a full batch left behind. */\nasync function runScheduled(\n prepared: PreparedCloudflareCloud,\n env: CloudflareCloudEnvironment,\n context: Pick<ExecutionContext, 'waitUntil'>\n) {\n const services = cloudServices(prepared, env, context)\n const { config, database, objects } = services\n try {\n if (config.cleanupEnabled) {\n const policy = createConfiguredCloudPolicy(config, database)\n await runCleanup(\n createCleanupServices(\n config,\n database,\n objects,\n policy,\n services.reporter,\n services.transport ? services.email : undefined\n ),\n cleanupPassOptions(config)\n )\n }\n if (services.transport) await services.deliver()\n } finally {\n services.finish()\n }\n}\n\n/**\n * OpenPencil Cloud on Cloudflare Workers, configured by a deployment TOML. The Worker serves the\n * API, the editor, and the portal per request, a Durable Object per document runs its collaboration rooms, and a\n * Cron Trigger runs cleanup and retries email.\n */\nexport type CloudflareCloudOptions = {\n /**\n * Where collaboration rooms' Durable Objects run and keep their storage, such as `eu` for a\n * deployment whose data stays in the EU; by default, near whoever opens the room first.\n */\n relayJurisdiction?: DurableObjectJurisdiction\n}\n\nexport function createCloudflareCloud(\n configSource: string,\n { relayJurisdiction }: CloudflareCloudOptions = {}\n) {\n provideXMLParser()\n const { prepare, reporter } = cloudflareCloudSetup(configSource)\n const relay = (env: CloudflareCloudEnvironment, documentId: string) =>\n relayFor(env, documentId, relayJurisdiction)\n\n const router = new Hono<{ Bindings: CloudflareCloudEnvironment }>()\n // Setup, relay routing, and the runtime around the app; the app reports its own errors.\n .onError((error, c) => cloudErrorHandler(keptAlive(reporter(), c.executionCtx))(error, c))\n .use('*', cloudRequestId(cloudflareRayId))\n .get(RELAY_PATH, relayRoute(relayJurisdiction))\n .all('*', async (c) => {\n const prepared = await prepare(c.env)\n const services = cloudServices(prepared, c.env, c.executionCtx)\n const { config, database, email, transport, runInBackground } = services\n try {\n const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email, {\n runInBackground,\n validateSchema: false\n })\n const app = createCloudApp({\n config,\n database,\n auth,\n objects: services.objects,\n invitationOutbox: transport ? createInvitationOutbox(email) : undefined,\n transactionalEmail: email,\n enrollment,\n servicesSigningKey: prepared.servicesSigningKey,\n relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),\n onDocumentRestored: (documentId) =>\n runInBackground(relay(c.env, documentId).startOver(documentId)),\n onDocumentTakenDown: (documentId) =>\n runInBackground(relay(c.env, documentId).closeDocument(documentId)),\n onDocumentVersionsChanged: (documentId) =>\n runInBackground(relay(c.env, documentId).announceVersions(documentId)),\n onDocumentCommentsChanged: (documentId, threadId) =>\n runInBackground(relay(c.env, documentId).announceComments(documentId, threadId)),\n runInBackground,\n reportError: services.reporter,\n forwardedRequestId: cloudflareRayId\n })\n return await createCloudServer(app, {\n site: assetSiteFiles(c.env.ASSETS),\n indexingPolicy: config.indexingPolicy,\n reportError: services.reporter\n }).fetch(c.req.raw)\n } finally {\n services.finish()\n }\n })\n\n const worker: ExportedHandler<CloudflareCloudEnvironment> = {\n fetch: (request, env, context) =>\n inMaintenance(env) ? maintenanceResponse(request) : router.fetch(request, env, context),\n\n async scheduled(_controller, env, context) {\n if (inMaintenance(env)) return\n try {\n await runScheduled(await prepare(env), env, context)\n } catch (error) {\n await reportCloudError(reporter(), 'Scheduled run failed', error, { source: 'scheduled' })\n throw error\n }\n }\n }\n\n return { worker, CollaborationRelayObject: createCloudflareRelayObject(prepare) }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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