@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
@@ -11,16 +11,22 @@ import { isUUID } from '#cloud/admin/schema'
11
11
  import {
12
12
  cloudAdminDocumentFilterSchema,
13
13
  type CloudAdminDocument,
14
- type CloudAdminDocumentFilter
14
+ type CloudAdminDocumentFilter,
15
+ type DocumentDownload
15
16
  } from '#cloud/contract'
16
17
  import { userIdText, type CloudDatabase } from '#cloud/server/db'
18
+ import { DocumentNotFoundError } from '#cloud/server/documents/errors'
17
19
  import { unmarkPurged } from '#cloud/server/documents/purge'
20
+ import type { DocumentService } from '#cloud/server/documents/service'
18
21
  import type { TransactionalEmailService } from '#cloud/server/email'
22
+ import type { ObjectStore } from '#cloud/server/objects'
19
23
  import { tellReporters } from '#cloud/server/reports'
20
24
  import { dateString } from '#cloud/server/sharing/contracts'
21
25
  import { uniq } from 'es-toolkit'
22
26
  import type { ExpressionBuilder, Kysely, Transaction } from 'kysely'
23
27
 
28
+ import { extractFigThumbnailFromReader } from '@open-pencil/fig'
29
+
24
30
  type DocumentExpression = ExpressionBuilder<CloudDatabase, 'document'>
25
31
 
26
32
  /** Whether reports about the document are still waiting for a decision. */
@@ -77,6 +83,26 @@ function searchCondition(search: string) {
77
83
  ])
78
84
  }
79
85
 
