@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
@@ -1,11 +1,11 @@
1
- import type { WorkspaceEntitlements } from '#cloud/contract'
1
+ import type { AccountEntitlements, WorkspaceEntitlements } from '#cloud/contract'
2
2
  import type { CloudDatabase } from '#cloud/server/db'
3
3
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
4
4
  import { workspaceRole } from '#cloud/server/documents/repository'
5
- import { createStorageQuotaService } from '#cloud/server/quota'
5
+ import { createStorageQuotaService, type StorageQuotaSnapshot } from '#cloud/server/quota'
6
6
  import type { Kysely } from 'kysely'
7
7
 
8
- import { CLOUD_FEATURE_KEYS } from './keys'
8
+ import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'
9
9
  import type { CloudPolicy } from './policy'
10
10
  import { workspacePolicyContext } from './workspace'
11
11
 
@@ -17,6 +17,7 @@ export function createEntitlementService(
17
17
  ) {
18
18
  const quota = createStorageQuotaService(database)
19
19
  return {
20
+ /** A workspace's entitlements: its owner's plan and pooled storage, for any member to read. */
20
21
  async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {
21
22
  if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()
22
23
  const context = await workspacePolicyContext(
@@ -25,64 +26,82 @@ export function createEntitlementService(
25
26
  { actorId: userId, deploymentMode: 'self-hosted' }
26
27
  )
27
28
  if (!context) throw new DocumentNotFoundError()
28
- const [
29
+ const [entitlements, usage] = await Promise.all([
30
+ resolve(context),
31
+ quota.snapshot(workspaceId)
32
+ ])
33
+ // The workspace may have gone since its role was read; it has no usage to report then.
34
+ if (!usage) throw new DocumentNotFoundError()
35
+ return { ...entitlements, usage: storageUsage(usage) }
36
+ },
37
+
38
+ /** The signed-in account's own plan, and the storage its workspaces hold together. */
39
+ async account(userId: string): Promise<AccountEntitlements> {
40
+ const [entitlements, usage] = await Promise.all([
41
+ resolve({
42
+ targetingKey: userId,
43
+ subjectType: 'user',
44
+ actorId: userId,
45
+ deploymentMode: 'self-hosted'
46
+ }),
47
+ quota.account(userId)
48
+ ])
49
+ return { ...entitlements, usage: storageUsage(usage) }
50
+ }
51
+ }
52
+
53
+ async function resolve(
54
+ context: CloudPolicyContext
55
+ ): Promise<Omit<WorkspaceEntitlements, 'usage'>> {
56
+ const [
57
+ links,
58
+ guestView,
59
+ guestEdit,
60
+ guestPresence,
61
+ collaboration,
62
+ revisionHistory,
63
+ cloudServices,
64
+ maximumFileBytes,
65
+ maximumStorage,
66
+ maximumParticipants,
67
+ monthlyCreditAllowance
68
+ ] = await Promise.all([
69
+ policy.boolean(CLOUD_FEATURE_KEYS.links, false, context),
70
+ policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),
71
+ policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context),
72
+ policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),
73
+ policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),
74
+ policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),
75
+ policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),
76
+ policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),
77
+ policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),
78
+ policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, technicalMaximumParticipants, context),
79
+ policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)
80
+ ])
81
+ // Technical limits are ceilings: an entitlement can lower them but never raise them.
82
+ const participants = Math.min(technicalMaximumParticipants, maximumParticipants)
83
+ return {
84
+ features: {
29
85
  links,
30
86
  guestView,
31
87
  guestEdit,
32
88
  guestPresence,
33
89
  collaboration,
34
90
  revisionHistory,
35
- cloudServices,
36
- maximumFileBytes,
37
- maximumStorage,
38
- maximumParticipants,
39
- monthlyCreditAllowance,
40
- usage
41
- ] = await Promise.all([
42
- policy.boolean(CLOUD_FEATURE_KEYS.links, false, context),
43
- policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),
44
- policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context),
45
- policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),
46
- policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),
47
- policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),
48
- policy.boolean(CLOUD_FEATURE_KEYS.cloudServices, false, context),
49
- policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),
50
- policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),
51
- policy.number(
52
- CLOUD_FEATURE_KEYS.maximumParticipants,
53
- technicalMaximumParticipants,
54
- context
55
- ),
56
- policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context),
57
- quota.snapshot(workspaceId)
58
- ])
59
- // The workspace may have gone since its role was read; it has no usage to report then.
60
- if (!usage) throw new DocumentNotFoundError()
61
- // Technical limits are ceilings: an entitlement can lower them but never raise them.
62
- const participants = Math.min(technicalMaximumParticipants, maximumParticipants)
63
- return {
64
- features: {
65
- links,
66
- guestView,
67
- guestEdit,
68
- guestPresence,
69
- collaboration,
70
- revisionHistory,
71
- cloudServices
72
- },
73
- limits: {
74
- maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),
75
- maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,
76
- maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,
77
- monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance
78
- },
79
- usage: {
80
- committedStorageBytes: usage.committedBytes,
81
- reservedStorageBytes: usage.reservedBytes
82
- }
91
+ cloudServices
92
+ },
93
+ limits: {
94
+ maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),
95
+ maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,
96
+ maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,
97
+ monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance
83
98
  }
