@open-pencil/cloud 0.17.0-beta.5 → 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 (187) hide show
  1. package/dist/client.d.ts +560 -93
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +1101 -186
  4. package/dist/client.js.map +1 -1
  5. package/dist/contract.d.ts +2 -2
  6. package/dist/contract.js +2 -2
  7. package/dist/contract2.js +390 -44
  8. package/dist/contract2.js.map +1 -1
  9. package/dist/email.d.ts +366 -3
  10. package/dist/email.d.ts.map +1 -1
  11. package/dist/email.js +1403 -556
  12. package/dist/email.js.map +1 -1
  13. package/dist/errors.js +16 -3
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +878 -37
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index2.d.ts +12 -2
  18. package/dist/index2.d.ts.map +1 -1
  19. package/dist/listen.mjs +589 -128
  20. package/dist/listen.mjs.map +1 -1
  21. package/dist/runtime-cloudflare.d.ts +4 -0
  22. package/dist/runtime-cloudflare.d.ts.map +1 -1
  23. package/dist/runtime-cloudflare.js +8689 -6324
  24. package/dist/runtime-cloudflare.js.map +1 -1
  25. package/dist/runtime-node.d.mts +10098 -5401
  26. package/dist/runtime-node.d.mts.map +1 -1
  27. package/dist/server.d.ts +14078 -7909
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +11723 -9412
  30. package/dist/server.js.map +1 -1
  31. package/dist/server.mjs +10658 -8649
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/server2.mjs +79 -57
  34. package/dist/server2.mjs.map +1 -1
  35. package/package.json +13 -4
  36. package/src/admin/api/routes.ts +263 -190
  37. package/src/admin/audit/service.ts +9 -1
  38. package/src/admin/bootstrap.ts +86 -0
  39. package/src/admin/documents/service.ts +119 -4
  40. package/src/admin/email/service.ts +2 -1
  41. package/src/admin/enrollment/email.ts +17 -3
  42. package/src/admin/enrollment/service.ts +71 -10
  43. package/src/admin/errors.ts +5 -0
  44. package/src/admin/index.ts +1 -0
  45. package/src/admin/reports/service.ts +9 -3
  46. package/src/admin/schema.ts +6 -5
  47. package/src/admin/users/service.ts +173 -16
  48. package/src/client/api.ts +29 -2
  49. package/src/client/comments.ts +205 -0
  50. package/src/client/device-authorization.ts +4 -20
  51. package/src/client/discovery.ts +4 -2
  52. package/src/client/files/archive.ts +60 -0
  53. package/src/client/files/checksum.ts +7 -0
  54. package/src/client/files/download.ts +122 -0
  55. package/src/client/files/images.ts +89 -0
  56. package/src/client/files/index.ts +15 -0
  57. package/src/client/files/objects.ts +173 -0
  58. package/src/client/files/save.ts +79 -0
  59. package/src/client/index.ts +3 -6
  60. package/src/client/portal/account.ts +20 -2
  61. package/src/client/portal/administration.ts +52 -5
  62. package/src/client/portal/request.ts +4 -2
  63. package/src/client/tour.ts +44 -0
  64. package/src/client/versions.ts +7 -1
  65. package/src/contract/account.ts +61 -11
  66. package/src/contract/admin/index.ts +48 -3
  67. package/src/contract/billing.ts +73 -4
  68. package/src/contract/comments.ts +223 -0
  69. package/src/contract/discovery.ts +47 -19
  70. package/src/contract/index.ts +10 -0
  71. package/src/contract/links.ts +5 -0
  72. package/src/contract/relay.ts +3 -1
  73. package/src/contract/services.ts +44 -4
  74. package/src/contract/workspaces.ts +5 -0
  75. package/src/email/locales/ar.json +28 -0
  76. package/src/email/locales/de.json +28 -0
  77. package/src/email/locales/es.json +28 -0
  78. package/src/email/locales/fr.json +28 -0
  79. package/src/email/locales/it.json +28 -0
  80. package/src/email/locales/ja.json +28 -0
  81. package/src/email/locales/pl.json +28 -0
  82. package/src/email/locales/pt-br.json +28 -0
  83. package/src/email/locales/ru.json +28 -0
  84. package/src/email/locales/zh-cn.json +28 -0
  85. package/src/email/messages.ts +35 -0
  86. package/src/email/render.ts +18 -0
  87. package/src/email/samples.ts +28 -1
  88. package/src/email/schema.ts +29 -3
  89. package/src/email/templates/BrandEmail.vue +3 -1
  90. package/src/email/templates/CommentNotification.vue +39 -0
  91. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  92. package/src/email/templates/TwoStepChanged.vue +17 -2
  93. package/src/email/templates/brand.ts +6 -0
  94. package/src/errors/posthog.ts +28 -4
  95. package/src/runtime/cloudflare/email.ts +2 -0
  96. package/src/runtime/cloudflare/relay/index.ts +21 -6
  97. package/src/runtime/cloudflare/worker.ts +6 -0
  98. package/src/runtime/cloudflare/xml.ts +12 -0
  99. package/src/runtime/node/admin.ts +51 -47
  100. package/src/runtime/node/email/runtime.ts +1 -0
  101. package/src/runtime/node/email/transport.ts +1 -0
  102. package/src/runtime/node/server.ts +8 -2
  103. package/src/runtime/posthog/errors.ts +3 -1
  104. package/src/server/account/actions.ts +3 -1
  105. package/src/server/account/deletion.ts +38 -4
  106. package/src/server/account/routes.ts +67 -46
  107. package/src/server/account/tokens.ts +3 -3
  108. package/src/server/api/router.ts +22 -7
  109. package/src/server/app/checks.ts +6 -1
  110. package/src/server/app/cors.ts +44 -0
  111. package/src/server/app/index.ts +76 -76
  112. package/src/server/app/routes.ts +14 -5
  113. package/src/server/app/services.ts +49 -15
  114. package/src/server/auth/access-control.ts +13 -8
  115. package/src/server/auth/account.ts +13 -12
  116. package/src/server/auth/activity.ts +7 -2
  117. package/src/server/auth/adapter.ts +16 -3
  118. package/src/server/auth/email.ts +29 -17
  119. package/src/server/auth/endpoints.ts +4 -0
  120. package/src/server/auth/factory.ts +83 -64
  121. package/src/server/auth/index.ts +1 -1
  122. package/src/server/auth/methods.ts +162 -0
  123. package/src/server/auth/mfa-assurance.ts +147 -10
  124. package/src/server/auth/rate-limit.ts +31 -0
  125. package/src/server/auth/runtime.ts +19 -5
  126. package/src/server/auth/social-providers.ts +70 -24
  127. package/src/server/billing/index.ts +2 -0
  128. package/src/server/billing/notify.ts +55 -0
  129. package/src/server/billing/seats.ts +17 -0
  130. package/src/server/billing/tokens.ts +1 -1
  131. package/src/server/cleanup/documents.ts +5 -2
  132. package/src/server/cleanup/revisions.ts +6 -3
  133. package/src/server/cleanup/uploads.ts +2 -1
  134. package/src/server/collaboration/relay/connection.ts +7 -2
  135. package/src/server/collaboration/relay/hub.ts +55 -24
  136. package/src/server/collaboration/routes.ts +8 -5
  137. package/src/server/comments/index.ts +9 -0
  138. package/src/server/comments/notify.ts +277 -0
  139. package/src/server/comments/routes.ts +352 -0
  140. package/src/server/comments/rows.ts +249 -0
  141. package/src/server/comments/service.ts +570 -0
  142. package/src/server/community/routes.ts +6 -6
  143. package/src/server/config/deployment.ts +19 -6
  144. package/src/server/config/index.ts +1 -1
  145. package/src/server/config/public.ts +19 -6
  146. package/src/server/config/schema.ts +14 -2
  147. package/src/server/config/toml/schema.ts +27 -4
  148. package/src/server/db/index.ts +2 -1
  149. package/src/server/db/migrate.ts +21 -1
  150. package/src/server/db/migrations/015_comments.ts +57 -0
  151. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  152. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  153. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  154. package/src/server/db/tables.ts +92 -2
  155. package/src/server/documents/access.ts +17 -0
  156. package/src/server/documents/images.ts +6 -1
  157. package/src/server/documents/routes.ts +12 -12
  158. package/src/server/documents/service.ts +19 -5
  159. package/src/server/documents/summary.ts +15 -0
  160. package/src/server/documents/versions/routes.ts +7 -8
  161. package/src/server/documents/versions/service.ts +5 -2
  162. package/src/server/email/service.ts +8 -2
  163. package/src/server/email/types.ts +1 -0
  164. package/src/server/errors/index.ts +48 -3
  165. package/src/server/index.ts +15 -1
  166. package/src/server/internal/routes.ts +8 -2
  167. package/src/server/internal/service.ts +10 -0
  168. package/src/server/invitations/budget.ts +3 -1
  169. package/src/server/invitations/index.ts +1 -0
  170. package/src/server/invitations/links.ts +6 -0
  171. package/src/server/pictures/service.ts +3 -1
  172. package/src/server/policy/workspace.ts +5 -2
  173. package/src/server/reports/routes.ts +2 -2
  174. package/src/server/reports/service.ts +3 -1
  175. package/src/server/services/routes.ts +2 -2
  176. package/src/server/sharing/capabilities/service.ts +1 -1
  177. package/src/server/sharing/document-routes.ts +3 -3
  178. package/src/server/sharing/invitations/service.ts +3 -4
  179. package/src/server/sharing/routes.ts +15 -15
  180. package/src/server/validation.ts +33 -25
  181. package/src/server/workspaces/members.ts +50 -12
  182. package/src/server/workspaces/repository.ts +23 -12
  183. package/src/server/workspaces/routes.ts +8 -8
  184. package/src/services/app.ts +30 -19
  185. package/src/services/config.ts +47 -8
  186. package/src/services/metering.ts +15 -27
  187. package/src/client/billing.ts +0 -80