86
+ /** Where the console finds what it shows of documents besides their rows. */
87
+ export type AdminDocumentsOptions = {
88
+ /** How long a document deleted forever waits before cleanup destroys it. */
89
+ purgeGraceMs?: number
90
+ /** The workspace whose documents are the deployment's community gallery, if it has one. */
91
+ communityWorkspaceId?: string | null
92
+ }
93
+
94
+ /** A share link that still opens its document: not revoked, and not expired by `now`. */
95
+ function liveShare(now: Date) {
96
+ return (expression: ExpressionBuilder<CloudDatabase, 'documentShare'>) =>
97
+ expression.and([
98
+ expression('documentShare.revokedAt', 'is', null),
99
+ expression.or([
100
+ expression('documentShare.expiresAt', 'is', null),
101
+ expression('documentShare.expiresAt', '>', now)
102
+ ])
103
+ ])
104
+ }
105
+
80
106
  /**
81
107
  * The documents with these IDs as the console shows them, in no particular order; with
82
108
  * `purgeGraceMs`, when cleanup destroys one deleted forever.
@@ -84,22 +110,25 @@ function searchCondition(search: string) {
84
110
  export async function adminDocuments(
85
111
  database: Kysely<CloudDatabase>,
86
112
  documentIds: readonly string[],
87
- purgeGraceMs?: number
113
+ { purgeGraceMs, communityWorkspaceId = null }: AdminDocumentsOptions = {}
88
114
  ): Promise<Map<string, CloudAdminDocument>> {
89
115
  const ids = uniq(documentIds).filter(isUUID)
90
116
  if (ids.length === 0) return new Map()
117
+ const now = new Date()
91
118
  const rows = await database
92
119
  .selectFrom('document')
93
120
  .innerJoin('workspace', 'workspace.id', 'document.workspaceId')
94
121
  .select((expression) => [
95
122
  'document.id',
96
123
  'document.name',
124
+ 'document.kind',
97
125
  'document.createdBy',
98
126
  'document.createdAt',
99
127
  'document.updatedAt',
100
128
  'document.disabledAt',
101
129
  'document.disabledReason',
102
130
  'document.purgedAt',
131
+ 'document.currentRevisionId',
103
132
  'workspace.id as workspaceId',
104
133
  'workspace.name as workspaceName',
105
134
  expression
@@ -107,7 +136,20 @@ export async function adminDocuments(
107
136
  .select((inner) => inner.fn.countAll<string>().as('count'))
108
137
  .whereRef('documentReport.documentId', '=', 'document.id')
109
138
  .where('documentReport.status', '=', 'open')
110
- .as('openReports')
139
+ .as('openReports'),
140
+ expression
141
+ .selectFrom('documentShare')
142
+ .select((inner) => inner.fn.countAll<string>().as('count'))
143
+ .whereRef('documentShare.documentId', '=', 'document.id')
144
+ .where(liveShare(now))
145
+ .as('links'),
146
+ expression
147
+ .selectFrom('documentShare')
148
+ .select((inner) => inner.fn.countAll<string>().as('count'))
149
+ .whereRef('documentShare.documentId', '=', 'document.id')
150
+ .where(liveShare(now))
151
+ .where('documentShare.permission', '=', 'edit')
152
+ .as('editLinks')
111
153
  ])
112
154
  .where('document.id', 'in', ids)
113
155
  .execute()
@@ -126,6 +168,7 @@ export async function adminDocuments(
126
168
  {
127
169
  id: row.id,
128
170
  name: row.name,
171
+ kind: row.kind,
129
172
  workspace: { id: row.workspaceId, name: row.workspaceName },
130
173
  owner: ownerById.get(row.createdBy) ?? null,
131
174
  createdAt: dateString(row.createdAt) ?? '',
@@ -134,6 +177,12 @@ export async function adminDocuments(
134
177
  disabledReason: row.disabledReason,
135
178
  openReports: Number(row.openReports ?? 0),
136
179
  purgedAt: dateString(row.purgedAt),
180
+ revisionId: row.currentRevisionId,
181
+ exposure: {
182
+ community: communityWorkspaceId !== null && row.workspaceId === communityWorkspaceId,
183
+ links: Number(row.links ?? 0),
184
+ editLinks: Number(row.editLinks ?? 0)
185
+ },
137
186
  destroyedAt:
138
187
  row.purgedAt === null || purgeGraceMs === undefined
139
188
  ? null
@@ -185,6 +234,12 @@ export type AdminDocumentServiceOptions = {
185
234
  closeRooms?: (documentId: string) => void
186
235
  /** How long a document deleted forever waits before cleanup destroys it; 0 when not given. */
187
236
  purgeGraceMs?: number