84
99
  }
85
100
  }
86
101
  }
87
102
 
103
+ function storageUsage(usage: StorageQuotaSnapshot): WorkspaceEntitlements['usage'] {
104
+ return { committedStorageBytes: usage.committedBytes, reservedStorageBytes: usage.reservedBytes }
105
+ }
106
+
88
107
  export type EntitlementService = ReturnType<typeof createEntitlementService>
@@ -0,0 +1,33 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import { createStorageQuotaService } from '#cloud/server/quota'
3
+ import type { Kysely } from 'kysely'
4
+
5
+ import { CLOUD_FEATURE_KEYS } from './keys'
6
+ import type { CloudPolicy } from './policy'
7
+ import { workspacePolicyContext } from './workspace'
8
+
9
+ /**
10
+ * Whether the owner of a workspace, or of a document's workspace, holds as much as their plan's
11
+ * storage allows or more. Their workspaces are then read-only until they free space or their plan
12
+ * grows: documents open and download, and can be deleted, but take no edits, uploads, or new
13
+ * documents. A plan that shrinks below what an account holds, as when a subscription lapses,
14
+ * reaches this the same way as filling it.
15
+ */
16
+ export async function storageLimitReached(
17
+ database: Kysely<CloudDatabase>,
18
+ policy: CloudPolicy | undefined,
19
+ target: { workspaceId: string } | { documentId: string },
20
+ deploymentMode: 'official' | 'self-hosted' = 'self-hosted'
21
+ ): Promise<boolean> {
22
+ if (!policy) return false
23
+ const context = await workspacePolicyContext(database, target, { deploymentMode })
24
+ if (!context) return false
25
+ const maximum = await policy.number(
26
+ CLOUD_FEATURE_KEYS.maximumStorageBytes,
27
+ Number.MAX_SAFE_INTEGER,
28
+ context
29
+ )
30
+ if (maximum === Number.MAX_SAFE_INTEGER) return false
31
+ const usage = await createStorageQuotaService(database).snapshot(context.workspaceId)
32
+ return usage !== null && usage.committedBytes >= maximum
33
+ }
@@ -5,6 +5,9 @@ import type { CloudPolicyContext } from './keys'
5
5
 
6
6
  type WorkspacePolicyTarget = { workspaceId: string } | { documentId: string }
7
7
 