@@ -0,0 +1,570 @@
1
+ import {
2
+ MAX_COMMENT_THREADS_PER_DOCUMENT,
3
+ MAX_COMMENTS_PER_THREAD,
4
+ type CloudCommentThread,
5
+ type CommentAccess,
6
+ type CommentThreads,
7
+ type CreateCommentInput,
8
+ type CreateCommentThreadInput,
9
+ type ImportCommentThreadsInput,
10
+ type NotificationSettings,
11
+ type UpdateCommentInput,
12
+ type UpdateCommentThreadInput
13
+ } from '#cloud/contract'
14
+ import type { CloudDatabase } from '#cloud/server/db'
15
+ import { resolveDocumentCommentAccess } from '#cloud/server/documents/access'
16
+ import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'
17
+ import { logCloud, loggedError } from '#cloud/server/logging'
18
+ import type { DocumentSharingService } from '#cloud/server/sharing'
19
+ import { chunk, groupBy, isEmptyObject } from 'es-toolkit'
20
+ import type { Kysely, Transaction } from 'kysely'
21
+
22
+ import {
23
+ commentPeople,
24
+ notifyComment,
25
+ recordMentions,
26
+ readNotificationSettings,
27
+ threadParticipants,
28
+ writeNotificationSettings,
29
+ type CommentNotifier
30
+ } from './notify'
31
+ import {
32
+ anchorValues,
33
+ comments,
34
+ documentThreadCount,
35
+ findThread,
36
+ lockDocument,
37
+ markRead,
38
+ readsOf,
39
+ resolutionChange,
40
+ threadOf,
41
+ threads,
42
+ type ThreadRow,
43
+ type Source
44
+ } from './rows'
45
+
46
+ /** A document holds as many threads, or a thread as many comments, as it may. */
47
+ export class CommentLimitError extends Error {
48
+ override readonly name = 'CommentLimitError'
49
+ }
50
+
51
+ /** A new thread or comment named an ID something else already has. */
52
+ export class CommentConflictError extends Error {
53
+ override readonly name = 'CommentConflictError'
54
+ }
55
+
56
+ /**
57
+ * Whose request it is and what they may do, settled before any comment is touched: a member or
58
+ * grantee through `forMember`, or whoever follows a share link through `forShare`.
59
+ */
60
+ export type CommentActor = Omit<CommentAccess, 'accountId'> & {
61
+ documentId: string
62
+ /** Null for a guest on a link, who may only read. */
63
+ userId: string | null
64
+ }
65
+
66
+ /** A request's input as callers may write it: naming nobody when it lists no mentions. */
67
+ type Mentioning<Input extends { mentions: string[] }> = Omit<Input, 'mentions'> & {
68
+ mentions?: readonly string[]
69
+ }
70
+ type NewThread = Mentioning<CreateCommentThreadInput>
71
+ type NewComment = Mentioning<CreateCommentInput>
72
+ type CommentEdit = Mentioning<UpdateCommentInput>
73
+
74
+ /** Rows one insert writes, within PostgreSQL's parameters per statement. */
75
+ const INSERT_BATCH = 500
76
+
77
+ /**
78
+ * A thread's comment times as a file gave them, each after the one before, so the first one is
79
+ * the thread's first wherever the file wrote two at the same moment.
80
+ */
81
+ function importedTimes(times: readonly string[]): Date[] {
82
+ const result: Date[] = []
83
+ for (const time of times) {
84
+ const at = new Date(time)
85
+ const previous = result.at(-1)
86
+ result.push(previous && at <= previous ? new Date(previous.getTime() + 1) : at)
87
+ }
88
+ return result
89
+ }
90
+
91
+ function requireCommenter(actor: CommentActor): string {
92
+ if (!actor.canComment || actor.userId === null) throw new DocumentForbiddenError()
93
+ return actor.userId
94
+ }
95
+
96
+ /**
97
+ * The comments of Cloud documents. Everyone who can read a document reads its comments; everyone
98
+ * signed in who can read writes them. A comment is changed only by its author, and deleted by its
99
+ * author or an editor; a thread's pin is moved by whoever started it or an editor, and anyone who
100
+ * comments resolves or reopens it. Deleting a thread's first comment deletes the thread.
101
+ */
102
+ export function createCommentService(
103
+ database: Kysely<CloudDatabase>,
104
+ options: {
105
+ sharing?: Pick<DocumentSharingService, 'resolveShare'>
106
+ /** Called once a thread changes, so the document's live rooms fetch it again. */
107
+ onCommentsChanged?: (documentId: string, threadId: string) => void
108
+ /** Emails the people a comment concerns; without it nobody hears by email. */
109
+ notifier?: CommentNotifier
110
+ } = {}
111
+ ) {
112
+ /**
113
+ * Records whom a comment names and emails them, and, for a reply, the thread's other writers
114
+ * who asked to hear about everything.
115
+ */
116
+ async function tell(
117
+ transaction: Transaction<CloudDatabase>,
118
+ actor: CommentActor,
119
+ comment: { commentId: string; threadId: string; body: string },
120
+ mentions: readonly string[],
121
+ { reply = false } = {}
122
+ ) {
123
+ const authorId = requireCommenter(actor)
124
+ const mentioned = await recordMentions(transaction, {
125
+ documentId: actor.documentId,
126
+ commentId: comment.commentId,
127
+ authorId,
128
+ mentions
129
+ })
130
+ if (!options.notifier) return
131
+ const participants = reply
132
+ ? await threadParticipants(transaction, actor.documentId, comment.threadId, authorId)
133
+ : []
134
+ await notifyComment(transaction, options.notifier, {
135
+ id: comment.commentId,
136
+ documentId: actor.documentId,
137
+ threadId: comment.threadId,
138
+ authorId,
139
+ body: comment.body,
140
+ mentioned,
141
+ participants
142
+ })
143
+ }
144
+
145
+ function announce(documentId: string, threadId: string): void {
146
+ try {
147
+ options.onCommentsChanged?.(documentId, threadId)
148
+ } catch (error) {
149
+ logCloud('error', 'Announcing a comment change failed', { error: loggedError(error) })
150
+ }
151
+ }
152
+
153
+ async function readThread(
154
+ source: Source,
155
+ row: ThreadRow,
156
+ viewer: string | null
157
+ ): Promise<CloudCommentThread> {
158
+ const reads = await readsOf(source, viewer, [row.id])
159
+ return threadOf(row, await comments(source, [row.id]), viewer, reads.get(row.id))
160
+ }
161
+
162
+ /**
163
+ * Marks the thread changed now, and read by whoever changed it, and answers it as it is after
164
+ * the change.
165
+ */
166
+ async function touched(
167
+ transaction: Transaction<CloudDatabase>,
168
+ actor: CommentActor,
169
+ threadId: string
170
+ ): Promise<CloudCommentThread> {
171
+ await transaction
172
+ .updateTable('commentThread')
173
+ .set({ updatedAt: new Date() })
174
+ .where('id', '=', threadId)
175
+ .execute()
176
+ if (actor.userId !== null) await markRead(transaction, actor.userId, threadId)
177
+ return readThread(
178
+ transaction,
179
+ await findThread(transaction, actor.documentId, threadId),
180
+ actor.userId
181
+ )
182
+ }
183
+
184
+ async function findComment(
185
+ source: Source,
186
+ threadId: string,
187
+ commentId: string
188
+ ): Promise<{ authorId: string | null; first: boolean }> {
189
+ const rows = await source
190
+ .selectFrom('comment')
191
+ .select(['id', 'authorId'])
192
+ .where('threadId', '=', threadId)
193
+ .orderBy('createdAt')
194
+ .orderBy('id')
195
+ .execute()
196
+ const index = rows.findIndex((comment) => comment.id === commentId)
197
+ const found = rows[index]
198
+ if (!found) throw new DocumentNotFoundError()
199
+ return { authorId: found.authorId, first: index === 0 }
200
+ }
201
+
202
+ /** A comment of a thread, with the thread held until the transaction ends. */
203
+ async function lockedComment(
204
+ transaction: Transaction<CloudDatabase>,
205
+ actor: CommentActor,
206
+ threadId: string,
207
+ commentId: string
208
+ ) {
209
+ await findThread(transaction, actor.documentId, threadId, true)
210
+ return findComment(transaction, threadId, commentId)
211
+ }
212
+
213
+ /** Every thread on the document, oldest first, with what the asker may do. */
214
+ async function list(actor: CommentActor): Promise<CommentThreads> {
215
+ const rows = await threads(database)
216
+ .where('commentThread.documentId', '=', actor.documentId)
217
+ .orderBy('commentThread.createdAt')
218
+ .orderBy('commentThread.id')
219
+ .execute()
220
+ const ids = rows.map((row) => row.id)
221
+ const byThread =
222
+ rows.length > 0 ? groupBy(await comments(database, ids), (c) => c.threadId) : {}
223
+ const reads = await readsOf(database, actor.userId, ids)
224
+ return {
225
+ threads: rows.map((row) =>
226
+ threadOf(row, byThread[row.id] ?? [], actor.userId, reads.get(row.id))
227
+ ),
228
+ access: {
229
+ canComment: actor.canComment,
230
+ canModerate: actor.canModerate,
231
+ accountId: actor.userId
232
+ }
233
+ }
234
+ }
235
+
236
+ return {
237
+ /** A member's or grantee's access to a document's comments. */
238
+ async forMember(userId: string, documentId: string): Promise<CommentActor> {
239
+ const access = await resolveDocumentCommentAccess(database, userId, documentId)
240
+ if (!access) throw new DocumentNotFoundError()
241
+ return { ...access, documentId, userId }
242
+ },
243
+
244
+ /**
245
+ * Access through a share link: everyone with it reads; people signed in also comment, and
246
+ * moderate when the link lets them edit. A guest on any link only reads.
247
+ */
248
+ async forShare(
249
+ shareId: string,
250
+ secret: string,
251
+ actor: { userId: string; name: string; email: string } | undefined
252
+ ): Promise<CommentActor> {
253
+ if (!options.sharing) throw new DocumentNotFoundError()
254
+ const resolution = await options.sharing.resolveShare(shareId, { secret }, actor)
255
+ const userId = resolution.principal.kind === 'user' ? resolution.principal.userId : null
256
+ return {
257
+ documentId: resolution.documentId,
258
+ userId,
259
+ canComment: userId !== null,
260
+ canModerate: userId !== null && resolution.permission === 'edit'
261
+ }
262
+ },
263
+
264
+ list,
265
+
266
+ async get(actor: CommentActor, threadId: string): Promise<CloudCommentThread> {
267
+ return readThread(
268
+ database,
269
+ await findThread(database, actor.documentId, threadId),
270
+ actor.userId
271
+ )
272
+ },
273
+
274
+ /** Records that the asker read the thread as it is now; a guest keeps no such record. */
275
+ async markRead(actor: CommentActor, threadId: string): Promise<void> {
276
+ if (actor.userId === null) return
277
+ await findThread(database, actor.documentId, threadId)
278
+ await markRead(database, actor.userId, threadId)
279
+ },
280
+
281
+ /** Which comments the account hears about by email. */
282
+ notificationSettings: (userId: string) => readNotificationSettings(database, userId),
283
+ setNotificationSettings: (userId: string, settings: NotificationSettings) =>
284
+ writeNotificationSettings(database, userId, settings),
285
+
286
+ /** Whom the asker may name in the document's comments. */
287
+ async people(actor: CommentActor) {
288
+ requireCommenter(actor)
289
+ return { people: await commentPeople(database, actor.documentId) }
290
+ },
291
+
292
+ async createThread(actor: CommentActor, input: NewThread): Promise<CloudCommentThread> {
293
+ const userId = requireCommenter(actor)
294
+ const threadId = input.id ?? crypto.randomUUID()
295
+ const thread = await database.transaction().execute(async (transaction) => {
296
+ // One writer at a time per document, so the count below holds until the insert.
297
+ await lockDocument(transaction, actor.documentId)
298
+ const existing = await transaction
299
+ .selectFrom('commentThread')
300
+ .select(['documentId', 'createdBy'])
301
+ .where('id', '=', threadId)
302
+ .executeTakeFirst()
303
+ if (existing) {
304
+ // The same request again, its answer lost on the way: the thread it made.
305
+ if (existing.documentId !== actor.documentId || existing.createdBy !== userId) {
306
+ throw new CommentConflictError()
307
+ }
308
+ return readThread(
309
+ transaction,
310
+ await findThread(transaction, actor.documentId, threadId),
311
+ actor.userId
312
+ )
313
+ }
314
+ if (
315
+ (await documentThreadCount(transaction, actor.documentId)) >=
316
+ MAX_COMMENT_THREADS_PER_DOCUMENT
317
+ ) {
318
+ throw new CommentLimitError()
319
+ }
320
+ const now = new Date()
321
+ await transaction
322
+ .insertInto('commentThread')
323
+ .values({
324
+ id: threadId,
325
+ documentId: actor.documentId,
326
+ ...anchorValues(input),
327
+ createdBy: userId,
328
+ createdAt: now,
329
+ updatedAt: now
330
+ })
331
+ .execute()
332
+ const commentId = crypto.randomUUID()
333
+ await transaction
334
+ .insertInto('comment')
335
+ .values({
336
+ id: commentId,
337
+ threadId,
338
+ authorId: userId,
339
+ agent: input.agent ?? null,
340
+ body: input.body,
341
+ createdAt: now
342
+ })
343
+ .execute()
344
+ await markRead(transaction, userId, threadId)
345
+ await tell(
346
+ transaction,
347
+ actor,
348
+ { commentId, threadId, body: input.body },
349
+ input.mentions ?? []
350
+ )
351
+ return readThread(
352
+ transaction,
353
+ await findThread(transaction, actor.documentId, threadId),
354
+ actor.userId
355
+ )
356
+ })
357
+ announce(actor.documentId, threadId)
358
+ return thread
359
+ },
360
+
361
+ /**
362
+ * Brings in the threads a file held as it moved to Cloud, for someone who may edit it. Their
363
+ * authors stay the names the file gave; the importer may move and resolve them as a starter.
364
+ */
365
+ async importThreads(
366
+ actor: CommentActor,
367
+ input: ImportCommentThreadsInput
368
+ ): Promise<CommentThreads> {
369
+ const userId = requireCommenter(actor)
370
+ if (!actor.canModerate) throw new DocumentForbiddenError()
371
+ const ids: string[] = []
372
+ if (input.threads.length > 0) {
373
+ await database.transaction().execute(async (transaction) => {
374
+ await lockDocument(transaction, actor.documentId)
375
+ const held = await documentThreadCount(transaction, actor.documentId)
376
+ if (held + input.threads.length > MAX_COMMENT_THREADS_PER_DOCUMENT) {
377
+ throw new CommentLimitError()
378
+ }
379
+ const now = new Date()
380
+ const rows = input.threads.map((thread) => ({
381
+ thread,
382
+ id: crypto.randomUUID(),
383
+ createdAt: new Date(thread.createdAt)
384
+ }))
385
+ const threadRows = rows.map(({ thread, id, createdAt }) => ({
386
+ id,
387
+ documentId: actor.documentId,
388
+ ...anchorValues(thread),
389
+ createdBy: userId,
390
+ createdAt,
391
+ updatedAt: now,
392
+ resolvedAt: thread.resolved ? now : null,
393
+ resolvedBy: thread.resolved ? userId : null
394
+ }))
395
+ for (const batch of chunk(threadRows, INSERT_BATCH)) {
396
+ await transaction.insertInto('commentThread').values(batch).execute()
397
+ }
398
+ const imported = rows.flatMap(({ thread, id }) =>
399
+ importedTimes(thread.comments.map((comment) => comment.createdAt)).map(
400
+ (createdAt, index) => ({
401
+ id: crypto.randomUUID(),
402
+ threadId: id,
403
+ authorId: null,
404
+ importedAuthorName: thread.comments[index]?.authorName ?? '',
405
+ body: thread.comments[index]?.body ?? '',
406
+ createdAt
407
+ })
408
+ )
409
+ )
410
+ // A statement takes so many parameters; a big file's comments go in a few.
411
+ for (const batch of chunk(imported, INSERT_BATCH)) {
412
+ await transaction.insertInto('comment').values(batch).execute()
413
+ }
414
+ // The importer has read what they brought.
415
+ for (const { id } of rows) {
416
+ await markRead(transaction, userId, id)
417
+ ids.push(id)
418
+ }
419
+ })
420
+ }
421
+ for (const id of ids) announce(actor.documentId, id)
422
+ return list(actor)
423
+ },
424
+
425
+ async updateThread(
426
+ actor: CommentActor,
427
+ threadId: string,
428
+ input: UpdateCommentThreadInput
429
+ ): Promise<CloudCommentThread> {
430
+ const userId = requireCommenter(actor)
431
+ const thread = await database.transaction().execute(async (transaction) => {
432
+ const row = await findThread(transaction, actor.documentId, threadId, true)
433
+ if (input.anchor && row.createdBy !== userId && !actor.canModerate) {
434
+ throw new DocumentForbiddenError()
435
+ }
436
+ const changes = {
437
+ ...(input.anchor ? anchorValues(input.anchor) : {}),
438
+ ...resolutionChange(input.resolved, row.resolvedAt !== null, userId)
439
+ }
440
+ // Resolving what is already resolved, and nothing else, changes nothing.
441
+ if (isEmptyObject(changes)) return readThread(transaction, row, actor.userId)
442
+ await transaction
443
+ .updateTable('commentThread')
444
+ .set(changes)
445
+ .where('id', '=', threadId)
446
+ .execute()
447
+ return touched(transaction, actor, threadId)
448
+ })
449
+ announce(actor.documentId, threadId)
450
+ return thread
451
+ },
452
+
453
+ async deleteThread(actor: CommentActor, threadId: string): Promise<void> {
454
+ const userId = requireCommenter(actor)
455
+ await database.transaction().execute(async (transaction) => {
456
+ const row = await findThread(transaction, actor.documentId, threadId, true)
457
+ if (row.createdBy !== userId && !actor.canModerate) throw new DocumentForbiddenError()
458
+ await transaction.deleteFrom('commentThread').where('id', '=', threadId).execute()
459
+ })
460
+ announce(actor.documentId, threadId)
461
+ },
462
+
463
+ async reply(
464
+ actor: CommentActor,
465
+ threadId: string,
466
+ input: NewComment
467
+ ): Promise<CloudCommentThread> {
468
+ const userId = requireCommenter(actor)
469
+ const commentId = input.id ?? crypto.randomUUID()
470
+ const thread = await database.transaction().execute(async (transaction) => {
471
+ await findThread(transaction, actor.documentId, threadId, true)
472
+ const existing = await transaction
473
+ .selectFrom('comment')
474
+ .select(['threadId', 'authorId'])
475
+ .where('id', '=', commentId)
476
+ .executeTakeFirst()
477
+ if (existing) {
478
+ if (existing.threadId !== threadId || existing.authorId !== userId) {
479
+ throw new CommentConflictError()
480
+ }
481
+ return readThread(
482
+ transaction,
483
+ await findThread(transaction, actor.documentId, threadId),
484
+ actor.userId
485
+ )
486
+ }
487
+ const { count } = await transaction
488
+ .selectFrom('comment')
489
+ .select((expression) => expression.fn.countAll<string>().as('count'))
490
+ .where('threadId', '=', threadId)
491
+ .executeTakeFirstOrThrow()
492
+ if (Number(count) >= MAX_COMMENTS_PER_THREAD) throw new CommentLimitError()
493
+ await transaction
494
+ .insertInto('comment')
495
+ .values({
496
+ id: commentId,
497
+ threadId,
498
+ authorId: userId,
499
+ agent: input.agent ?? null,
500
+ body: input.body
501
+ })
502
+ .execute()
503
+ await tell(
504
+ transaction,
505
+ actor,
506
+ { commentId, threadId, body: input.body },
507
+ input.mentions ?? [],
508
+ {
509
+ reply: true
510
+ }
511
+ )
512
+ return touched(transaction, actor, threadId)
513
+ })
514
+ announce(actor.documentId, threadId)
515
+ return thread
516
+ },
517
+
518
+ /** Changes what a comment says; only its author may, so no one puts words in another's mouth. */
519
+ async updateComment(
520
+ actor: CommentActor,
521
+ threadId: string,
522
+ commentId: string,
523
+ input: CommentEdit
524
+ ): Promise<CloudCommentThread> {
525
+ const userId = requireCommenter(actor)
526
+ const thread = await database.transaction().execute(async (transaction) => {
527
+ const comment = await lockedComment(transaction, actor, threadId, commentId)
528
+ if (comment.authorId !== userId) throw new DocumentForbiddenError()
529
+ await transaction
530
+ .updateTable('comment')
531
+ .set({ body: input.body, editedAt: new Date() })
532
+ .where('id', '=', commentId)
533
+ .execute()
534
+ // An edit tells only the people it names that it did not before.
535
+ await tell(
536
+ transaction,
537
+ actor,
538
+ { commentId, threadId, body: input.body },
539
+ input.mentions ?? []
540
+ )
541
+ return touched(transaction, actor, threadId)
542
+ })
543
+ announce(actor.documentId, threadId)
544
+ return thread
545
+ },
546
+
547
+ /** Deletes a comment for good; the thread goes with its first one. Null once it is gone. */
548
+ async deleteComment(
549
+ actor: CommentActor,
550
+ threadId: string,
551
+ commentId: string
552
+ ): Promise<CloudCommentThread | null> {
553
+ const userId = requireCommenter(actor)
554
+ const thread = await database.transaction().execute(async (transaction) => {
555
+ const comment = await lockedComment(transaction, actor, threadId, commentId)
556
+ if (comment.authorId !== userId && !actor.canModerate) throw new DocumentForbiddenError()
557
+ if (comment.first) {
558
+ await transaction.deleteFrom('commentThread').where('id', '=', threadId).execute()
559
+ return null
560
+ }
561
+ await transaction.deleteFrom('comment').where('id', '=', commentId).execute()
562
+ return touched(transaction, actor, threadId)
563
+ })
564
+ announce(actor.documentId, threadId)
565
+ return thread
566
+ }
567
+ }
568
+ }
569
+
570
+ export type CommentService = ReturnType<typeof createCommentService>
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  COMMUNITY_THUMBNAIL_PATH,
3
- parseCommunityDownloadQuery,
4
- parseRequestImageLinks
3
+ communityDownloadQuerySchema,
4
+ requestImageLinksSchema
5
5
  } from '#cloud/contract'