237
+ /** The workspace whose documents are the deployment's community gallery, if it has one. */
238
+ communityWorkspaceId?: string | null
239
+ /** Where documents are stored, for their thumbnails; without it none has one. */
240
+ objects?: Pick<ObjectStore, 'readRange'>
241
+ /** Documents' downloads; without it none can be downloaded. */
242
+ documents?: Pick<DocumentService, 'downloadRetained'>
188
243
  /**
189
244
  * Tells the owner of a document's workspace when it is blocked and restored. Without it, or
190
245
  * without the server's address its link needs, nobody is told.
@@ -243,7 +298,7 @@ export function createAdminDocumentService(
243
298
  const documents = await adminDocuments(
244
299
  database,
245
300
  page.map((row) => row.id),
246
- purgeGraceMs
301
+ { purgeGraceMs, communityWorkspaceId: options.communityWorkspaceId }
247
302
  )
248
303
  return {
249
304
  documents: page.flatMap((row) => documents.get(row.id) ?? []),
@@ -252,6 +307,66 @@ export function createAdminDocumentService(
252
307
  }
253
308
  },
254
309
 
310
+ /**
311
+ * The thumbnail a document's stored file carries at `revisionId`, read from storage in ranges
312
+ * as the community gallery reads its own; null when that revision is not current any more,
313
+ * its file is gone, or it carries none.
314
+ */
315
+ /** Whether `revisionId` is still the document's saved state, so a copy of its thumbnail holds. */
316
+ async isCurrentRevision(documentId: string, revisionId: string): Promise<boolean> {
317
+ const row = await database
318
+ .selectFrom('document')
319
+ .select('id')
320
+ .where('id', '=', documentId)
321
+ .where('currentRevisionId', '=', revisionId)
322
+ .executeTakeFirst()
323
+ return row !== undefined
324
+ },
325
+
326
+ async thumbnail(documentId: string, revisionId: string): Promise<Uint8Array | null> {
327
+ const { objects } = options
328
+ if (!objects) return null
329
+ const row = await database
330
+ .selectFrom('document')
331
+ .innerJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')
332
+ .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
333
+ .select(['storageObject.objectKey', 'storageObject.byteSize'])
334
+ .where('document.id', '=', documentId)
335
+ .where('document.currentRevisionId', '=', revisionId)
336
+ .executeTakeFirst()
337
+ if (!row) return null
338
+ const gone = new Error('The document’s stored file is gone')
339
+ try {
340
+ return await extractFigThumbnailFromReader({
341
+ size: Number(row.byteSize),
342
+ read: async (start, endExclusive) => {
343
+ const bytes = await objects.readRange(row.objectKey, start, endExclusive)
344
+ if (!bytes) throw gone
345
+ return bytes
346
+ }
347
+ })
348
+ } catch (error) {
349
+ if (error === gone) return null
350
+ throw error
351
+ }
352
+ },
353
+
354
+ /**
355
+ * Links to download a document as it is now, its file and images, for an administrator to look
356
+ * at it outside any editor, taken down or in Trash included, recorded in the audit log. A
357
+ * document never saved has none.
358
+ */
359
+ async download(actorId: string, documentId: string): Promise<DocumentDownload> {
360
+ if (!options.documents) throw new DocumentNotFoundError()
361
+ // A taken-down document too: looking at it is what moderating it takes.
362
+ const download = await options.documents.downloadRetained(documentId)
363
+ await auditContentAction(database, actorId, 'document.downloaded', {
364
+ type: 'document',
365
+ id: documentId
366
+ })
367
+ return download
368
+ },
369
+
255
370
  /**
256
371
  * Takes a document down: it opens for nobody, its owner included, its links stop working,
257
372
  * and its live rooms close, saved. Its open reports count as acted on. Nothing is deleted and
@@ -17,6 +17,7 @@ import type { Kysely } from 'kysely'
17
17
  const ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {
18
18
  'enrollment-requested': 'pending',
19
19
  'enrollment-approved': 'approved',
20
+ 'enrollment-invited': 'approved',
20
21
  'enrollment-rejected': 'rejected',
21
22
  'enrollment-revoked': 'revoked'
22
23
  }
@@ -114,7 +115,7 @@ export function createAdminEmailService(
114
115
  payload: {
115
116
  name: enrollment.name ?? 'there',
116
117
  actionURL:
117
- kind === 'enrollment-approved'
118
+ kind === 'enrollment-approved' || kind === 'enrollment-invited'
118
119
  ? links.publicURL
119
120
  : new URL('/auth/sign-in', links.publicURL).href
120
121
  }
@@ -12,6 +12,11 @@ export type EnrollmentEmailOptions = {
12
12
  publicURL: string
13
13
  adminRecipients: string[]
14
14
  email?: TransactionalEmailService
15
+ /**
16
+ * Whether an approval may carry the founder's letter (`enrollment-invited`) instead of the
17
+ * plain approval: only on the official deployment, whose letter it is.
18
+ */
19
+ invitations?: boolean
15
20
  }
16
21
 