8
+ /** A policy context for a workspace, which names it. */
9
+ type WorkspacePolicyContext = CloudPolicyContext & { workspaceId: string }
10
+
8
11
  /**
9
12
  * The policy context for a workspace, or for a document by its workspace: its owner's plan, which
10
13
  * every workspace they own takes, so creating more workspaces adds no allowance. Null when the
@@ -14,7 +17,7 @@ export async function workspacePolicyContext(
14
17
  database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
15
18
  target: WorkspacePolicyTarget,
16
19
  context: Pick<CloudPolicyContext, 'actorId' | 'deploymentMode'>
17
- ): Promise<(CloudPolicyContext & { workspaceId: string }) | null> {
20
+ ): Promise<WorkspacePolicyContext | null> {
18
21
  const row =
19
22
  'documentId' in target
20
23
  ? await database
@@ -29,7 +32,7 @@ export async function workspacePolicyContext(
29
32
  .where('id', '=', target.workspaceId)
30
33
  .executeTakeFirst()
31
34
  if (!row) return null
32
- const policyContext: CloudPolicyContext & { workspaceId: string } = {
35
+ const policyContext: WorkspacePolicyContext = {
33
36
  targetingKey: row.ownerId,
34
37
  subjectType: 'user',
35
38
  workspaceId: row.workspaceId,
@@ -1,3 +1,9 @@
1
+ export {
2
+ createStorageLimitNoticeService,
3
+ type StorageLimitNoticeOptions,
4
+ type StorageLimitNoticeResult,
5
+ type StorageLimitNoticeService
6
+ } from './notices'
1
7
  export { createStorageReconciliationService, type StorageReconciliation } from './reconcile'
2
8
  export {
3
9
  createStorageQuotaService,
@@ -0,0 +1,121 @@
1
+ import { CLOUD_ACCOUNT_PLAN_PATH } from '#cloud/contract'
2
+ import type { CloudDatabase } from '#cloud/server/db'
3
+ import type { TransactionalEmailService } from '#cloud/server/email'
4
+ import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
5
+ import type { CloudPolicy } from '#cloud/server/policy/policy'
6
+ import type { Kysely } from 'kysely'
7
+
8
+ export type StorageLimitNoticeResult = {
9
+ /** Accounts told this pass that their storage is full. */
10
+ notified: number
11
+ /** Accounts back under their plan, which are told again if they fill it again. */
12
+ cleared: number
13
+ }
14
+
15
+ export type StorageLimitNoticeOptions = {
16
+ policy: CloudPolicy
17
+ email: TransactionalEmailService
18
+ publicURL: string
19
+ /** Whether the server sells plans, so the email offers more storage. */
20
+ upgradable: boolean
21
+ deploymentMode: 'official' | 'self-hosted'
22
+ }
23
+
24
+ /**
25
+ * Emails each account once when it holds all the storage its plan allows, which makes its
26
+ * workspaces read-only (`storageLimitReached`), whether it filled its plan or its plan shrank below
27
+ * what it holds, as when a subscription lapses. A pass compares every owner's committed storage
28
+ * with their plan, so it reaches both however the plan changed.
29
+ */
30
+ export function createStorageLimitNoticeService(
31
+ database: Kysely<CloudDatabase>,
32
+ options: StorageLimitNoticeOptions
33
+ ) {
34
+ /**
35
+ * Each account's limit: a number, null when its plan sets none, or undefined when the policy
36
+ * failed to answer, which decides nothing either way until a pass where it answers.
37
+ */
38
+ async function limit(userId: string): Promise<number | null | undefined> {
39
+ const maximum = await options.policy.numberResolution(
40
+ CLOUD_FEATURE_KEYS.maximumStorageBytes,
41
+ Number.MAX_SAFE_INTEGER,
42
+ { targetingKey: userId, subjectType: 'user', deploymentMode: options.deploymentMode }
43
+ )
44
+ if (maximum.failed) return undefined
45
+ return maximum.value === Number.MAX_SAFE_INTEGER ? null : maximum.value
46
+ }
47
+
48
+ async function notify(userId: string, usedBytes: number, limitBytes: number): Promise<boolean> {
49
+ return database.transaction().execute(async (transaction) => {
50
+ const notice = await transaction
51
+ .insertInto('storageLimitNotice')
52
+ .values({ userId })
53
+ .onConflict((conflict) => conflict.column('userId').doNothing())
54
+ .returning('notifiedAt')
55
+ .executeTakeFirst()
56
+ if (!notice) return false
57
+ const user = await transaction
58
+ .selectFrom('user')
59
+ .select(['name', 'email'])
60
+ .where('id', '=', userId)
61
+ .executeTakeFirst()
62
+ if (!user) return false
63
+ await options.email.enqueue(
64
+ {
65
+ idempotencyKey: `storage-limit-reached/${userId}/${new Date(notice.notifiedAt).getTime()}`,
66
+ kind: 'storage-limit-reached',
67
+ recipientEmail: user.email,
68
+ payload: {
69
+ name: user.name,
70
+ usedBytes,
71
+ limitBytes,
72
+ upgradable: options.upgradable,
73
+ actionURL: new URL(
74
+ options.upgradable ? CLOUD_ACCOUNT_PLAN_PATH : '/',
75
+ options.publicURL
76
+ ).href
77
+ }
78
+ },
79
+ transaction
80
+ )
81
+ return true
82
+ })
83
+ }
84
+
85
+ return {
86
+ async notifyStorageLimits(): Promise<StorageLimitNoticeResult> {
87
+ const [owners, notices] = await Promise.all([
88
+ database
89
+ .selectFrom('workspace')
90
+ .innerJoin('workspaceStorageUsage', 'workspaceStorageUsage.workspaceId', 'workspace.id')
91
+ .select((expression) => [
92
+ 'workspace.ownerId',
93
+ expression.fn.sum<string | number>('workspaceStorageUsage.committedBytes').as('bytes')
94
+ ])
95
+ .groupBy('workspace.ownerId')
96
+ .execute(),
97
+ database.selectFrom('storageLimitNotice').select('userId').execute()
98
+ ])
99
+ const usage = new Map(owners.map((owner) => [owner.ownerId, Number(owner.bytes)]))
100
+ const result: StorageLimitNoticeResult = { notified: 0, cleared: 0 }
101
+ for (const [userId, usedBytes] of usage) {
102
+ const limitBytes = await limit(userId)
103
+ if (typeof limitBytes === 'number' && usedBytes >= limitBytes) {
104
+ if (await notify(userId, usedBytes, limitBytes)) result.notified++
105
+ }
106
+ }
107
+ // A notice whose account holds less than its plan allows again, or nothing at all, is done.
108
+ for (const { userId } of notices) {
109
+ const usedBytes = usage.get(userId) ?? 0
110
+ const limitBytes = await limit(userId)
111
+ if (limitBytes === undefined) continue
112
+ if (limitBytes !== null && usedBytes >= limitBytes) continue
113
+ await database.deleteFrom('storageLimitNotice').where('userId', '=', userId).execute()
114
+ result.cleared++
115
+ }
116
+ return result
117
+ }
118
+ }
119
+ }
120
+
121
+ export type StorageLimitNoticeService = ReturnType<typeof createStorageLimitNoticeService>
@@ -159,6 +159,11 @@ export function createStorageQuotaService(database: Kysely<CloudDatabase>) {
159
159
  return ownerId === null ? null : usage(database, ownerId)
160
160
  },