6
6
  import { documentDomainError } from '#cloud/server/documents'
7
7
  import {
8
- communityThumbnailParams,
8
+ documentRevisionParams,
9
9
  documentParams,
10
10
  validatedJSON,
11
11
  validatedQuery
@@ -43,7 +43,7 @@ export function createCommunityRoutes(community: CommunityService) {
43
43
  .get(
44
44
  '/community/:documentId/document',
45
45
  documentParams,
46
- validatedQuery(parseCommunityDownloadQuery),
46
+ validatedQuery(communityDownloadQuerySchema),
47
47
  (context) =>
48
48
  communityRoute(context, async () => {
49
49
  const { documentId } = context.req.valid('param')
@@ -55,7 +55,7 @@ export function createCommunityRoutes(community: CommunityService) {
55
55
  .post(
56
56
  '/community/:documentId/images',
57
57
  documentParams,
58
- validatedJSON(parseRequestImageLinks),
58
+ validatedJSON(requestImageLinksSchema),
59
59
  (context) =>
60
60
  communityRoute(context, async () =>
61
61
  context.json(
@@ -76,7 +76,7 @@ export function createCommunityRoutes(community: CommunityService) {
76
76
  export function createCommunityThumbnailRoutes(community: CommunityService) {
77
77
  return new Hono().get(
78
78
  `${COMMUNITY_THUMBNAIL_PATH}/:documentId/:revisionId`,
79
- communityThumbnailParams,
79
+ documentRevisionParams,
80
80
  (context) =>
81
81
  communityRoute(context, async () => {
82
82
  const { documentId, revisionId } = context.req.valid('param')
@@ -2,6 +2,8 @@ import { staticEntitlementsFromTOML } from '#cloud/server/policy/static'
2
2
  import { parse as parseTOML } from 'smol-toml'
3
3
  import * as v from 'valibot'
4
4
 
5
+ import { DAY_MS } from '@open-pencil/std/timing'
6
+
5
7
  import { parseCloudServerConfig, type CloudServerConfig } from './schema'
6
8
  import {
7
9
  cloudDeploymentConfigSchema,
@@ -48,11 +50,16 @@ function defaultEntitlements(config: CloudDeploymentConfig) {
48
50
  function emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
49
51
  if (config.email.transport === 'none') return { emailTransport: 'none' as const }
50
52
  if (config.email.transport === 'cloudflare') {
51
- return { emailTransport: 'cloudflare' as const, emailFrom: config.email.from }
53
+ return {
54
+ emailTransport: 'cloudflare' as const,
55
+ emailFrom: config.email.from,
56
+ emailReplyTo: config.email.reply_to
57
+ }
52
58
  }
53
59
  return {
54
60
  emailTransport: 'smtp' as const,
55
61
  emailFrom: config.email.from,
62
+ emailReplyTo: config.email.reply_to,
56
63
  smtpHost: config.email.smtp.host,
57
64
  smtpPort: config.email.smtp.port,
58
65
  smtpSecure: config.email.smtp.secure,
@@ -64,6 +71,7 @@ function emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironmen
64
71
  function authenticationConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
65
72
  const google = config.authentication.providers.google
66
73
  const apple = config.authentication.providers.apple
74
+ const github = config.authentication.providers.github
67
75
  return {
68
76
  googleClientId: google ? configuredText(environment, google.client_id) : undefined,
69
77
  googleClientSecret: google ? requiredSecret(environment, google.client_secret) : undefined,
@@ -71,7 +79,9 @@ function authenticationConfig(config: CloudDeploymentConfig, environment: CloudE
71
79
  appleTeamId: apple?.team_id,
72
80
  appleKeyId: apple?.key_id,
73
81
  applePrivateKey: apple ? requiredSecret(environment, apple.private_key) : undefined,
74
- appleAppBundleIdentifier: apple?.app_bundle_identifier
82
+ appleAppBundleIdentifier: apple?.app_bundle_identifier,
83
+ githubClientId: github ? configuredText(environment, github.client_id) : undefined,
84
+ githubClientSecret: github ? requiredSecret(environment, github.client_secret) : undefined
75
85
  }
76
86
  }
77
87
 
@@ -87,8 +97,8 @@ function workerConfig(config: CloudDeploymentConfig) {
87
97
  cleanupBatchSize: cleanup?.batch_size,
88
98
  cleanupIntervalMs: cleanup?.interval_ms,
89
99
  cleanupLeaseDurationMs: cleanup?.lease_ms,
90
- documentRetentionMs: config.documents.retention_days * 86_400_000,
91
- documentPurgeGraceMs: config.documents.purge_grace_days * 86_400_000
100
+ documentRetentionMs: config.documents.retention_days * DAY_MS,
101
+ documentPurgeGraceMs: config.documents.purge_grace_days * DAY_MS
92
102
  }
93
103
  }
94
104
 
@@ -127,7 +137,8 @@ function errorTrackingConfig(config: CloudDeploymentConfig, environment: CloudEn
127
137
  return {
128
138
  provider: tracking.provider,
129
139
  host: tracking.host,
130
- projectAPIKey: configuredText(environment, tracking.project_api_key)
140
+ projectAPIKey: configuredText(environment, tracking.project_api_key),
141
+ includeIds: tracking.include_ids
131
142
  }
132
143
  }
133
144
 
@@ -202,7 +213,9 @@ export function parseCloudDeploymentConfig(
202
213
  ...workerConfig(config),
203
214
  ...serviceConfig(config, environment),
204
215
  legal: legalConfig(config),
205
- community: config.community ? { workspaceId: config.community.workspace } : undefined,
216
+ community: config.community
217
+ ? { workspaceId: config.community.workspace, tourDocumentId: config.community.tour }
218
+ : undefined,
206
219
  branding: config.deployment.branding && {
207
220
  name: config.deployment.branding.name,
208
221
  logoURL: config.deployment.branding.logo_url,
@@ -16,5 +16,5 @@ export {
16
16
  CLOUD_DEFAULT_MAX_CONNECTIONS_PER_ROOM,
17
17
  type CloudTechnicalLimits
18
18
  } from './limits'
19
- export { cloudDiscoveryFromConfig, configuredSocialProviders } from './public'
19
+ export { cloudDiscoveryFromConfig } from './public'
20
20
  export { CloudConfigError, parseCloudServerConfig, type CloudServerConfig } from './schema'