17
22
  export async function enqueueEnrollmentRequested(
@@ -56,20 +61,29 @@ export async function enqueueEnrollmentReview(
56
61
  name: string
57
62
  status: Exclude<EnrollmentStatus, 'pending'>
58
63
  reviewedAt: Date
64
+ /** An approval that sends the letter instead of the plain approval. */
65
+ invite?: boolean
66
+ /** The person joined openpencil.dev's waitlist rather than asking here; the letter says so. */
67
+ waitlist?: boolean
59
68
  }
60
69
  ): Promise<void> {
61
70
  if (!options.email) return
71
+ const kind =
72
+ input.status === 'approved' && input.invite
73
+ ? ('enrollment-invited' as const)
74
+ : (`enrollment-${input.status}` as const)
62
75
  await options.email.enqueue(
63
76
  {
64
- idempotencyKey: `enrollment-${input.status}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,
65
- kind: `enrollment-${input.status}`,
77
+ idempotencyKey: `${kind}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,
78
+ kind,
66
79
  recipientEmail: input.recipientEmail,
67
80
  payload: {
68
81
  name: input.name,
69
82
  actionURL:
70
83
  input.status === 'approved'
71
84
  ? options.publicURL
72
- : new URL('/auth/sign-in', options.publicURL).href
85
+ : new URL('/auth/sign-in', options.publicURL).href,
86
+ ...(kind === 'enrollment-invited' && input.waitlist && { waitlist: true as const })
73
87
  }
74
88
  },
75
89
  transaction
@@ -11,7 +11,7 @@ import { isUUID } from '#cloud/admin/schema'
11
11
  import { enrollmentStatusSchema } from '#cloud/contract'
12
12
  import type { CloudDatabase } from '#cloud/server/db'
13
13
  import { compact, uniq } from 'es-toolkit'
14
- import type { Kysely } from 'kysely'
14
+ import { NoResultError, type Kysely } from 'kysely'
15
15
 
16
16
  import {
17
17
  enqueueEnrollmentRequested,
@@ -22,8 +22,23 @@ import {
22
22
  export type EnrollmentStatus = 'pending' | 'approved' | 'rejected' | 'revoked'
23
23
  export type EnrollmentMode = 'open' | 'approval' | 'closed'
24
24
 
25
- export type EnrollmentRequestInput = { email: string; name?: string; reason?: string }
26
- export type EnrollmentReviewInput = { note?: string }
25
+ export type EnrollmentRequestInput = {
26
+ email: string
27
+ name?: string
28
+ reason?: string
29
+ /** Someone an administrator recorded from openpencil.dev's waitlist, who asked nowhere here. */
30
+ source?: 'waitlist'
31
+ }
32
+ export type EnrollmentReviewInput = {
33
+ note?: string
34
+ /** An approval that sends the founder's letter instead of the plain approval. */
35
+ invite?: boolean
36
+ /**
37
+ * The status the reviewer saw, checked under the row's lock: a request another administrator
38
+ * decided meanwhile is refused rather than decided again.
39
+ */
40
+ expectedStatus?: EnrollmentStatus
41
+ }
27
42
  export type EnrollmentRecord = {
28
43
  id: string
29
44
  email: string
@@ -102,17 +117,21 @@ export function createEnrollmentService(
102
117
  .executeTakeFirst()
103
118
  return row?.status ?? null
104
119
  }
105
- return {
106
- async request(input: EnrollmentRequestInput): Promise<void> {
120
+ const service = {
121
+ /**
122
+ * Records a request, or leaves one that is waiting or approved as it is, source and all:
123
+ * someone who asked here keeps the letter for asking. Says which it did.
124
+ */
125
+ async request(input: EnrollmentRequestInput): Promise<'recorded' | 'unchanged'> {
107
126
  const emailNormalized = normalizeEnrollmentEmail(input.email)
108
- await database.transaction().execute(async (transaction) => {
127
+ return database.transaction().execute(async (transaction) => {
109
128
  const existing = await transaction
110
129
  .selectFrom('enrollment')
111
130
  .selectAll()
112
131
  .where('emailNormalized', '=', emailNormalized)
113
132
  .forUpdate()
114
133
  .executeTakeFirst()
115
- if (existing?.status === 'approved' || existing?.status === 'pending') return
134
+ if (existing?.status === 'approved' || existing?.status === 'pending') return 'unchanged'
116
135
  const revision = (existing?.requestRevision ?? 0) + 1
117
136
  const values = {
118
137
  name: input.name?.trim() || existing?.name || null,
@@ -121,7 +140,8 @@ export function createEnrollmentService(
121
140
  reviewedAt: null,
122
141
  reviewedBy: null,
123
142
  reviewNote: null,
124
- requestRevision: revision
143
+ requestRevision: revision,
144
+ source: input.source ?? null
125
145
  }
126
146
  let row: EnrollmentRow
127
147
  if (existing) {
@@ -150,6 +170,7 @@ export function createEnrollmentService(
150
170
  reason: row.reason ?? 'No reason provided.',
151
171
  revision
152
172
  })
173
+ return 'recorded'
153
174
  })
154
175
  },
155
176
  statusForEmail,
@@ -209,7 +230,10 @@ export function createEnrollmentService(
209
230
  .where('id', '=', enrollmentId)
210
231
  .forUpdate()
211
232
  .executeTakeFirstOrThrow()
212
- if (!ALLOWED_TRANSITIONS[current.status].has(status)) {
233
+ if (
234
+ !ALLOWED_TRANSITIONS[current.status].has(status) ||
235
+ (input.expectedStatus !== undefined && current.status !== input.expectedStatus)
236
+ ) {
213
237
  throw new AdminDomainError(
214
238
  'invalid_enrollment_transition',
215
239
  `Enrollment cannot transition from ${current.status} to ${status}`
@@ -254,11 +278,47 @@ export function createEnrollmentService(
254
278
  recipientEmail: row.emailNormalized,
255
279
  name: row.name ?? 'there',
256
280
  status,
257
- reviewedAt: now
281
+ reviewedAt: now,
282
+ invite: input.invite,
283
+ waitlist: row.source === 'waitlist'
258
284
  })
259
285
  return enrollmentRecord(row)
260
286
  })
261
287
  },
288
+ /**
289
+ * Approves every waiting request and sends each person the founder's letter instead of the
290
+ * plain approval, on the official deployment. Each approval is its own review, so one that
291
+ * another administrator decided meanwhile is skipped rather than undoing the rest.
292
+ */
293
+ async invitePending(actorId: string): Promise<{ invited: number }> {
294
+ // Approving everyone without the letters going out would be a silent bulk approval.
295
+ if (!emailOptions.invitations || !emailOptions.email) {
296
+ throw new AdminDomainError(
297
+ 'invitations_unavailable',
298
+ 'Only the official deployment, with email configured, sends invitation letters'
299
+ )
300
+ }
301
+ const pending = await database
302
+ .selectFrom('enrollment')
303
+ .select('id')
304
+ .where('status', '=', 'pending')
305
+ .orderBy('requestedAt')
306
+ .execute()
307
+ let invited = 0
308
+ for (const { id } of pending) {
309
+ try {
310
+ await service.review(actorId, id, 'approved', {
311
+ invite: true,
312
+ expectedStatus: 'pending'
313
+ })
314
+ invited++
315
+ } catch (error) {
316
+ // Decided by someone else meanwhile, or gone with an address change: skip it.
317
+ if (!(error instanceof AdminDomainError) && !(error instanceof NoResultError)) throw error
318
+ }
319
+ }
320
+ return { invited }
321
+ },
262
322
  async bindApprovedUser(email: string, userId: string): Promise<void> {
263
323
  await database
264
324
  .updateTable('enrollment')
@@ -304,5 +364,6 @@ export function createEnrollmentService(
304
364
  return Number(row.count)
305
365
  }
306
366
  }
367
+ return service
307
368
  }
308
369
  export type EnrollmentService = ReturnType<typeof createEnrollmentService>
@@ -1,9 +1,13 @@
1
1
  export type AdminErrorCode =
2
2
  | 'invalid_enrollment_transition'
3
+ | 'invitations_unavailable'
3
4
  | 'last_admin_required'
4
5
  | 'self_admin_action_forbidden'
6
+ | 'last_authentication_method'
7
+ | 'account_approved'
5
8
  | 'email_regeneration_unavailable'
6
9
  | 'mfa_required'
10
+ | 'two_step_unconfirmed'
7
11
  | 'document_not_restorable'
8
12
  | 'workspace_gone'
9
13
 
@@ -19,6 +23,7 @@ export class AdminDomainError extends Error {
19
23
 
20
24
  const CONFLICTS = new Set<AdminErrorCode>([
21
25
  'invalid_enrollment_transition',
26
+ 'account_approved',
22
27
  'document_not_restorable',
23
28
  'workspace_gone'
24
29
  ])
@@ -4,6 +4,7 @@ export {
4
4
  type CloudAdminRoutes,
5
5
  type CloudAdminServices
6
6
  } from './api/routes'
7
+ export { approveEnrollmentByEmail, grantDeploymentAdminByEmail } from './bootstrap'
7
8
  export { createAdminAuditService, type AdminAuditService } from './audit/service'
8
9
  export { createAdminEmailService, type AdminEmailService } from './email/service'
9
10
  export { PostgresRateLimitStore } from '#cloud/server/rate-limit'
@@ -1,4 +1,8 @@
1
- import { adminDocuments, auditContentAction } from '#cloud/admin/documents/service'
1
+ import {
2
+ adminDocuments,
3
+ auditContentAction,
4
+ type AdminDocumentsOptions
5
+ } from '#cloud/admin/documents/service'
2
6
  import {
3
7
  containsPattern,
4
8
  countEachFilter,
@@ -48,7 +52,8 @@ function searchCondition(search: string) {
48
52
  /** Reports' administration, which tells each reporter who left an address what it decided. */
49
53
  export function createAdminReportService(
50
54
  database: Kysely<CloudDatabase>,
51
- replies: ReportReplies = {}
55
+ replies: ReportReplies = {},
56
+ documentOptions: Pick<AdminDocumentsOptions, 'communityWorkspaceId'> = {}
52
57
  ) {
53
58
  return {
54
59
  /** A page of reports, newest first, and how many match the search under each filter. */
@@ -74,7 +79,8 @@ export function createAdminReportService(
74
79
  const [documents, shares, reporters] = await Promise.all([
75
80
  adminDocuments(
76
81
  database,
77
- rows.map((row) => row.documentId)
82
+ rows.map((row) => row.documentId),
83
+ documentOptions
78
84
  ),
79
85
  shareIds.length
80
86
  ? database
@@ -21,14 +21,15 @@ export const userMutationSchema = v.object({
21
21
  reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))
22
22
  })
23
23
 
24
+ /** One of an account's sign-in methods, as the person's page lists them. */
25
+ export const signInMethodMutationSchema = v.object({
26
+ userId: v.pipe(v.string(), v.trim(), v.minLength(1)),
27
+ methodId: v.pipe(v.string(), v.trim(), v.minLength(1))
28
+ })
29
+
24
30
  /** Why an administrator takes a document down, which the audit log keeps. */
25
31
  export const documentTakedownSchema = v.object({
26
32
  reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))
27
33
  })
28
34
 
29
35
  export type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>
30
-
31
- export const parseEnrollmentReview = (input: unknown) => v.parse(enrollmentReviewSchema, input)
32
- export const parseUserMutation = (input: unknown) => v.parse(userMutationSchema, input)
33
- export const parseUserRoleMutation = (input: unknown) => v.parse(userRoleMutationSchema, input)
34
- export const parseDocumentTakedown = (input: unknown) => v.parse(documentTakedownSchema, input)