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

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 (206) 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 +296 -27
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +649 -295
  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 +331 -21
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1773 -32
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3478 -288
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +48 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +466 -13
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +35 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +447 -290
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +89 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +15667 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +2963 -294
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +3473 -842
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +12187 -8244
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +7739 -3548
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +5 -5
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +22 -5
  42. package/src/admin/audit/service.ts +2 -2
  43. package/src/admin/documents/service.ts +76 -6
  44. package/src/admin/reports/service.ts +7 -1
  45. package/src/client/api.ts +23 -471
  46. package/src/client/auth/client.ts +22 -3
  47. package/src/client/billing.ts +80 -0
  48. package/src/client/community.ts +40 -0
  49. package/src/client/discovery.ts +35 -9
  50. package/src/client/documents.ts +160 -0
  51. package/src/client/index.ts +7 -0
  52. package/src/client/portal/account.ts +54 -2
  53. package/src/client/portal/request.ts +2 -0
  54. package/src/client/response.ts +21 -0
  55. package/src/client/schema.ts +8 -0
  56. package/src/client/services.ts +23 -18
  57. package/src/client/sharing.ts +262 -0
  58. package/src/client/versions.ts +104 -0
  59. package/src/contract/account.ts +50 -0
  60. package/src/contract/billing.ts +166 -0
  61. package/src/contract/collaboration.ts +5 -0
  62. package/src/contract/community.ts +60 -0
  63. package/src/contract/discovery.ts +63 -2
  64. package/src/contract/entitlements.ts +10 -0
  65. package/src/contract/index.ts +54 -5
  66. package/src/contract/links.ts +57 -4
  67. package/src/contract/locale.ts +27 -0
  68. package/src/contract/portal.ts +12 -1
  69. package/src/contract/routes.ts +10 -0
  70. package/src/contract/services.ts +18 -16
  71. package/src/email/i18n.ts +174 -0
  72. package/src/email/index.ts +13 -2
  73. package/src/email/locales/ar.json +141 -0
  74. package/src/email/locales/de.json +141 -0
  75. package/src/email/locales/es.json +141 -0
  76. package/src/email/locales/fr.json +141 -0
  77. package/src/email/locales/it.json +141 -0
  78. package/src/email/locales/ja.json +141 -0
  79. package/src/email/locales/pl.json +141 -0
  80. package/src/email/locales/pt-br.json +141 -0
  81. package/src/email/locales/ru.json +141 -0
  82. package/src/email/locales/zh-cn.json +141 -0
  83. package/src/email/messages.ts +200 -0
  84. package/src/email/render.ts +142 -276
  85. package/src/email/samples.ts +115 -0
  86. package/src/email/schema.ts +70 -6
  87. package/src/email/templates/BrandEmail.vue +54 -0
  88. package/src/email/templates/DocumentBlocked.vue +45 -0
  89. package/src/email/templates/DocumentInvitation.vue +24 -0
  90. package/src/email/templates/DocumentReport.vue +32 -0
  91. package/src/email/templates/DocumentReportDecided.vue +36 -0
  92. package/src/email/templates/DocumentReportReceived.vue +18 -0
  93. package/src/email/templates/DocumentRestored.vue +24 -0
  94. package/src/email/templates/EmailChangeRequested.vue +24 -0
  95. package/src/email/templates/EmailRoot.vue +19 -0
  96. package/src/email/templates/EmailText.vue +9 -0
  97. package/src/email/templates/EmailVerification.vue +38 -0
  98. package/src/email/templates/EnrollmentNotification.vue +24 -0
  99. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  100. package/src/email/templates/NewSignIn.vue +37 -0
  101. package/src/email/templates/PasswordChanged.vue +22 -0
  102. package/src/email/templates/PasswordReset.vue +23 -0
  103. package/src/email/templates/StorageLimitReached.vue +28 -0
  104. package/src/email/templates/TwoStepChanged.vue +32 -0
  105. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  106. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  107. package/src/email/templates/brand.ts +9 -61
  108. package/src/email/templates/localization.ts +17 -0
  109. package/src/errors/index.ts +6 -0
  110. package/src/global.d.ts +7 -0
  111. package/src/runtime/cloudflare/relay/index.ts +7 -1
  112. package/src/runtime/cloudflare/tsconfig.json +2 -1
  113. package/src/runtime/cloudflare/worker.ts +8 -1
  114. package/src/runtime/node/cleanup.ts +5 -1
  115. package/src/runtime/node/email/transport.ts +13 -10
  116. package/src/runtime/node/main.ts +1 -1
  117. package/src/runtime/node/server.ts +12 -2
  118. package/src/runtime/node/services/main.ts +1 -1
  119. package/src/runtime/posthog/errors.ts +2 -1
  120. package/src/runtime/s3/objects.ts +17 -0
  121. package/src/runtime/site/community.ts +101 -0
  122. package/src/runtime/site/server.ts +17 -1
  123. package/src/server/account/deletion.ts +2 -0
  124. package/src/server/account/routes.ts +271 -240
  125. package/src/server/account/tokens.ts +57 -0
  126. package/src/server/api/router.ts +23 -0
  127. package/src/server/app/checks.ts +84 -0
  128. package/src/server/app/editors.ts +20 -0
  129. package/src/server/app/index.ts +128 -0
  130. package/src/server/app/indexing.ts +40 -0
  131. package/src/server/app/limiters.ts +53 -0
  132. package/src/server/app/routes.ts +114 -0
  133. package/src/server/app/services.ts +185 -0
  134. package/src/server/auth/access-tokens.ts +62 -0
  135. package/src/server/auth/adapter.ts +21 -1
  136. package/src/server/auth/email.ts +4 -1
  137. package/src/server/auth/enrollment.ts +116 -0
  138. package/src/server/auth/factory.ts +88 -131
  139. package/src/server/auth/logger.ts +23 -0
  140. package/src/server/auth/mfa-assurance.ts +51 -0
  141. package/src/server/auth/passwords.ts +43 -0
  142. package/src/server/auth/session.ts +2 -0
  143. package/src/server/billing/index.ts +6 -0
  144. package/src/server/billing/routes.ts +27 -0
  145. package/src/server/billing/tokens.ts +37 -0
  146. package/src/server/cleanup/configured.ts +16 -3
  147. package/src/server/cleanup/worker.ts +10 -1
  148. package/src/server/collaboration/relay/hub.ts +25 -142
  149. package/src/server/collaboration/relay/room.ts +154 -0
  150. package/src/server/collaboration/service.ts +21 -2
  151. package/src/server/community/index.ts +2 -0
  152. package/src/server/community/routes.ts +93 -0
  153. package/src/server/community/service.ts +134 -0
  154. package/src/server/config/deployment.ts +17 -5
  155. package/src/server/config/index.ts +1 -1
  156. package/src/server/config/public.ts +7 -1
  157. package/src/server/config/schema.ts +40 -292
  158. package/src/server/config/toml/schema.ts +307 -0
  159. package/src/server/db/index.ts +1 -0
  160. package/src/server/db/migrate.ts +13 -1
  161. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  162. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  163. package/src/server/db/migrations/011_account_ids.ts +30 -0
  164. package/src/server/db/migrations/012_email_locales.ts +34 -0
  165. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  166. package/src/server/db/migrations/014_report_replies.ts +28 -0
  167. package/src/server/db/migrations/schema.ts +26 -1
  168. package/src/server/db/tables.ts +30 -1
  169. package/src/server/db/users.ts +22 -0
  170. package/src/server/documents/index.ts +1 -1
  171. package/src/server/documents/limits.ts +7 -1
  172. package/src/server/documents/service.ts +12 -402
  173. package/src/server/documents/uploads.ts +450 -0
  174. package/src/server/documents/versions/service.ts +81 -24
  175. package/src/server/email/invitations.ts +1 -0
  176. package/src/server/email/service.ts +31 -4
  177. package/src/server/email/types.ts +12 -0
  178. package/src/server/errors/index.ts +1 -9
  179. package/src/server/index.ts +12 -5
  180. package/src/server/invitations/types.ts +5 -1
  181. package/src/server/objects/types.ts +5 -0
  182. package/src/server/policy/configured.ts +9 -3
  183. package/src/server/policy/database.ts +13 -2
  184. package/src/server/policy/policy.ts +39 -12
  185. package/src/server/policy/service.ts +71 -52
  186. package/src/server/policy/storage.ts +33 -0
  187. package/src/server/quota/index.ts +6 -0
  188. package/src/server/quota/notices.ts +121 -0
  189. package/src/server/quota/storage.ts +5 -0
  190. package/src/server/rate-limit/middleware.ts +4 -0
  191. package/src/server/reports/index.ts +1 -0
  192. package/src/server/reports/replies.ts +55 -0
  193. package/src/server/reports/routes.ts +3 -1
  194. package/src/server/reports/service.ts +24 -2
  195. package/src/server/sharing/capabilities/service.ts +2 -3
  196. package/src/server/sharing/invitations/service.ts +14 -4
  197. package/src/server/validation.ts +3 -0
  198. package/src/server/workspaces/members.ts +7 -19
  199. package/src/services/app.ts +1 -3
  200. package/src/services/config.ts +1 -0
  201. package/src/services/usage.ts +6 -14
  202. package/src/email/templates/document-invitation.ts +0 -35
  203. package/src/email/templates/enrollment.ts +0 -27
  204. package/src/email/templates/layout.ts +0 -18
  205. package/src/server/app.ts +0 -453
  206. /package/src/{server/errors → errors}/posthog.ts +0 -0