161
161
 
162
+ /** What `ownerId` holds and has reserved across every workspace they own. */
163
+ async account(ownerId: string): Promise<StorageQuotaSnapshot> {
164
+ return usage(database, ownerId)
165
+ },
166
+
162
167
  async reserve(input: {
163
168
  workspaceId: string
164
169
  uploadId: string
@@ -23,6 +23,9 @@ export type ResourceRateLimitPolicy = RateLimitPolicy & { actorLimit: number }
23
23
 
24
24
  export const CLOUD_RATE_LIMITS = {
25
25
  publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },
26
+ // Everything one visitor reads of the community gallery, across its paths: a page of thumbnails
27
+ // fits, made-up addresses do not each get a fresh budget.
28
+ communityRead: { namespace: 'community-read', windowMs: 60_000, limit: 300 },
26
29
  collaborationTicket: {
27
30
  namespace: 'collaboration-ticket',
28
31
  windowMs: 60_000,
@@ -45,6 +48,7 @@ export const CLOUD_RATE_LIMITS = {
45
48
  uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120, actorLimit: 600 },
46
49
  authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },
47
50
  servicesToken: { namespace: 'services-token', windowMs: 60_000, limit: 30 },
51
+ billingToken: { namespace: 'billing-token', windowMs: 60_000, limit: 30 },
48
52
  adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },
49
53
  adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
50
54
  } as const satisfies Record<string, RateLimitPolicy | ResourceRateLimitPolicy>
