@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,8 +1,10 @@
1
1
  import { renderTransactionalEmail } from '#cloud/email'
2
- import type { TransactionalEmailKind } from '#cloud/email'
2
+ import type { EmailLocale, TransactionalEmailKind } from '#cloud/email'
3
3
  import type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'
4
4
  import type { Kysely, Transaction } from 'kysely'
5
5
 
6
+ import { backoffDelay, HOUR_MS, SECOND_MS, type Backoff } from '@open-pencil/std/timing'
7
+
6
8
  import { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'
7
9
  import type {
8
10
  EnqueueTransactionalEmailInput,
@@ -13,7 +15,8 @@ import type {
13
15
  } from './types'
14
16
 
15
17
  const DEFAULT_MAXIMUM_ATTEMPTS = 5
16
- const MAXIMUM_RETRY_DELAY_MS = 60 * 60_000
18
+ /** Mail is retried patiently: a provider that refused it is rarely back within seconds. */
19
+ const EMAIL_RETRY: Backoff = { baseMs: 30 * SECOND_MS, capMs: HOUR_MS, jitter: false }
17
20
 
18
21
  export type TransactionalEmailTransportErrorKind =
19
22
  | 'configuration'
@@ -40,6 +43,7 @@ type ClaimedTransactionalEmail = {
40
43
  kind: TransactionalEmailKind
41
44
  recipientEmailNormalized: string
42
45
  payloadEncrypted: string
46
+ locale: EmailLocale
43
47
  attemptCount: number
44
48
  }
45
49
 
@@ -48,7 +52,7 @@ function normalizedEmail(value: string): string {
48
52
  }
49
53
 
50
54
  function retryDelayMilliseconds(attemptCount: number): number {
51
- return Math.min(MAXIMUM_RETRY_DELAY_MS, 2 ** Math.max(0, attemptCount - 1) * 30_000)
55
+ return backoffDelay(attemptCount - 1, EMAIL_RETRY)
52
56
  }
53
57
 
54
58
  function transportFailure(error: unknown): TransactionalEmailTransportError {
@@ -77,6 +81,8 @@ export function createTransactionalEmailService(
77
81
  options: {
78
82
  encryptionSecret: string
79
83
  from: string
84
+ /** Where replies go; mail clients answer `from` without it. */
85
+ replyTo?: string
80
86
  transport?: TransactionalEmailTransport
81
87
  }
82
88
  ): TransactionalEmailService {
@@ -93,14 +99,33 @@ export function createTransactionalEmailService(
93
99
  input.payload
94
100
  )
95
101
  const executor = transaction ?? database
102
+ const recipientEmailNormalized = normalizedEmail(input.recipientEmail)
103
+ // An account is written to in the language it chose, whoever sends to it.
104
+ const recipientLocale =
105
+ input.recipientLocale !== undefined
106
+ ? input.recipientLocale
107
+ : (
108
+ await executor
109
+ .selectFrom('user')
110
+ .select('locale')
111
+ .where((expression) =>
112
+ expression(
113
+ expression.fn('lower', [expression.ref('email')]),
114
+ '=',
115
+ recipientEmailNormalized
116
+ )
117
+ )
118
+ .executeTakeFirst()
119
+ )?.locale
96
120
  const row = await executor
97
121
  .insertInto('transactionalEmail')
98
122
  .values({
99
123
  id,
100
124
  idempotencyKey: input.idempotencyKey,
101
125
  kind: input.kind,
102
- recipientEmailNormalized: normalizedEmail(input.recipientEmail),
126
+ recipientEmailNormalized,
103
127
  payloadEncrypted,
128
+ locale: recipientLocale ?? input.fallbackLocale ?? 'en',
104
129
  status: 'pending',
105
130
  nextAttemptAt: new Date(),
106
131
  claimId: null,
@@ -136,7 +161,14 @@ export function createTransactionalEmailService(
136
161
  const claimed = await database.transaction().execute(async (transaction) => {
137
162
  const candidates = await transaction
138
163
  .selectFrom('transactionalEmail')
139
- .select(['id', 'kind', 'recipientEmailNormalized', 'payloadEncrypted', 'attemptCount'])
164
+ .select([
165
+ 'id',
166
+ 'kind',
167
+ 'recipientEmailNormalized',
168
+ 'payloadEncrypted',
169
+ 'locale',
170
+ 'attemptCount'
171
+ ])
140
172
  .where('payloadEncrypted', 'is not', null)
141
173
  .where((expression) =>
142
174
  expression.or([
@@ -186,10 +218,11 @@ export function createTransactionalEmailService(
186
218
  message.kind,
187
219
  message.payloadEncrypted
188
220
  )
189
- const rendered = await renderTransactionalEmail(content)
221
+ const rendered = await renderTransactionalEmail(content, message.locale)
190
222
  const sent = await options.transport.send({
191
223
  deliveryId: message.id,
192
224
  from: options.from,
225
+ replyTo: options.replyTo,
193
226
  to: message.recipientEmailNormalized,
194
227
  subject: rendered.subject,
195
228
  html: rendered.html,
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ EmailLocale,
2
3
  RenderedTransactionalEmail,
3
4
  TransactionalEmailKind,
4
5
  TransactionalEmailPayloadByKind
@@ -9,6 +10,7 @@ import type { Transaction } from 'kysely'
9
10
  export type TransactionalEmailEnvelope = RenderedTransactionalEmail & {
10
11
  deliveryId: string
11
12
  from: string
13
+ replyTo?: string
12
14
  to: string
13
15
  headers: Record<string, string>
14
16
  }
@@ -28,6 +30,17 @@ export type EnqueueTransactionalEmailInput<Kind extends TransactionalEmailKind>
28
30
  kind: Kind
29
31
  recipientEmail: string
30
32
  payload: TransactionalEmailPayloadByKind[Kind]
33
+ /**
34
+ * The recipient account's own language, when the sender has the account: the email is then
35
+ * written in it, or in English when it has none, without looking the account up. Signing up
36
+ * needs this, since its callbacks run inside its transaction and must not query the database.
37
+ */
38
+ recipientLocale?: EmailLocale | null
39
+ /**
40
+ * The language to write in when the recipient has no account that chose one: the inviter's for
41
+ * an invitation. English otherwise.
42
+ */
43
+ fallbackLocale?: EmailLocale | null
31
44
  }
32
45
 
33
46
  export type TransactionalEmailDeliveryOptions = {
@@ -1,9 +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
- import type { ErrorReportContext, ErrorReporter } from './posthog'
6
+ import * as v from 'valibot'
7
7
 
8
8
  /** Where the server caught an error. */
9
9
  export const CLOUD_ERROR_SOURCES = [
@@ -18,8 +18,10 @@ export const CLOUD_ERROR_SOURCES = [
18
18
  export type CloudErrorSource = (typeof CLOUD_ERROR_SOURCES)[number]
19
19
 
20
20
  /**
21
- * What the server knows about a caught error; never who made the request or what it carried. For a
22
- * request: its method, the route pattern it matched (not the path with its IDs), and its ID.
21
+ * What the server knows about a caught error. For a request: its method, the route pattern it
22
+ * matched, its ID, the signed-in user's account ID, and the IDs of the records its path names;
23
+ * never what it carried. Error tracking sends the account and record IDs only where the
24
+ * deployment's `[error_tracking]` sets `include_ids`; the server's own log always has them.
23
25
  */
24
26
  export type CloudErrorContext = ErrorReportContext<CloudErrorSource>
25
27
 
@@ -46,6 +48,8 @@ export function createLoggingErrorReporter(
46
48
  method: context.method,
47
49
  route: context.route,
48
50
  requestId: context.requestId,
51
+ userId: context.userId,
52
+ ...context.resources,
49
53
  error: loggedError(error)
50
54
  })
51
55
  } catch (failure) {
@@ -69,13 +73,53 @@ export function reportCloudError(
69
73
  return (reporter ?? logOnly)(error, { ...context, message })
70
74
  }
71
75
 
76
+ /**
77
+ * Path parameters that name a record by its ID. Others are left out: an invitation's or a
78
+ * continuation's ID is the link that grants it, and an OAuth callback's names a provider.
79
+ */
80
+ const RECORD_PARAMETERS = [
81
+ 'documentId',
82
+ 'workspaceId',
83
+ 'threadId',
84
+ 'commentId',
85
+ 'versionId',
86
+ 'revisionId',
87
+ 'shareId',
88
+ 'uploadId'
89
+ ] as const
90
+
91
+ const validatedParametersSchema = v.record(v.string(), v.unknown())
92
+
93
+ /**
94
+ * The record IDs the request's path named, as its route's parameter validator accepted them: a
95
+ * path no validator checked names none, so what a caller typed never reaches a report.
96
+ */
97
+ function requestResources(context: Context): Record<string, string> {
98
+ const validated = v.safeParse(validatedParametersSchema, context.req.valid('param' as never))
99
+ if (!validated.success) return {}
100
+ return Object.fromEntries(
101
+ RECORD_PARAMETERS.flatMap((name) => {
102
+ const id = validated.output[name]
103
+ return typeof id === 'string' ? [[name, id]] : []
104
+ })
105
+ )
106
+ }
107
+
72
108
  function requestContext(context: Context): CloudErrorContext {
73
109
  const requestId: unknown = context.get('requestId')
110
+ const actor: unknown = context.get('actor')
111
+ const resources = requestResources(context)
112
+ const userId =
113
+ actor && typeof actor === 'object' && 'userId' in actor && typeof actor.userId === 'string'
114
+ ? actor.userId
115
+ : undefined
74
116
  return {
75
117
  source: 'request',
76
118
  method: context.req.method,
77
119
  route: routePath(context),
78
- ...(typeof requestId === 'string' && { requestId })
120
+ ...(Object.keys(resources).length > 0 && { resources }),
121
+ ...(typeof requestId === 'string' && { requestId }),
122
+ ...(userId && { userId })
79
123
  }
80
124
  }
81
125
 
@@ -90,10 +134,3 @@ export function cloudErrorHandler(reporter: CloudErrorReporter | undefined): Err
90
134
  return context.text('Internal Server Error', 500)
91
135
  }
92
136
  }
93
-
94
- export {
95
- createPostHogErrorReporter,
96
- type ErrorReportContext,
97
- type ErrorReporter,
98
- type PostHogErrorReporterOptions
99
- } from './posthog'
@@ -1,12 +1,14 @@
1
1
  export {
2
2
  adminErrorStatus,
3
3
  AdminDomainError,
4
+ approveEnrollmentByEmail,
4
5
  createAdminAuditService,
5
6
  createAdminEmailService,
6
7
  createAdminOperationsService,
7
8
  createAdminUserService,
8
9
  createCloudAdminRoutes,
9
10
  createEnrollmentService,
11
+ grantDeploymentAdminByEmail,
10
12
  normalizeEnrollmentEmail,
11
13
  type AdminAuditService,
12
14
  type AdminErrorCode,
@@ -19,6 +21,13 @@ export {
19
21
  type EnrollmentService,
20
22
  type EnrollmentStatus
21
23
  } from '#cloud/admin'
24
+ export {
25
+ createBillingRoutes,
26
+ createBillingTokenService,
27
+ type BillingRouteEnvironment,
28
+ type BillingTokenService,
29
+ type BillingTokenServiceOptions
30
+ } from '#cloud/server/billing'
22
31
  export {
23
32
  ServicesNotEntitledError,
24
33
  createServicesRoutes,
@@ -34,6 +43,7 @@ export {
34
43
  createAuthenticationEmailService,
35
44
  createAccountAuthenticationService,
36
45
  createCloudAuthenticationRuntime,
46
+ enrollmentEmailOptions,
37
47
  createBetterAuthAdapter,
38
48
  createCloudIdentityResolver,
39
49
  createCloudSessionResolver,
@@ -54,6 +64,7 @@ export {
54
64
  type AccessRequest,
55
65
  type DocumentRole
56
66
  } from './auth'
67
+ export { configuredSocialProviders } from './auth/social-providers'
57
68
  export {
58
69
  createCloudAPIRouter,
59
70
  createPublicCloudAPIRouter,
@@ -118,7 +129,6 @@ export {
118
129
  CloudConfigError,
119
130
  cloudDeploymentConfigSchema,
120
131
  cloudDiscoveryFromConfig,
121
- configuredSocialProviders,
122
132
  parseCloudDeploymentConfig,
123
133
  parseCloudDeploymentSource,
124
134
  parseCloudDeploymentTOML,
@@ -135,6 +145,7 @@ export {
135
145
  export {
136
146
  createCloudDatabase,
137
147
  migrateCloudDatabase,
148
+ pendingCloudMigrations,
138
149
  type CloudDatabase,
139
150
  type CloudDatabaseOptions,
140
151
  type Document,
@@ -173,6 +184,16 @@ export {
173
184
  LIMITED_HISTORY_DAYS,
174
185
  type DocumentVersionService
175
186
  } from './documents/versions'
187
+ export {
188
+ COMMENT_EMAIL_BUDGET,
189
+ CommentConflictError,
190
+ CommentLimitError,
191
+ createCommentRoutes,
192
+ createCommentService,
193
+ createSharedCommentRoutes,
194
+ type CommentActor,
195
+ type CommentService
196
+ } from './comments'
176
197
  export {
177
198
  createInvitationOutbox,
178
199
  createTransactionalEmailService,
@@ -197,11 +218,7 @@ export {
197
218
  reportCloudError,
198
219
  type CloudErrorContext,
199
220
  type CloudErrorReporter,
200
- type CloudErrorSource,
201
- createPostHogErrorReporter,
202
- type ErrorReportContext,
203
- type ErrorReporter,
204
- type PostHogErrorReporterOptions
221
+ type CloudErrorSource
205
222
  } from './errors'
206
223
  export {
207
224
  cloudRequestId,
@@ -282,9 +299,13 @@ export {
282
299
  type StaticEntitlementsInput
283
300
  } from './policy'
284
301
  export {
302
+ createStorageLimitNoticeService,
285
303
  createStorageQuotaService,
286
304
  createStorageReconciliationService,
287
305
  StorageQuotaExceededError,
306
+ type StorageLimitNoticeOptions,
307
+ type StorageLimitNoticeResult,
308
+ type StorageLimitNoticeService,
288
309
  type StorageQuotaService,
289
310
  type StorageQuotaSnapshot,
290
311
  type StorageReconciliation
@@ -3,7 +3,8 @@ import { accountParams, validatedJSON } from '#cloud/server/validation'
3
3
  import { Hono } from 'hono'
4
4
  import { bearerAuth } from 'hono/bearer-auth'
5
5
 
6
- import { parseSetAccountEntitlements, type InternalService } from './service'
6
+ import { setAccountEntitlementsSchema } from './schema'
7
+ import type { InternalService } from './service'
7
8
 
8
9
  /** The internal API on HTTP, for runtimes without a private transport to their services. */
9
10
  export function createInternalRoutes(service: InternalService, serviceToken: string) {
@@ -22,7 +23,7 @@ export function createInternalRoutes(service: InternalService, serviceToken: str
22
23
  .put(
23
24
  '/accounts/:userId/entitlements',
24
25
  accountParams,
25
- validatedJSON(parseSetAccountEntitlements),
26
+ validatedJSON(setAccountEntitlementsSchema),
26
27
  async (context) => {
27
28
  const { userId } = context.req.valid('param')
28
29
  const result = await service.setAccountEntitlements(userId, context.req.valid('json'))
@@ -30,4 +31,9 @@ export function createInternalRoutes(service: InternalService, serviceToken: str
30
31
  return context.json({ applied: result.applied })
31
32
  }
32
33
  )
34
+ .get('/accounts/:userId/seats', accountParams, async (context) => {
35
+ const seats = await service.accountSeats(context.req.valid('param').userId)
36
+ if (seats === null) return context.json({ error: { code: 'not_found' as const } }, 404)
37
+ return context.json({ seats })
38
+ })
33
39
  }
@@ -1,3 +1,4 @@
1
+ import { accountSeats } from '#cloud/server/billing/seats'
1
2
  import type { CloudDatabase } from '#cloud/server/db'
2
3
  import { createAccountEntitlementRepository } from '#cloud/server/policy'
3
4
  import type { Kysely } from 'kysely'
@@ -31,6 +32,15 @@ export function createInternalService(database: Kysely<CloudDatabase>) {
31
32
  if (!account) return { found: false, applied: false }
32
33
  const { applied } = await entitlements.setVersioned(account, values, source, externalVersion)
33
34
  return { found: true, applied }
35
+ },
36
+
37
+ /**
38
+ * How many people can edit across the workspaces an account owns, which billing charges a
39
+ * seat for; `null` for an unknown account.
40
+ */
41
+ async accountSeats(userId: string): Promise<number | null> {
42
+ const account = await entitlements.account(userId)
43
+ return account ? accountSeats(database, userId) : null
34
44
  }
35
45
  }
36
46
  }
@@ -2,13 +2,15 @@ import type { CloudDatabase } from '#cloud/server/db'
2
2
  import { lockForTransaction } from '#cloud/server/db/expressions'
3
3
  import type { Transaction } from 'kysely'
4
4
 
5
+ import { DAY_MS } from '@open-pencil/std/timing'
6
+
5
7
  /**
6
8
  * How many invitations, to documents and workspaces alike, one person may send in a day, and how
7
9
  * many one address may receive from everyone. Each sends an email naming the inviter and the file,
8
10
  * both of which the sender chooses, so without a daily budget invitations are a way to send spam.
9
11
  */
10
12
  export const INVITATION_BUDGET = {
11
- windowMs: 24 * 60 * 60 * 1000,
13
+ windowMs: DAY_MS,
12
14
  perSender: 100,
13
15
  perRecipient: 5
14
16
  } as const
@@ -1,4 +1,5 @@
1
1
  export { INVITATION_BUDGET, InvitationLimitError, spendInvitationBudget } from './budget'
2
+ export { INVITATION_LIFETIME_MS, INVITATION_SECRET_BYTES } from './links'
2
3
  export {
3
4
  noOpInvitationDelivery,
4
5
  type DocumentInvitationMessage,
@@ -0,0 +1,6 @@
1
+ import { DAY_MS } from '@open-pencil/std/timing'
2
+
3
+ /** How many random bytes an invitation link's secret has. */
4
+ export const INVITATION_SECRET_BYTES = 24
5
+ /** How long an invitation link works, for a document or a workspace alike. */
6
+ export const INVITATION_LIFETIME_MS = 7 * DAY_MS
@@ -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
  }
@@ -7,6 +7,8 @@ import { imageSize } from 'image-size'
7
7
  import type { Kysely } from 'kysely'
8
8
  import * as v from 'valibot'
9
9
 
10
+ import { DEADLINE_MS } from '@open-pencil/std/timing'
11
+
10
12
  /** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */
11
13
  export const PICTURE_PATH = '/api/pictures'
12
14
  /** The longest side a stored picture may have; pages send 256 pixels. */
@@ -14,7 +16,7 @@ const PICTURE_MAX_SIDE = 1024
14
16
  /** How many hex digits of the checksum name a picture in its address. */
15
17
  const PICTURE_VERSION_LENGTH = 16
16
18
  /** How long a linked account's picture may take to fetch before sign-in goes on without it. */
17
- const PROVIDER_PICTURE_TIMEOUT_MS = 5000
19
+ const PROVIDER_PICTURE_TIMEOUT_MS = DEADLINE_MS.request
18
20
  /** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */
19
21
  const PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']
20
22
  const PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }
@@ -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
  }