@@ -1,10 +1,9 @@
1
+ import type { ErrorReportContext, ErrorReporter } from '#cloud/errors'
1
2
  import { loggedError, writeJSONLine, type CloudLogWriter } from '#cloud/server/logging'
2
3
  import type { Context, ErrorHandler } from 'hono'
3
4
  import { HTTPException } from 'hono/http-exception'
4
5
  import { routePath } from 'hono/route'
5
6
 
6
- import type { ErrorReportContext, ErrorReporter } from './posthog'
7
-
8
7
  /** Where the server caught an error. */
9
8
  export const CLOUD_ERROR_SOURCES = [
10
9
  'request',
@@ -90,10 +89,3 @@ export function cloudErrorHandler(reporter: CloudErrorReporter | undefined): Err
90
89
  return context.text('Internal Server Error', 500)
91
90
  }
92
91
  }
93
-
94
- export {
95
- createPostHogErrorReporter,
96
- type ErrorReportContext,
97
- type ErrorReporter,
98
- type PostHogErrorReporterOptions
99
- } from './posthog'
@@ -19,6 +19,13 @@ export {
19
19
  type EnrollmentService,
20
20
  type EnrollmentStatus
21
21
  } from '#cloud/admin'
22
+ export {
23
+ createBillingRoutes,
24
+ createBillingTokenService,
25
+ type BillingRouteEnvironment,
26
+ type BillingTokenService,
27
+ type BillingTokenServiceOptions
28
+ } from '#cloud/server/billing'
22
29
  export {
23
30
  ServicesNotEntitledError,
24
31
  createServicesRoutes,
@@ -197,11 +204,7 @@ export {
197
204
  reportCloudError,
198
205
  type CloudErrorContext,
199
206
  type CloudErrorReporter,
200
- type CloudErrorSource,
201
- createPostHogErrorReporter,
202
- type ErrorReportContext,
203
- type ErrorReporter,
204
- type PostHogErrorReporterOptions
207
+ type CloudErrorSource
205
208
  } from './errors'
206
209
  export {
207
210
  cloudRequestId,
@@ -282,9 +285,13 @@ export {
282
285
  type StaticEntitlementsInput
283
286
  } from './policy'
284
287
  export {
288
+ createStorageLimitNoticeService,
285
289
  createStorageQuotaService,
286
290
  createStorageReconciliationService,
287
291
  StorageQuotaExceededError,
292
+ type StorageLimitNoticeOptions,
293
+ type StorageLimitNoticeResult,
294
+ type StorageLimitNoticeService,
288
295
  type StorageQuotaService,
289
296
  type StorageQuotaSnapshot,
290
297
  type StorageReconciliation
@@ -1,11 +1,15 @@
1
1
  import type { DocumentPermission } from '#cloud/contract'
2
+ import type { EmailLocale } from '#cloud/email'
2
3
  import type { CloudDatabase } from '#cloud/server/db'
3
4
  import type { Transaction } from 'kysely'
4
5
 
5
6
  export type DocumentInvitationMessage = {
6
7
  deliveryId: string
7
8
  recipientEmail: string
8
- inviterName: string
9
+ /** The language the invitation is written in. */
10
+ locale: EmailLocale
11
+ /** Null when the inviter's account is gone, so the email says someone invited you. */
12
+ inviterName: string | null
9
13
  documentName: string
10
14
  permission: DocumentPermission
11
15
  expiresAt: string
@@ -90,4 +90,9 @@ export interface ObjectStore {
90
90
  write(input: WriteObjectInput): Promise<void>
91
91
  /** The bytes stored under `key`, or null when there are none. */
92
92
  read(key: string): Promise<Uint8Array | null>
93
+ /**
94
+ * Bytes `start` up to `endExclusive` of the object under `key`, or null when there is none:
95
+ * enough of a large stored file to read one part of it, such as a document's thumbnail.
96
+ */
97
+ readRange(key: string, start: number, endExclusive: number): Promise<Uint8Array | null>
93
98
  }
@@ -8,16 +8,22 @@ import { createDefaultCloudPolicy } from './policy'
8
8
  import { EntitlementOpenFeatureProvider } from './provider'
9
9
  import { staticEntitlementValues } from './static'
10
10
 
11
- /** The policy a deployment configures: its static entitlements, or the database's. */
11
+ /**
12
+ * The policy a deployment configures: its static entitlements, or the database's, over the
13
+ * defaults an account without stored entitlements takes.
14
+ */
12
15
  export function createConfiguredCloudPolicy(
13
- config: Pick<CloudServerConfig, 'staticEntitlements'>,
16
+ config: Pick<CloudServerConfig, 'staticEntitlements' | 'defaultEntitlements'>,
14
17
  database: Kysely<CloudDatabase>
15
18
  ) {
16
19
  return createDefaultCloudPolicy(
17
20
  new EntitlementOpenFeatureProvider(
18
21
  config.staticEntitlements
19
22
  ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
20
- : new DatabaseEntitlementSource(database)
23
+ : new DatabaseEntitlementSource(
24
+ database,
25
+ config.defaultEntitlements ? staticEntitlementValues(config.defaultEntitlements) : {}
26
+ )
21
27
  )
22
28
  )
23
29
  }
@@ -6,8 +6,15 @@ import type { EntitlementSource, EntitlementSubject } from './entitlements'
6
6
  import { staticEntitlementsSchema } from './schema'
7
7
  import { staticEntitlementValues, type StaticEntitlementsInput } from './static'
8
8
 
9
+ /**
10
+ * Each account's stored entitlements, value by value over `defaults`: what an account takes until
11
+ * billing or an operator stores its own, and whatever a stored plan leaves out.
12
+ */
9
13
  export class DatabaseEntitlementSource implements EntitlementSource {
10
- constructor(private readonly database: Kysely<CloudDatabase>) {}
14
+ constructor(
15
+ private readonly database: Kysely<CloudDatabase>,
16
+ private readonly defaults: Record<string, boolean | number> = {}
17
+ ) {}
11
18
 
12
19
  private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {
13
20
  if (subject.type !== 'user') return {}
@@ -16,7 +23,11 @@ export class DatabaseEntitlementSource implements EntitlementSource {
16
23
  .select('values')
17
24
  .where('userId', '=', subject.id)
18
25
  .executeTakeFirst()
19
- return row ? staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values)) : {}
26
+ if (!row) return this.defaults
27
+ return {
28
+ ...this.defaults,
29
+ ...staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values))
30
+ }
20
31
  }
21
32
 
22
33
  async boolean(subject: EntitlementSubject, key: string): Promise<boolean | null> {
@@ -1,6 +1,8 @@
1
1
  import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'
2
2
  import {
3
3
  DefaultLogger,
4
+ ErrorCode,
5
+ OpenFeatureError,
4
6
  TypedInMemoryProvider,
5
7
  type EvaluationContext,
6
8
  type Provider,
@@ -69,11 +71,24 @@ const logger = new DefaultLogger()
69
71
 
70
72
  /** A flag's value, or the default when the provider failed or reported an error, as a client does. */
71
73
  async function resolved<T>(evaluation: () => Promise<ResolutionDetails<T>>, defaultValue: T) {
74
+ return (await resolution(evaluation, defaultValue)).value
75
+ }
76
+
77
+ /**
78
+ * A flag's value, and whether the provider failed to answer. A flag it doesn't know is no failure:
79
+ * the default stands for it, as for a plan that sets no value.
80
+ */
81
+ async function resolution<T>(
82
+ evaluation: () => Promise<ResolutionDetails<T>>,
83
+ defaultValue: T
84
+ ): Promise<{ value: T; failed: boolean }> {
72
85
  try {
73
86
  const details = await evaluation()
74
- return details.errorCode ? defaultValue : details.value
75
- } catch {
76
- return defaultValue
87
+ if (!details.errorCode) return { value: details.value, failed: false }
88
+ return { value: defaultValue, failed: details.errorCode !== ErrorCode.FLAG_NOT_FOUND }
89
+ } catch (error) {
90
+ const unknown = error instanceof OpenFeatureError && error.code === ErrorCode.FLAG_NOT_FOUND
91
+ return { value: defaultValue, failed: !unknown }
77
92
  }
78
93
  }
79
94
 
@@ -100,15 +115,27 @@ export class CloudPolicy {
100
115
  }
101
116
 
102
117
  number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {
103
- return resolved(
104
- () =>
105
- this.provider.resolveNumberEvaluation(
106
- key,
107
- defaultValue,
108
- evaluationContext(context),
109
- logger
110
- ),
111
- defaultValue
118
+ return resolved(() => this.evaluateNumber(key, defaultValue, context), defaultValue)
119
+ }
120
+
121
+ /**
122
+ * Like `number`, and says whether the provider failed to answer, for a caller that must not
123
+ * take the default for an answer, such as one that undoes something when a limit is gone.
124
+ */
125
+ numberResolution(
126
+ key: string,
127
+ defaultValue: number,
128
+ context: CloudPolicyContext
129
+ ): Promise<{ value: number; failed: boolean }> {
130
+ return resolution(() => this.evaluateNumber(key, defaultValue, context), defaultValue)
131
+ }
132
+
133
+ private evaluateNumber(key: string, defaultValue: number, context: CloudPolicyContext) {
134
+ return this.provider.resolveNumberEvaluation(
135
+ key,
136
+ defaultValue,
137
+ evaluationContext(context),
138
+ logger
112
139
  )
113
140
  }
114
141
  }
@@ -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
+ }
@@ -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
1
  import { parseFileDocumentReport } 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'
@@ -22,7 +23,8 @@ export function createPublicReportRoutes(
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
  })