@@ -1,3 +1,4 @@
1
+ export { tellReporters, type ReportReplies } from './replies'
1
2
  export { createPublicReportRoutes } from './routes'
2
3
  export {
3
4
  createDocumentReportService,
@@ -0,0 +1,55 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import type { TransactionalEmailService } from '#cloud/server/email'
3
+ import type { Transaction } from 'kysely'
4
+
5
+ /** How reporters hear back: through email, with the deployment's abuse address to disagree. */
6
+ export type ReportReplies = {
7
+ email?: TransactionalEmailService
8
+ /** Where a reporter writes to disagree with a decision: the deployment's abuse address. */
9
+ contactEmail?: string
10
+ }
11
+
12
+ /**
13
+ * Tells each reporter who left an address what the administrators decided about their report:
14
+ * the document blocked, the report acted on some other way, or the document left as it was. Only
15
+ * 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
16
+ * decides it, so a decision that rolls back tells nobody.
17
+ */
18
+ export async function tellReporters(
19
+ transaction: Transaction<CloudDatabase>,
20
+ replies: ReportReplies,
21
+ reportIds: readonly string[],
22
+ outcome: 'blocked' | 'actioned' | 'dismissed'
23
+ ): Promise<void> {
24
+ const { email } = replies
25
+ if (!email || reportIds.length === 0) return
26
+ const reports = await transaction
27
+ .selectFrom('documentReport')
28
+ .innerJoin('document', 'document.id', 'documentReport.documentId')
29
+ .select([
30
+ 'documentReport.id',
31
+ 'documentReport.replyEmail',
32
+ 'documentReport.replyLocale',
33
+ 'document.name'
34
+ ])
35
+ .where('documentReport.id', 'in', reportIds)
36
+ .where('documentReport.replyEmail', 'is not', null)
37
+ .execute()
38
+ for (const report of reports) {
39
+ if (!report.replyEmail) continue
40
+ await email.enqueue(
41
+ {
42
+ idempotencyKey: `document-report-decided/${report.id}`,
43
+ kind: 'document-report-decided',
44
+ recipientEmail: report.replyEmail,
45
+ fallbackLocale: report.replyLocale,
46
+ payload: {
47
+ documentName: report.name,
48
+ outcome,
49
+ contactEmail: replies.contactEmail ?? null
50
+ }
51
+ },
52
+ transaction
53
+ )
54
+ }
55
+ }
@@ -1,4 +1,5 @@
1
- import { parseFileDocumentReport } from '#cloud/contract'
1
+ import { fileDocumentReportSchema } from '#cloud/contract'
2
+ import { acceptedLocale } from '#cloud/email'
2
3
  import type { CloudSessionResolver } from '#cloud/server/auth'
3
4
  import { shareActor } from '#cloud/server/sharing/actor'
4
5
  import { sharingRoute } from '#cloud/server/sharing/http'
@@ -15,14 +16,15 @@ export function createPublicReportRoutes(
15
16
  return new Hono().post(
16
17
  '/shares/:shareId/reports',
17
18
  shareParams,
18
- validatedJSON(parseFileDocumentReport),
19
+ validatedJSON(fileDocumentReportSchema),
19
20
  async (context) => {
20
21
  try {
21
22
  return await sharingRoute(context, async () => {
22
23
  await service.file(
23
24
  context.req.valid('param').shareId,
24
25
  context.req.valid('json'),
25
- await shareActor(context.req.raw, resolveSession)
26
+ await shareActor(context.req.raw, resolveSession),
27
+ acceptedLocale(context.req.header('accept-language'))
26
28
  )
27
29
  return context.json({ received: true as const }, 201)
28
30
  })
@@ -1,16 +1,19 @@
1
1
  import type { FileDocumentReportInput } from '#cloud/contract'
2
+ import type { EmailLocale } from '#cloud/email'
2
3
  import type { CloudActor } from '#cloud/server/auth'
3
4
  import type { CloudDatabase } from '#cloud/server/db'
4
5
  import type { TransactionalEmailService } from '#cloud/server/email'
5
6
  import type { DocumentSharingService } from '#cloud/server/sharing'
6
7
  import type { Kysely } from 'kysely'
7
8
 
9
+ import { DAY_MS } from '@open-pencil/std/timing'
10
+
8
11
  /**
9
12
  * How many reports one person, or guest, may file about one link in a day, and how many a link
10
13
  * may gather from everyone, since a guest names themselves and could otherwise flood the queue.
11
14
  */
12
15
  export const DOCUMENT_REPORT_BUDGET = {
13
- windowMs: 24 * 60 * 60 * 1000,
16
+ windowMs: DAY_MS,
14
17
  perReporter: 3,
15
18
  perShare: 50
16
19
  } as const
@@ -41,7 +44,13 @@ export function createDocumentReportService(
41
44
  * tells the deployment's administrators. It answers nothing about the document, so a report
42
45
  * never tells its reporter more than the link already did.
43
46
  */
44
- async file(shareId: string, input: FileDocumentReportInput, actor?: CloudActor): Promise<void> {
47
+ async file(
48
+ shareId: string,
49
+ input: FileDocumentReportInput,
50
+ actor?: CloudActor,
51
+ /** The language the reporter's browser asked for, to reply in without an account's own. */
52
+ replyLocale: EmailLocale | null = null
53
+ ): Promise<void> {
45
54
  const resolved = await options.sharing.resolveShare(
46
55
  shareId,
47
56
  { secret: input.secret, guestId: input.guestId },
@@ -80,6 +89,7 @@ export function createDocumentReportService(
80
89
  throw new DocumentReportLimitError()
81
90
  }
82
91
  const id = crypto.randomUUID()
92
+ const replyEmail = input.replyEmail ?? actor?.email ?? null
83
93
  await transaction
84
94
  .insertInto('documentReport')
85
95
  .values({
@@ -88,7 +98,8 @@ export function createDocumentReportService(
88
98
  shareId,
89
99
  reporterUserId,
90
100
  reporterGuestId,
91
- replyEmail: input.replyEmail ?? actor?.email ?? null,
101
+ replyEmail,
102
+ replyLocale,
92
103
  reason: input.reason,
93
104
  description: input.description
94
105
  })
@@ -99,6 +110,19 @@ export function createDocumentReportService(
99
110
  .select('name')
100
111
  .where('id', '=', resolved.documentId)
101
112
  .executeTakeFirstOrThrow()
113
+ // Whoever left an address hears that the report arrived, and later what was decided.
114
+ if (replyEmail) {
115
+ await options.email.enqueue(
116
+ {
117
+ idempotencyKey: `document-report-received/${id}`,
118
+ kind: 'document-report-received',
119
+ recipientEmail: replyEmail,
120
+ fallbackLocale: replyLocale,
121
+ payload: { documentName: document.name }
122
+ },
123
+ transaction
124
+ )
125
+ }
102
126
  for (const recipientEmail of options.adminRecipients) {
103
127
  await options.email.enqueue(
104
128
  {
@@ -1,4 +1,4 @@
1
- import { parseCreateServicesToken } from '#cloud/contract'
1
+ import { createServicesTokenSchema } from '#cloud/contract'
2
2
  import type { CloudActor } from '#cloud/server/auth'
3
3
  import type { CloudDatabase } from '#cloud/server/db'
4
4
  import { DocumentNotFoundError } from '#cloud/server/documents'
@@ -26,7 +26,7 @@ export function createServicesRoutes(
26
26
  }
27
27
  return router.post(
28
28
  '/services/token',
29
- validatedJSON(parseCreateServicesToken),
29
+ validatedJSON(createServicesTokenSchema),
30
30
  async (context) => {
31
31
  if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)
32
32
  try {
@@ -6,7 +6,7 @@ import type {
6
6
  UpdateDocumentShareInput
7
7
  } from '#cloud/contract'
8
8
  import type { CloudActor } from '#cloud/server/auth'
9
- import type { CloudDatabase } from '#cloud/server/db'
9
+ import { isBannedNow, type CloudDatabase } from '#cloud/server/db'
10
10
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
11
11
  import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
12
12
  import type { CloudPolicy } from '#cloud/server/policy/policy'
@@ -14,7 +14,7 @@ import { workspacePolicyContext } from '#cloud/server/policy/workspace'
14
14
  import type { Kysely, UpdateObject } from 'kysely'
15
15
  import * as v from 'valibot'
16
16
 
17
- import { randomHex } from '@open-pencil/scene-graph/random'
17
+ import { randomHex } from '@open-pencil/std/random'
18
18
 
19
19
  import { advanceCollaborationEpoch, requireSharingAccess } from '../access'
20
20
  import { shareContract } from '../contracts'
@@ -39,8 +39,7 @@ async function anyBanned(database: Kysely<CloudDatabase>, userIds: string[]): Pr
39
39
  .selectFrom('user')
40
40
  .select('id')
41
41
  .where('id', 'in', accounts)
42
- .where('banned', '=', true)
43
- .where((user) => user.or([user('banExpires', 'is', null), user('banExpires', '>', new Date())]))
42
+ .where(isBannedNow)
44
43
  .executeTakeFirst()
45
44
  return banned !== undefined
46
45
  }
@@ -1,4 +1,4 @@
1
- import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'
1
+ import { requestSharedImageLinksSchema, resolveDocumentShareSchema } from '#cloud/contract'
2
2
  import type { CloudSessionResolver } from '#cloud/server/auth'
3
3
  import type { DocumentService } from '#cloud/server/documents'
4
4
  import type { DocumentSharingService } from '#cloud/server/sharing'
@@ -17,7 +17,7 @@ export function createPublicDocumentRoutes(
17
17
  .post(
18
18
  '/shares/:shareId/document',
19
19
  shareParams,
20
- validatedJSON(parseResolveDocumentShare),
20
+ validatedJSON(resolveDocumentShareSchema),
21
21
  (context) =>
22
22
  sharingRoute(context, async () => {
23
23
  const resolution = await sharing.resolveShare(
@@ -34,7 +34,7 @@ export function createPublicDocumentRoutes(
34
34
  .post(
35
35
  '/shares/:shareId/images',
36
36
  shareParams,
37
- validatedJSON(parseRequestSharedImageLinks),
37
+ validatedJSON(requestSharedImageLinksSchema),
38
38
  (context) =>
39
39
  sharingRoute(context, async () => {
40
40
  const { checksums, ...share } = context.req.valid('json')