@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
@@ -12,13 +12,16 @@ import type { CloudActor } from '#cloud/server/auth'
12
12
  import type { CloudDatabase } from '#cloud/server/db'
13
13
  import { DocumentNotFoundError } from '#cloud/server/documents/errors'
14
14
  import {
15
+ INVITATION_LIFETIME_MS,
16
+ INVITATION_SECRET_BYTES,
15
17
  spendInvitationBudget,
18
+ type DocumentInvitationMessage,
16
19
  type InvitationDelivery,
17
20
  type InvitationOutbox
18
21
  } from '#cloud/server/invitations'
19
22
  import type { Kysely } from 'kysely'
20
23
 
21
- import { randomHex } from '@open-pencil/scene-graph/random'
24
+ import { randomHex } from '@open-pencil/std/random'
22
25
 
23
26
  import { requireSharingAccess } from '../access'
24
27
  import {
@@ -31,9 +34,6 @@ import { dateString, grantContract, invitationContract } from '../contracts'
31
34
  import { hashCapability } from '../crypto'
32
35
  import { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'
33
36
 
34
- const INVITATION_SECRET_BYTES = 24
35
- const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
36
-
37
37
  /** Workspace invitations share the invitation link; their ids are not document invitations. */
38
38
  export type WorkspaceInvitationResolver = {
39
39
  preview(invitationId: string, token: string): Promise<InvitationPreview | null>
@@ -140,26 +140,35 @@ export function createInvitationService(
140
140
  ? await Promise.all([
141
141
  database
142
142
  .selectFrom('user')
143
- .select('name')
143
+ .select(['name', 'locale'])
144
144
  .where('id', '=', userId)
145
145
  .executeTakeFirst(),
146
146
  database
147
147
  .selectFrom('document')
148
148
  .select('name')
149
149
  .where('id', '=', documentId)
150
- .executeTakeFirstOrThrow()
150
+ .executeTakeFirstOrThrow(),
151
+ database
152
+ .selectFrom('user')
153
+ .select('locale')
154
+ .where((expression) =>
155
+ expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)
156
+ )
157
+ .executeTakeFirst()
151
158
  ])
152
159
  : null
153
160
  const acceptanceURL =
154
161
  deliveryContext && options.publicURL
155
162
  ? cloudInvitationURL(options.publicURL, id, token)
156
163
  : null
157
- const message =
164
+ const message: DocumentInvitationMessage | null =
158
165
  deliveryContext && acceptanceURL
159
166
  ? {
160
167
  deliveryId: id,
161
168
  recipientEmail: input.email,
162
- inviterName: deliveryContext[0]?.name ?? 'An OpenPencil user',
169
+ // Someone without an account yet reads the inviter's language.
170
+ locale: deliveryContext[2]?.locale ?? deliveryContext[0]?.locale ?? 'en',
171
+ inviterName: deliveryContext[0]?.name ?? null,
163
172
  documentName: deliveryContext[1].name,
164
173
  permission: input.permission,
165
174
  expiresAt: expiresAt.toISOString(),
@@ -1,11 +1,11 @@
1
1
  import {
2
- parseAcceptDocumentInvitation,
3
- parseCreateInvitationContinuation,
4
- parseCreateDocumentInvitation,
5
- parseCreateDocumentShare,
6
- parsePutDocumentGrant,
7
- parseResolveDocumentShare,
8
- parseUpdateDocumentShare
2
+ acceptDocumentInvitationSchema,
3
+ createInvitationContinuationSchema,
4
+ createDocumentInvitationSchema,
5
+ createDocumentShareSchema,
6
+ putDocumentGrantSchema,
7
+ resolveDocumentShareSchema,
8
+ updateDocumentShareSchema
9
9
  } from '#cloud/contract'
10
10
  import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
11
11
  import type { CloudDatabase } from '#cloud/server/db'
@@ -77,7 +77,7 @@ export function createDocumentSharingRoutes(
77
77
  .post(
78
78
  '/documents/:documentId/shares',
79
79
  documentParams,
80
- validatedJSON(parseCreateDocumentShare),
80
+ validatedJSON(createDocumentShareSchema),
81
81
  (context) =>
82
82
  sharingRoute(context, async () =>
83
83
  context.json(
@@ -93,7 +93,7 @@ export function createDocumentSharingRoutes(
93
93
  .patch(
94
94
  '/documents/:documentId/shares/:shareId',
95
95
  documentShareParams,
96
- validatedJSON(parseUpdateDocumentShare),
96
+ validatedJSON(updateDocumentShareSchema),
97
97
  (context) =>
98
98
  sharingRoute(context, async () =>
99
99
  context.json({
@@ -140,7 +140,7 @@ export function createDocumentSharingRoutes(
140
140
  .put(
141
141
  '/documents/:documentId/grants/:userId',
142
142
  documentUserParams,
143
- validatedJSON(parsePutDocumentGrant),
143
+ validatedJSON(putDocumentGrantSchema),
144
144
  (context) =>
145
145
  sharingRoute(context, async () =>
146
146
  context.json({
@@ -176,7 +176,7 @@ export function createDocumentSharingRoutes(
176
176
  .post(
177
177
  '/documents/:documentId/invitations',
178
178
  documentParams,
179
- validatedJSON(parseCreateDocumentInvitation),
179
+ validatedJSON(createDocumentInvitationSchema),
180
180
  (context) =>
181
181
  sharingRoute(context, async () =>
182
182
  context.json(
@@ -192,7 +192,7 @@ export function createDocumentSharingRoutes(
192
192
  .post(
193
193
  '/invitations/:invitationId/accept',
194
194
  invitationParams,
195
- validatedJSON(parseAcceptDocumentInvitation),
195
+ validatedJSON(acceptDocumentInvitationSchema),
196
196
  (context) =>
197
197
  sharingRoute(context, async () =>
198
198
  context.json({
@@ -226,7 +226,7 @@ export function createPublicSharingRoutes(
226
226
  return new Hono()
227
227
  .post(
228
228
  '/invitations/continuations',
229
- validatedJSON(parseCreateInvitationContinuation),
229
+ validatedJSON(createInvitationContinuationSchema),
230
230
  (context) =>
231
231
  sharingRoute(context, async () =>
232
232
  context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)
@@ -245,7 +245,7 @@ export function createPublicSharingRoutes(
245
245
  .post(
246
246
  '/invitations/:invitationId/preview',
247
247
  invitationParams,
248
- validatedJSON(parseAcceptDocumentInvitation),
248
+ validatedJSON(acceptDocumentInvitationSchema),
249
249
  (context) =>
250
250
  sharingRoute(context, async () =>
251
251
  context.json({
@@ -259,7 +259,7 @@ export function createPublicSharingRoutes(
259
259
  .post(
260
260
  '/shares/:shareId/resolve',
261
261
  shareParams,
262
- validatedJSON(parseResolveDocumentShare),
262
+ validatedJSON(resolveDocumentShareSchema),
263
263
  (context) =>
264
264
  sharingRoute(context, async () =>
265
265
  context.json({
@@ -1,26 +1,24 @@
1
- import type { Context } from 'hono'
2
- import { validator } from 'hono/validator'
1
+ import { sValidator } from '@hono/standard-validator'
3
2
  import * as v from 'valibot'
4
3
 
5
- /** A request part that fails its schema is a 400, never a server error. */
6
- function parseOrReject<T>(parse: (input: unknown) => T, value: unknown, context: Context) {
7
- try {
8
- return parse(value)
9
- } catch (error) {
10
- if (error instanceof v.ValiError) {
11
- return context.json({ error: { code: 'invalid_request' as const } }, 400)
12
- }
13
- throw error
14
- }
15
- }
4
+ const invalidRequest = { error: { code: 'invalid_request' as const } }
16
5
 
17
- export function validatedJSON<T>(parse: (input: unknown) => T) {
18
- return validator('json', (value, context: Context) => parseOrReject(parse, value, context))
6
+ /**
7
+ * A JSON body through `schema`; handlers read it from `context.req.valid('json')`. A body that
8
+ * fails it is a 400, never a server error. The route's type takes what the schema accepts and
9
+ * hands handlers what it outputs, so a typed client may leave out a field with a default.
10
+ */
11
+ export function validatedJSON<Schema extends v.GenericSchema>(schema: Schema) {
12
+ return sValidator('json', schema, (result, context) =>
13
+ result.success ? undefined : context.json(invalidRequest, 400)
14
+ )
19
15
  }
20
16
 
21
17
  /** Query string counterpart of `validatedJSON`. */
22
- export function validatedQuery<T>(parse: (input: unknown) => T) {
23
- return validator('query', (value, context: Context) => parseOrReject(parse, value, context))
18
+ export function validatedQuery<Schema extends v.GenericSchema>(schema: Schema) {
19
+ return sValidator('query', schema, (result, context) =>
20
+ result.success ? undefined : context.json(invalidRequest, 400)
21
+ )
24
22
  }
25
23
 
26
24
  /**
@@ -34,13 +32,10 @@ const uuidParamSchema = v.pipe(v.string(), v.uuid(), v.toLowerCase())
34
32
  * parameter that fails it names nothing, so the route answers 404 as for a missing row, and the
35
33
  * value never reaches the database.
36
34
  */
37
- export function validatedParams<TOutput>(schema: v.GenericSchema<unknown, TOutput>) {
38
- return validator('param', (value, context: Context) => {
39
- const parsed = v.safeParse(schema, value)
40
- return parsed.success
41
- ? parsed.output
42
- : context.json({ error: { code: 'not_found' as const } }, 404)
43
- })
35
+ export function validatedParams<Schema extends v.GenericSchema>(schema: Schema) {
36
+ return sValidator('param', schema, (result, context) =>
37
+ result.success ? undefined : context.json({ error: { code: 'not_found' as const } }, 404)
38
+ )
44
39
  }
45
40
 
46
41
  /** A route parameter the server takes as text, such as a user ID, which is not a UUID column. */
@@ -50,6 +45,12 @@ export const documentParams = validatedParams(v.object({ documentId: uuidParamSc
50
45
  export const documentVersionParams = validatedParams(
51
46
  v.object({ documentId: uuidParamSchema, versionId: uuidParamSchema })
52
47
  )
48
+ export const documentThreadParams = validatedParams(
49
+ v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema })
50
+ )
51
+ export const documentCommentParams = validatedParams(
52
+ v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })
53
+ )
53
54
  export const documentShareParams = validatedParams(
54
55
  v.object({ documentId: uuidParamSchema, shareId: uuidParamSchema })
55
56
  )
@@ -68,6 +69,16 @@ export const workspaceMemberParams = validatedParams(
68
69
  )
69
70
  export const accountParams = validatedParams(v.object({ userId: uuidParamSchema }))
70
71
  export const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }))
72
+ export const shareThreadParams = validatedParams(
73
+ v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema })
74
+ )
75
+ export const shareCommentParams = validatedParams(
76
+ v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })
77
+ )
78
+ /** A document and one of its revisions, as a thumbnail's address names them. */
79
+ export const documentRevisionParams = validatedParams(
80
+ v.object({ documentId: uuidParamSchema, revisionId: uuidParamSchema })
81
+ )
71
82
  export const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }))
72
83
  export const invitationContinuationParams = validatedParams(
73
84
  v.object({ continuationId: textParamSchema })
@@ -10,9 +10,13 @@ import type {
10
10
  import { cloudInvitationURL } from '#cloud/contract'
11
11
  import type { CloudActor } from '#cloud/server/auth'
12
12
  import { workspaceRoleCan, type AccessRequest } from '#cloud/server/auth/access-control'
13
- import type { CloudDatabase } from '#cloud/server/db'
13
+ import { userIdText, type CloudDatabase } from '#cloud/server/db'
14
14
  import type { TransactionalEmailService } from '#cloud/server/email/types'
15
- import { spendInvitationBudget } from '#cloud/server/invitations'
15
+ import {
16
+ INVITATION_LIFETIME_MS,
17
+ INVITATION_SECRET_BYTES,
18
+ spendInvitationBudget
19
+ } from '#cloud/server/invitations'
16
20
  import { lockStorageAllowance } from '#cloud/server/quota/storage'
17
21
  import {
18
22
  invitationMatchesActor,
@@ -22,12 +26,10 @@ import {
22
26
  import { dateString } from '#cloud/server/sharing/contracts'
23
27
  import { hashCapability } from '#cloud/server/sharing/crypto'
24
28
  import { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'
29
+ import { compact, uniq } from 'es-toolkit'
25
30
  import type { Kysely, Transaction } from 'kysely'
26
31
 
27
- import { randomHex } from '@open-pencil/scene-graph/random'
28
-
29
- const INVITATION_SECRET_BYTES = 24
30
- const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
32
+ import { randomHex } from '@open-pencil/std/random'
31
33
 
32
34
  /** The workspace does not exist, or the person is not a member of it. */
33
35
  export class WorkspaceNotFoundError extends Error {
@@ -83,6 +85,12 @@ export class WorkspaceInvitationInvalidError extends Error {
83
85
  export type WorkspaceMemberServiceOptions = {
84
86
  email?: TransactionalEmailService
85
87
  publicURL: string
88
+ /**
89
+ * Told, after a change commits, the accounts whose seats it may have changed: the owner of the
90
+ * workspace, and the one before when ownership passed on. Seats are the people who can edit
91
+ * across the workspaces an account owns, which billing may charge for.
92
+ */
93
+ onSeatsChanged?: (accountIds: readonly string[]) => void
86
94
  }
87
95
 
88
96
  function invitationContract(row: {
@@ -179,6 +187,25 @@ export function createWorkspaceMemberService(
179
187
  database: Kysely<CloudDatabase>,
180
188
  options: WorkspaceMemberServiceOptions
181
189
  ) {
190
+ /** The workspace's owner as `database` sees it, inside the change's transaction. */
191
+ async function ownerIn(database: WorkspaceDatabase, workspaceId: string): Promise<string | null> {
192
+ const workspace = await database
193
+ .selectFrom('workspace')
194
+ .select('ownerId')
195
+ .where('id', '=', workspaceId)
196
+ .executeTakeFirst()
197
+ return workspace?.ownerId ?? null
198
+ }
199
+
200
+ /**
201
+ * Reports the owners whose seats a committed change touched, read inside its transaction, so
202
+ * nothing after the commit can fail or see a later change.
203
+ */
204
+ function seatsChanged(owners: readonly (string | null)[]): void {
205
+ const accountIds = uniq(compact(owners))
206
+ if (accountIds.length > 0) options.onSeatsChanged?.(accountIds)
207
+ }
208
+
182
209
  async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {
183
210
  const workspace = await findWorkspace(database, userId, workspaceId)
184
211
  if (!workspace) throw new WorkspaceNotFoundError()
@@ -199,15 +226,7 @@ export function createWorkspaceMemberService(
199
226
  function memberUsers(workspaceId: string) {
200
227
  return database
201
228
  .selectFrom('workspaceMember')
202
- .innerJoin('user', (join) =>
203
- join.on((expression) =>
204
- expression(
205
- expression.cast(expression.ref('user.id'), 'text'),
206
- '=',
207
- expression.ref('workspaceMember.userId')
208
- )
209
- )
210
- )
229
+ .innerJoin('user', (join) => join.onRef(userIdText, '=', 'workspaceMember.userId'))
211
230
  .where('workspaceMember.workspaceId', '=', workspaceId)
212
231
  }
213
232
 
@@ -231,7 +250,7 @@ export function createWorkspaceMemberService(
231
250
  if (existing) throw new WorkspaceAlreadyMemberError()
232
251
  const inviter = await database
233
252
  .selectFrom('user')
234
- .select('name')
253
+ .select(['name', 'locale'])
235
254
  .where('id', '=', userId)
236
255
  .executeTakeFirst()
237
256
  const id = crypto.randomUUID()
@@ -268,8 +287,10 @@ export function createWorkspaceMemberService(
268
287
  idempotencyKey: `workspace-invitation/${id}`,
269
288
  kind: 'workspace-invitation',
270
289
  recipientEmail: input.email,
290
+ // Someone without an account yet reads the inviter's language.
291
+ fallbackLocale: inviter?.locale,
271
292
  payload: {
272
- inviterName: inviter?.name ?? 'An OpenPencil user',
293
+ inviterName: inviter?.name ?? null,
273
294
  workspaceName: workspace.name,
274
295
  role: input.role,
275
296
  expiresAt: expiresAt.toISOString(),
@@ -314,13 +335,7 @@ export function createWorkspaceMemberService(
314
335
  ? await database
315
336
  .selectFrom('workspaceInvitation')
316
337
  .leftJoin('user', (join) =>
317
- join.on((expression) =>
318
- expression(
319
- expression.cast(expression.ref('user.id'), 'text'),
320
- '=',
321
- expression.ref('workspaceInvitation.invitedBy')
322
- )
323
- )
338
+ join.onRef(userIdText, '=', 'workspaceInvitation.invitedBy')
324
339
  )
325
340
  .select([
326
341
  'workspaceInvitation.id',
@@ -399,8 +414,9 @@ export function createWorkspaceMemberService(
399
414
  role: WorkspaceRole
400
415
  ): Promise<void> {
401
416
  await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
402
- await database.transaction().execute(async (transaction) => {
417
+ const owners = await database.transaction().execute(async (transaction) => {
403
418
  const member = await lockedMember(transaction, workspaceId, memberId)
419
+ const before = await ownerIn(transaction, workspaceId)
404
420
  if (member.role === 'admin' && role !== 'admin') {
405
421
  if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()
406
422
  }
@@ -411,17 +427,19 @@ export function createWorkspaceMemberService(
411
427
  .where('userId', '=', memberId)
412
428
  .execute()
413
429
  if (role !== 'admin') await handOverOwnership(transaction, workspaceId, memberId)
430
+ return [before, await ownerIn(transaction, workspaceId)]
414
431
  })
432
+ seatsChanged(owners)
415
433
  },
416
434
 
417
435
  /** Deletes an empty workspace, with its members and invitations. */
418
436
  async delete(userId: string, workspaceId: string): Promise<void> {
419
437
  await requireAccess(userId, workspaceId, { workspace: ['delete'] })
420
- await database.transaction().execute(async (transaction) => {
438
+ const owner = await database.transaction().execute(async (transaction) => {
421
439
  // Locked first, so a document created meanwhile waits and then finds no workspace.
422
- await transaction
440
+ const workspace = await transaction
423
441
  .selectFrom('workspace')
424
- .select('id')
442
+ .select('ownerId')
425
443
  .where('id', '=', workspaceId)
426
444
  .forUpdate()
427
445
  .executeTakeFirstOrThrow()
@@ -435,7 +453,9 @@ export function createWorkspaceMemberService(
435
453
  }
436
454
  if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')
437
455
  await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()
456
+ return workspace.ownerId
438
457
  })
458
+ seatsChanged([owner])
439
459
  },
440
460
 
441
461
  /**
@@ -445,8 +465,9 @@ export function createWorkspaceMemberService(
445
465
  async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {
446
466
  if (memberId === userId) await membership(userId, workspaceId)
447
467
  else await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
448
- await database.transaction().execute(async (transaction) => {
468
+ const owners = await database.transaction().execute(async (transaction) => {
449
469
  const member = await lockedMember(transaction, workspaceId, memberId)
470
+ const before = await ownerIn(transaction, workspaceId)
450
471
  if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {
451
472
  throw new WorkspaceLastAdminError()
452
473
  }
@@ -456,7 +477,9 @@ export function createWorkspaceMemberService(
456
477
  .where('userId', '=', memberId)
457
478
  .execute()
458
479
  await handOverOwnership(transaction, workspaceId, memberId)
480
+ return [before, await ownerIn(transaction, workspaceId)]
459
481
  })
482
+ seatsChanged(owners)
460
483
  },
461
484
 
462
485
  /** What a workspace invitation link offers, or null when the id is not one. */
@@ -522,7 +545,7 @@ export function createWorkspaceMemberService(
522
545
  ) {
523
546
  throw new WorkspaceInvitationInvalidError()
524
547
  }
525
- return database.transaction().execute(async (transaction) => {
548
+ const joined = await database.transaction().execute(async (transaction) => {
526
549
  await transaction
527
550
  .insertInto('workspaceMember')
528
551
  .values({
@@ -544,8 +567,11 @@ export function createWorkspaceMemberService(
544
567
  .where('workspaceId', '=', invitation.workspaceId)
545
568
  .where('userId', '=', actor.userId)
546
569
  .executeTakeFirstOrThrow()
547
- return { workspaceId: invitation.workspaceId, role: member.role }
570
+ const owner = await ownerIn(transaction, invitation.workspaceId)
571
+ return { joined: { workspaceId: invitation.workspaceId, role: member.role }, owner }
548
572
  })
573
+ seatsChanged([joined.owner])
574
+ return joined.joined
549
575
  }
550
576
  }
551
577
  }
@@ -8,6 +8,25 @@ function toISOString(value: Date | string): string {
8
8
  return value instanceof Date ? value.toISOString() : value
9
9
  }
10
10
 
11
+ function summary(
12
+ {
13
+ ownerId,
14
+ ...row
15
+ }: Omit<WorkspaceSummary, 'owner' | 'createdAt' | 'updatedAt'> & {
16
+ ownerId: string
17
+ createdAt: Date | string
18
+ updatedAt: Date | string
19
+ },
20
+ userId: string
21
+ ): WorkspaceSummary {
22
+ return {
23
+ ...row,
24
+ owner: ownerId === userId,
25
+ createdAt: toISOString(row.createdAt),
26
+ updatedAt: toISOString(row.updatedAt)
27
+ }
28
+ }
29
+
11
30
  export async function listWorkspaces(
12
31
  database: WorkspaceDatabase,
13
32
  userId: string
@@ -21,17 +40,14 @@ export async function listWorkspaces(
21
40
  'workspace.slug',
22
41
  'workspace.createdAt',
23
42
  'workspace.updatedAt',
43
+ 'workspace.ownerId',
24
44
  'workspaceMember.role'
25
45
  ])
26
46
  .where('workspaceMember.userId', '=', userId)
27
47
  .orderBy('workspace.updatedAt', 'desc')
28
48
  .execute()
29
49
 
30
- return rows.map((row) => ({
31
- ...row,
32
- createdAt: toISOString(row.createdAt),
33
- updatedAt: toISOString(row.updatedAt)
34
- }))
50
+ return rows.map((row) => summary(row, userId))
35
51
  }
36
52
 
37
53
  export async function findWorkspace(
@@ -48,18 +64,13 @@ export async function findWorkspace(
48
64
  'workspace.slug',
49
65
  'workspace.createdAt',
50
66
  'workspace.updatedAt',
67
+ 'workspace.ownerId',
51
68
  'workspaceMember.role'
52
69
  ])
53
70
  .where('workspace.id', '=', workspaceId)
54
71
  .where('workspaceMember.userId', '=', userId)
55
72
  .executeTakeFirst()
56
- return row
57
- ? {
58
- ...row,
59
- createdAt: toISOString(row.createdAt),
60
- updatedAt: toISOString(row.updatedAt)
61
- }
62
- : undefined
73
+ return row ? summary(row, userId) : undefined
63
74
  }
64
75
 
65
76
  export async function insertWorkspace(
@@ -1,8 +1,8 @@
1
1
  import {
2
- parseCreateWorkspace,
3
- parseCreateWorkspaceInvitation,
4
- parseUpdateWorkspace,
5
- parseUpdateWorkspaceMember
2
+ createWorkspaceSchema,
3
+ createWorkspaceInvitationSchema,
4
+ updateWorkspaceSchema,
5
+ updateWorkspaceMemberSchema
6
6
  } from '#cloud/contract'
7
7
  import type { CloudActor } from '#cloud/server/auth'
8
8
  import type { CloudDatabase } from '#cloud/server/db'
@@ -109,7 +109,7 @@ export function createWorkspaceRoutes(
109
109
  const workspaces = await service.list(context.get('actor').userId)
110
110
  return context.json({ workspaces })
111
111
  })
112
- .post('/', validatedJSON(parseCreateWorkspace), async (context) => {
112
+ .post('/', validatedJSON(createWorkspaceSchema), async (context) => {
113
113
  try {
114
114
  const workspace = await service.create(
115
115
  context.get('actor').userId,
@@ -131,7 +131,7 @@ export function createWorkspaceRoutes(
131
131
  if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)
132
132
  return context.json({ workspace })
133
133
  })
134
- .patch('/:workspaceId', workspaceParams, validatedJSON(parseUpdateWorkspace), (context) =>
134
+ .patch('/:workspaceId', workspaceParams, validatedJSON(updateWorkspaceSchema), (context) =>
135
135
  memberRoute(context, async () =>
136
136
  context.json({
137
137
  workspace: await members.rename(
@@ -158,7 +158,7 @@ export function createWorkspaceRoutes(
158
158
  .post(
159
159
  '/:workspaceId/invitations',
160
160
  workspaceParams,
161
- validatedJSON(parseCreateWorkspaceInvitation),
161
+ validatedJSON(createWorkspaceInvitationSchema),
162
162
  (context) =>
163
163
  memberRoute(context, async () =>
164
164
  context.json(
@@ -195,7 +195,7 @@ export function createWorkspaceRoutes(
195
195
  .patch(
196
196
  '/:workspaceId/members/:userId',
197
197
  workspaceMemberParams,
198
- validatedJSON(parseUpdateWorkspaceMember),
198
+ validatedJSON(updateWorkspaceMemberSchema),
199
199
  (context) =>
200
200
  memberRoute(context, async () => {
201
201
  await members.updateRole(