@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
@@ -16,6 +16,7 @@ import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/doc
16
16
  import {
17
17
  createDocumentImages,
18
18
  currentImageUsage,
19
+ DOWNLOAD_LIFETIME_MS,
19
20
  documentImageLinks,
20
21
  revisionImageDownloads
21
22
  } from '#cloud/server/documents/images'
@@ -26,7 +27,11 @@ import {
26
27
  listSharedDocuments,
27
28
  workspaceRole
28
29
  } from '#cloud/server/documents/repository'
29
- import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'
30
+ import {
31
+ documentSummary,
32
+ getDocumentSummaryRow,
33
+ getRetainedDocumentSummaryRow
34
+ } from '#cloud/server/documents/summary'
30
35
  import {
31
36
  createDocumentTrash,
32
37
  DEFAULT_TRASH_OPTIONS,
@@ -40,8 +45,6 @@ import { storageLimitReached } from '#cloud/server/policy/storage'
40
45
  import { createStorageQuotaService, StorageQuotaExceededError } from '#cloud/server/quota'
41
46
  import type { Kysely } from 'kysely'
42
47
 
43
- const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
44
-
45
48
  export type DocumentServiceOptions = {
46
49
  policy?: CloudPolicy
47
50
  technicalMaximumUploadBytes?: number
@@ -71,8 +74,11 @@ export function createDocumentService(
71
74
  }
72
75
  }
73
76
 
74
- async function createDownload(documentId: string): Promise<DocumentDownload> {
75
- const row = await getDocumentSummaryRow(database, documentId)
77
+ async function createDownload(
78
+ documentId: string,
79
+ lookup: typeof getDocumentSummaryRow = getDocumentSummaryRow
80
+ ): Promise<DocumentDownload> {
81
+ const row = await lookup(database, documentId)
76
82
  if (!row?.currentRevisionId) throw new DocumentNotFoundError()
77
83
  const document: DocumentSummary = documentSummary(row)
78
84
  const revision = await database
@@ -158,6 +164,14 @@ export function createDocumentService(
158
164
  return createDownload(documentId)
159
165
  },
160
166
 
167
+ /**
168
+ * A document as it is now for a deployment administrator, taken down or in Trash included,
169
+ * to look at what was reported or blocked; the caller checks the administrator.
170
+ */
171
+ async downloadRetained(documentId: string): Promise<DocumentDownload> {
172
+ return createDownload(documentId, getRetainedDocumentSummaryRow)
173
+ },
174
+
161
175
  /** Links for images a live room names, for someone who may view the document. */
162
176
  async imageLinks(userId: string, documentId: string, checksums: string[]) {
163
177
  const access = await resolveDocumentAccess(database, userId, documentId)
@@ -36,3 +36,18 @@ export async function getDocumentSummaryRow(
36
36
  .where('disabledAt', 'is', null)
37
37
  .executeTakeFirst()
38
38
  }
39
+
40
+ /**
41
+ * A document the server still keeps, even one in Trash or taken down, which only a deployment
42
+ * administrator may reach; ordinary access goes through `getDocumentSummaryRow`.
43
+ */
44
+ export async function getRetainedDocumentSummaryRow(
45
+ database: DocumentDatabase,
46
+ documentId: string
47
+ ): Promise<DocumentSummaryRow | undefined> {
48
+ return database
49
+ .selectFrom('document')
50
+ .select(SUMMARY_COLUMNS)
51
+ .where('id', '=', documentId)
52
+ .executeTakeFirst()
53
+ }
@@ -1,7 +1,7 @@
1
1
  import {
2
- parseDuplicateDocumentVersion,
3
- parseSaveDocumentVersion,
4
- parseUpdateDocumentVersion
2
+ duplicateDocumentVersionSchema,
3
+ saveDocumentVersionSchema,
4
+ updateDocumentVersionSchema
5
5
  } from '#cloud/contract'
6
6
  import { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents/routes'
7
7
  import {
@@ -19,7 +19,6 @@ const pageSchema = v.object({
19
19
  before: v.optional(v.pipe(v.string(), v.uuid())),
20
20
  limit: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)))
21
21
  })
22
- const parsePage = (input: unknown) => v.parse(pageSchema, input)
23
22
 
24
23
  async function answer(context: Context, run: () => Promise<Response>): Promise<Response> {
25
24
  try {
@@ -34,7 +33,7 @@ async function answer(context: Context, run: () => Promise<Response>): Promise<R
34
33
  /** A document's version history: listing, naming, opening, restoring, and duplicating versions. */
35
34
  export function createDocumentVersionRoutes(service: DocumentVersionService) {
36
35
  return new Hono<DocumentRouteEnvironment>()
37
- .get('/documents/:documentId/versions', documentParams, validatedQuery(parsePage), (context) =>
36
+ .get('/documents/:documentId/versions', documentParams, validatedQuery(pageSchema), (context) =>
38
37
  answer(context, async () =>
39
38
  context.json(
40
39
  await service.list(
@@ -48,7 +47,7 @@ export function createDocumentVersionRoutes(service: DocumentVersionService) {
48
47
  .post(
49
48
  '/documents/:documentId/versions',
50
49
  documentParams,
51
- validatedJSON(parseSaveDocumentVersion),
50
+ validatedJSON(saveDocumentVersionSchema),
52
51
  (context) =>
53
52
  answer(context, async () =>
54
53
  context.json(
@@ -66,7 +65,7 @@ export function createDocumentVersionRoutes(service: DocumentVersionService) {
66
65
  .patch(
67
66
  '/documents/:documentId/versions/:versionId',
68
67
  documentVersionParams,
69
- validatedJSON(parseUpdateDocumentVersion),
68
+ validatedJSON(updateDocumentVersionSchema),
70
69
  (context) =>
71
70
  answer(context, async () =>
72
71
  context.json({
@@ -104,7 +103,7 @@ export function createDocumentVersionRoutes(service: DocumentVersionService) {
104
103
  .post(
105
104
  '/documents/:documentId/versions/:versionId/duplicate',
106
105
  documentVersionParams,
107
- validatedJSON(parseDuplicateDocumentVersion),
106
+ validatedJSON(duplicateDocumentVersionSchema),
108
107
  (context) =>
109
108
  answer(context, async () =>
110
109
  context.json(
@@ -11,7 +11,11 @@ import { workspaceRoleCan } from '#cloud/server/auth/access-control'
11
11
  import { userIdText, type CloudDatabase } from '#cloud/server/db'
12
12
  import { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'
13
13
  import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'
14
- import { copyRevisionImages, revisionImageDownloads } from '#cloud/server/documents/images'
14
+ import {
15
+ copyRevisionImages,
16
+ DOWNLOAD_LIFETIME_MS,
17
+ revisionImageDownloads
18
+ } from '#cloud/server/documents/images'
15
19
  import { findDocument, insertDocument, workspaceRole } from '#cloud/server/documents/repository'
16
20
  import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'
17
21
  import { logCloud, loggedError } from '#cloud/server/logging'
@@ -23,7 +27,6 @@ import type { Kysely, Transaction } from 'kysely'
23
27
  import { announceVersions, keepRevision } from './checkpoint'
24
28
  import { historyStart } from './history'
25
29
 
26
- const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
27
30
  const DEFAULT_PAGE_SIZE = 50
28
31
  const MAXIMUM_PAGE_SIZE = 100
29
32
 
@@ -3,6 +3,8 @@ import type { EmailLocale, TransactionalEmailKind } from '#cloud/email'
3
3
  import type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'
4
4
  import type { Kysely, Transaction } from 'kysely'
5
5
 
6
+ import { backoffDelay, HOUR_MS, SECOND_MS, type Backoff } from '@open-pencil/std/timing'
7
+
6
8
  import { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'
7
9
  import type {
8
10
  EnqueueTransactionalEmailInput,
@@ -13,7 +15,8 @@ import type {
13
15
  } from './types'
14
16
 
15
17
  const DEFAULT_MAXIMUM_ATTEMPTS = 5
16
- const MAXIMUM_RETRY_DELAY_MS = 60 * 60_000
18
+ /** Mail is retried patiently: a provider that refused it is rarely back within seconds. */
19
+ const EMAIL_RETRY: Backoff = { baseMs: 30 * SECOND_MS, capMs: HOUR_MS, jitter: false }
17
20
 
18
21
  export type TransactionalEmailTransportErrorKind =
19
22
  | 'configuration'
@@ -49,7 +52,7 @@ function normalizedEmail(value: string): string {
49
52
  }
50
53
 
51
54
  function retryDelayMilliseconds(attemptCount: number): number {
52
- return Math.min(MAXIMUM_RETRY_DELAY_MS, 2 ** Math.max(0, attemptCount - 1) * 30_000)
55
+ return backoffDelay(attemptCount - 1, EMAIL_RETRY)
53
56
  }
54
57
 
55
58
  function transportFailure(error: unknown): TransactionalEmailTransportError {
@@ -78,6 +81,8 @@ export function createTransactionalEmailService(
78
81
  options: {
79
82
  encryptionSecret: string
80
83
  from: string
84
+ /** Where replies go; mail clients answer `from` without it. */
85
+ replyTo?: string
81
86
  transport?: TransactionalEmailTransport
82
87
  }
83
88
  ): TransactionalEmailService {
@@ -217,6 +222,7 @@ export function createTransactionalEmailService(
217
222
  const sent = await options.transport.send({
218
223
  deliveryId: message.id,
219
224
  from: options.from,
225
+ replyTo: options.replyTo,
220
226
  to: message.recipientEmailNormalized,
221
227
  subject: rendered.subject,
222
228
  html: rendered.html,
@@ -10,6 +10,7 @@ import type { Transaction } from 'kysely'
10
10
  export type TransactionalEmailEnvelope = RenderedTransactionalEmail & {
11
11
  deliveryId: string
12
12
  from: string
13
+ replyTo?: string
13
14
  to: string
14
15
  headers: Record<string, string>
15
16
  }
@@ -3,6 +3,7 @@ import { loggedError, writeJSONLine, type CloudLogWriter } from '#cloud/server/l
3
3
  import type { Context, ErrorHandler } from 'hono'
4
4
  import { HTTPException } from 'hono/http-exception'
5
5
  import { routePath } from 'hono/route'
6
+ import * as v from 'valibot'
6
7
 
7
8
  /** Where the server caught an error. */
8
9
  export const CLOUD_ERROR_SOURCES = [
@@ -17,8 +18,10 @@ export const CLOUD_ERROR_SOURCES = [
17
18
  export type CloudErrorSource = (typeof CLOUD_ERROR_SOURCES)[number]
18
19
 
19
20
  /**
20
- * What the server knows about a caught error; never who made the request or what it carried. For a
21
- * request: its method, the route pattern it matched (not the path with its IDs), and its ID.
21
+ * What the server knows about a caught error. For a request: its method, the route pattern it
22
+ * matched, its ID, the signed-in user's account ID, and the IDs of the records its path names;
23
+ * never what it carried. Error tracking sends the account and record IDs only where the
24
+ * deployment's `[error_tracking]` sets `include_ids`; the server's own log always has them.
22
25
  */
23
26
  export type CloudErrorContext = ErrorReportContext<CloudErrorSource>
24
27
 
@@ -45,6 +48,8 @@ export function createLoggingErrorReporter(
45
48
  method: context.method,
46
49
  route: context.route,
47
50
  requestId: context.requestId,
51
+ userId: context.userId,
52
+ ...context.resources,
48
53
  error: loggedError(error)
49
54
  })
50
55
  } catch (failure) {
@@ -68,13 +73,53 @@ export function reportCloudError(
68
73
  return (reporter ?? logOnly)(error, { ...context, message })
69
74
  }
70
75
 
76
+ /**
77
+ * Path parameters that name a record by its ID. Others are left out: an invitation's or a
78
+ * continuation's ID is the link that grants it, and an OAuth callback's names a provider.
79
+ */
80
+ const RECORD_PARAMETERS = [
81
+ 'documentId',
82
+ 'workspaceId',
83
+ 'threadId',
84
+ 'commentId',
85
+ 'versionId',
86
+ 'revisionId',
87
+ 'shareId',
88
+ 'uploadId'
89
+ ] as const
90
+
91
+ const validatedParametersSchema = v.record(v.string(), v.unknown())
92
+
93
+ /**
94
+ * The record IDs the request's path named, as its route's parameter validator accepted them: a
95
+ * path no validator checked names none, so what a caller typed never reaches a report.
96
+ */
97
+ function requestResources(context: Context): Record<string, string> {
98
+ const validated = v.safeParse(validatedParametersSchema, context.req.valid('param' as never))
99
+ if (!validated.success) return {}
100
+ return Object.fromEntries(
101
+ RECORD_PARAMETERS.flatMap((name) => {
102
+ const id = validated.output[name]
103
+ return typeof id === 'string' ? [[name, id]] : []
104
+ })
105
+ )
106
+ }
107
+
71
108
  function requestContext(context: Context): CloudErrorContext {
72
109
  const requestId: unknown = context.get('requestId')
110
+ const actor: unknown = context.get('actor')
111
+ const resources = requestResources(context)
112
+ const userId =
113
+ actor && typeof actor === 'object' && 'userId' in actor && typeof actor.userId === 'string'
114
+ ? actor.userId
115
+ : undefined
73
116
  return {
74
117
  source: 'request',
75
118
  method: context.req.method,
76
119
  route: routePath(context),
77
- ...(typeof requestId === 'string' && { requestId })
120
+ ...(Object.keys(resources).length > 0 && { resources }),
121
+ ...(typeof requestId === 'string' && { requestId }),
122
+ ...(userId && { userId })
78
123
  }
79
124
  }
80
125
 
@@ -1,12 +1,14 @@
1
1
  export {
2
2
  adminErrorStatus,
3
3
  AdminDomainError,
4
+ approveEnrollmentByEmail,
4
5
  createAdminAuditService,
5
6
  createAdminEmailService,
6
7
  createAdminOperationsService,
7
8
  createAdminUserService,
8
9
  createCloudAdminRoutes,
9
10
  createEnrollmentService,
11
+ grantDeploymentAdminByEmail,
10
12
  normalizeEnrollmentEmail,
11
13
  type AdminAuditService,
12
14
  type AdminErrorCode,
@@ -41,6 +43,7 @@ export {
41
43
  createAuthenticationEmailService,
42
44
  createAccountAuthenticationService,
43
45
  createCloudAuthenticationRuntime,
46
+ enrollmentEmailOptions,
44
47
  createBetterAuthAdapter,
45
48
  createCloudIdentityResolver,
46
49
  createCloudSessionResolver,
@@ -61,6 +64,7 @@ export {
61
64
  type AccessRequest,
62
65
  type DocumentRole
63
66
  } from './auth'
67
+ export { configuredSocialProviders } from './auth/social-providers'
64
68
  export {
65
69
  createCloudAPIRouter,
66
70
  createPublicCloudAPIRouter,
@@ -125,7 +129,6 @@ export {
125
129
  CloudConfigError,
126
130
  cloudDeploymentConfigSchema,
127
131
  cloudDiscoveryFromConfig,
128
- configuredSocialProviders,
129
132
  parseCloudDeploymentConfig,
130
133
  parseCloudDeploymentSource,
131
134
  parseCloudDeploymentTOML,
@@ -142,6 +145,7 @@ export {
142
145
  export {
143
146
  createCloudDatabase,
144
147
  migrateCloudDatabase,
148
+ pendingCloudMigrations,
145
149
  type CloudDatabase,
146
150
  type CloudDatabaseOptions,
147
151
  type Document,
@@ -180,6 +184,16 @@ export {
180
184
  LIMITED_HISTORY_DAYS,
181
185
  type DocumentVersionService
182
186
  } from './documents/versions'
187
+ export {
188
+ COMMENT_EMAIL_BUDGET,
189
+ CommentConflictError,
190
+ CommentLimitError,
191
+ createCommentRoutes,
192
+ createCommentService,
193
+ createSharedCommentRoutes,
194
+ type CommentActor,
195
+ type CommentService
196
+ } from './comments'
183
197
  export {
184
198
  createInvitationOutbox,
185
199
  createTransactionalEmailService,
@@ -3,7 +3,8 @@ import { accountParams, validatedJSON } from '#cloud/server/validation'
3
3
  import { Hono } from 'hono'
4
4
  import { bearerAuth } from 'hono/bearer-auth'
5
5
 
6
- import { parseSetAccountEntitlements, type InternalService } from './service'
6
+ import { setAccountEntitlementsSchema } from './schema'
7
+ import type { InternalService } from './service'
7
8
 
8
9
  /** The internal API on HTTP, for runtimes without a private transport to their services. */
9
10
  export function createInternalRoutes(service: InternalService, serviceToken: string) {
@@ -22,7 +23,7 @@ export function createInternalRoutes(service: InternalService, serviceToken: str
22
23
  .put(
23
24
  '/accounts/:userId/entitlements',
24
25
  accountParams,
25
- validatedJSON(parseSetAccountEntitlements),
26
+ validatedJSON(setAccountEntitlementsSchema),
26
27
  async (context) => {
27
28
  const { userId } = context.req.valid('param')
28
29
  const result = await service.setAccountEntitlements(userId, context.req.valid('json'))
@@ -30,4 +31,9 @@ export function createInternalRoutes(service: InternalService, serviceToken: str
30
31
  return context.json({ applied: result.applied })
31
32
  }
32
33
  )
34
+ .get('/accounts/:userId/seats', accountParams, async (context) => {
35
+ const seats = await service.accountSeats(context.req.valid('param').userId)
36
+ if (seats === null) return context.json({ error: { code: 'not_found' as const } }, 404)
37
+ return context.json({ seats })
38
+ })
33
39
  }
@@ -1,3 +1,4 @@
1
+ import { accountSeats } from '#cloud/server/billing/seats'
1
2
  import type { CloudDatabase } from '#cloud/server/db'
2
3
  import { createAccountEntitlementRepository } from '#cloud/server/policy'
3
4
  import type { Kysely } from 'kysely'
@@ -31,6 +32,15 @@ export function createInternalService(database: Kysely<CloudDatabase>) {
31
32
  if (!account) return { found: false, applied: false }
32
33
  const { applied } = await entitlements.setVersioned(account, values, source, externalVersion)
33
34
  return { found: true, applied }
35
+ },
36
+
37
+ /**
38
+ * How many people can edit across the workspaces an account owns, which billing charges a
39
+ * seat for; `null` for an unknown account.
40
+ */
41
+ async accountSeats(userId: string): Promise<number | null> {
42
+ const account = await entitlements.account(userId)
43
+ return account ? accountSeats(database, userId) : null
34
44
  }
35
45
  }
36
46
  }
@@ -2,13 +2,15 @@ import type { CloudDatabase } from '#cloud/server/db'
2
2
  import { lockForTransaction } from '#cloud/server/db/expressions'
3
3
  import type { Transaction } from 'kysely'
4
4
 
5
+ import { DAY_MS } from '@open-pencil/std/timing'
6
+
5
7
  /**
6
8
  * How many invitations, to documents and workspaces alike, one person may send in a day, and how
7
9
  * many one address may receive from everyone. Each sends an email naming the inviter and the file,
8
10
  * both of which the sender chooses, so without a daily budget invitations are a way to send spam.
9
11
  */
10
12
  export const INVITATION_BUDGET = {
11
- windowMs: 24 * 60 * 60 * 1000,
13
+ windowMs: DAY_MS,
12
14
  perSender: 100,
13
15
  perRecipient: 5
14
16
  } as const
@@ -1,4 +1,5 @@
1
1
  export { INVITATION_BUDGET, InvitationLimitError, spendInvitationBudget } from './budget'
2
+ export { INVITATION_LIFETIME_MS, INVITATION_SECRET_BYTES } from './links'
2
3
  export {
3
4
  noOpInvitationDelivery,
4
5
  type DocumentInvitationMessage,
@@ -0,0 +1,6 @@
1
+ import { DAY_MS } from '@open-pencil/std/timing'
2
+
3
+ /** How many random bytes an invitation link's secret has. */
4
+ export const INVITATION_SECRET_BYTES = 24
5
+ /** How long an invitation link works, for a document or a workspace alike. */
6
+ export const INVITATION_LIFETIME_MS = 7 * DAY_MS
@@ -7,6 +7,8 @@ import { imageSize } from 'image-size'
7
7
  import type { Kysely } from 'kysely'
8
8
  import * as v from 'valibot'
9
9
 
10
+ import { DEADLINE_MS } from '@open-pencil/std/timing'
11
+
10
12
  /** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */
11
13
  export const PICTURE_PATH = '/api/pictures'
12
14
  /** The longest side a stored picture may have; pages send 256 pixels. */
@@ -14,7 +16,7 @@ const PICTURE_MAX_SIDE = 1024
14
16
  /** How many hex digits of the checksum name a picture in its address. */
15
17
  const PICTURE_VERSION_LENGTH = 16
16
18
  /** How long a linked account's picture may take to fetch before sign-in goes on without it. */
17
- const PROVIDER_PICTURE_TIMEOUT_MS = 5000
19
+ const PROVIDER_PICTURE_TIMEOUT_MS = DEADLINE_MS.request
18
20
  /** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */
19
21
  const PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']
20
22
  const PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }
@@ -5,6 +5,9 @@ import type { CloudPolicyContext } from './keys'
5
5
 
6
6
  type WorkspacePolicyTarget = { workspaceId: string } | { documentId: string }
7
7
 
8
+ /** A policy context for a workspace, which names it. */
9
+ type WorkspacePolicyContext = CloudPolicyContext & { workspaceId: string }
10
+
8
11
  /**
9
12
  * The policy context for a workspace, or for a document by its workspace: its owner's plan, which
10
13
  * every workspace they own takes, so creating more workspaces adds no allowance. Null when the
@@ -14,7 +17,7 @@ export async function workspacePolicyContext(
14
17
  database: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
15
18
  target: WorkspacePolicyTarget,
16
19
  context: Pick<CloudPolicyContext, 'actorId' | 'deploymentMode'>
17
- ): Promise<(CloudPolicyContext & { workspaceId: string }) | null> {
20
+ ): Promise<WorkspacePolicyContext | null> {
18
21
  const row =
19
22
  'documentId' in target
20
23
  ? await database
@@ -29,7 +32,7 @@ export async function workspacePolicyContext(
29
32
  .where('id', '=', target.workspaceId)
30
33
  .executeTakeFirst()
31
34
  if (!row) return null
32
- const policyContext: CloudPolicyContext & { workspaceId: string } = {
35
+ const policyContext: WorkspacePolicyContext = {
33
36
  targetingKey: row.ownerId,
34
37
  subjectType: 'user',
35
38
  workspaceId: row.workspaceId,
@@ -1,4 +1,4 @@
1
- import { parseFileDocumentReport } from '#cloud/contract'
1
+ import { fileDocumentReportSchema } from '#cloud/contract'
2
2
  import { acceptedLocale } from '#cloud/email'
3
3
  import type { CloudSessionResolver } from '#cloud/server/auth'
4
4
  import { shareActor } from '#cloud/server/sharing/actor'
@@ -16,7 +16,7 @@ export function createPublicReportRoutes(
16
16
  return new Hono().post(
17
17
  '/shares/:shareId/reports',
18
18
  shareParams,
19
- validatedJSON(parseFileDocumentReport),
19
+ validatedJSON(fileDocumentReportSchema),
20
20
  async (context) => {
21
21
  try {
22
22
  return await sharingRoute(context, async () => {
@@ -6,12 +6,14 @@ import type { TransactionalEmailService } from '#cloud/server/email'
6
6
  import type { DocumentSharingService } from '#cloud/server/sharing'
7
7
  import type { Kysely } from 'kysely'
8
8
 
9
+ import { DAY_MS } from '@open-pencil/std/timing'
10
+
9
11
  /**
10
12
  * How many reports one person, or guest, may file about one link in a day, and how many a link
11
13
  * may gather from everyone, since a guest names themselves and could otherwise flood the queue.
12
14
  */
13
15
  export const DOCUMENT_REPORT_BUDGET = {
14
- windowMs: 24 * 60 * 60 * 1000,
16
+ windowMs: DAY_MS,
15
17
  perReporter: 3,
16
18
  perShare: 50
17
19
  } as const
@@ -1,4 +1,4 @@
1
- import { parseCreateServicesToken } from '#cloud/contract'
1
+ import { createServicesTokenSchema } from '#cloud/contract'
2
2
  import type { CloudActor } from '#cloud/server/auth'
3
3
  import type { CloudDatabase } from '#cloud/server/db'
4
4
  import { DocumentNotFoundError } from '#cloud/server/documents'
@@ -26,7 +26,7 @@ export function createServicesRoutes(
26
26
  }
27
27
  return router.post(
28
28
  '/services/token',
29
- validatedJSON(parseCreateServicesToken),
29
+ validatedJSON(createServicesTokenSchema),
30
30
  async (context) => {
31
31
  if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)
32
32
  try {
@@ -14,7 +14,7 @@ import { workspacePolicyContext } from '#cloud/server/policy/workspace'
14
14
  import type { Kysely, UpdateObject } from 'kysely'
15
15
  import * as v from 'valibot'
16
16
 
17
- import { randomHex } from '@open-pencil/scene-graph/random'
17
+ import { randomHex } from '@open-pencil/std/random'
18
18
 
19
19
  import { advanceCollaborationEpoch, requireSharingAccess } from '../access'
20
20
  import { shareContract } from '../contracts'
@@ -1,4 +1,4 @@
1
- import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'
1
+ import { requestSharedImageLinksSchema, resolveDocumentShareSchema } from '#cloud/contract'
2
2
  import type { CloudSessionResolver } from '#cloud/server/auth'
3
3
  import type { DocumentService } from '#cloud/server/documents'
4
4
  import type { DocumentSharingService } from '#cloud/server/sharing'
@@ -17,7 +17,7 @@ export function createPublicDocumentRoutes(
17
17
  .post(
18
18
  '/shares/:shareId/document',
19
19
  shareParams,
20
- validatedJSON(parseResolveDocumentShare),
20
+ validatedJSON(resolveDocumentShareSchema),
21
21
  (context) =>
22
22
  sharingRoute(context, async () => {
23
23
  const resolution = await sharing.resolveShare(
@@ -34,7 +34,7 @@ export function createPublicDocumentRoutes(
34
34
  .post(
35
35
  '/shares/:shareId/images',
36
36
  shareParams,
37
- validatedJSON(parseRequestSharedImageLinks),
37
+ validatedJSON(requestSharedImageLinksSchema),
38
38
  (context) =>
39
39
  sharingRoute(context, async () => {
40
40
  const { checksums, ...share } = context.req.valid('json')
@@ -12,6 +12,8 @@ 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,
16
18
  type DocumentInvitationMessage,
17
19
  type InvitationDelivery,
@@ -19,7 +21,7 @@ import {
19
21
  } from '#cloud/server/invitations'
20
22
  import type { Kysely } from 'kysely'
21
23
 
22
- import { randomHex } from '@open-pencil/scene-graph/random'
24
+ import { randomHex } from '@open-pencil/std/random'
23
25
 
24
26
  import { requireSharingAccess } from '../access'
25
27
  import {
@@ -32,9 +34,6 @@ import { dateString, grantContract, invitationContract } from '../contracts'
32
34
  import { hashCapability } from '../crypto'
33
35
  import { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'
34
36
 
35
- const INVITATION_SECRET_BYTES = 24
36
- const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
37
-
38
37
  /** Workspace invitations share the invitation link; their ids are not document invitations. */
39
38
  export type WorkspaceInvitationResolver = {
40
39
  preview(invitationId: string, token: string): Promise<InvitationPreview | null>