@open-pencil/cloud 0.17.0-beta.5 → 0.17.0-beta.7

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 (188) 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 +8690 -6325
  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 +13807 -7638
  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 +10659 -8650
  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/runtime/site/server.ts +4 -1
  105. package/src/server/account/actions.ts +3 -1
  106. package/src/server/account/deletion.ts +38 -4
  107. package/src/server/account/routes.ts +67 -46
  108. package/src/server/account/tokens.ts +3 -3
  109. package/src/server/api/router.ts +22 -7
  110. package/src/server/app/checks.ts +6 -1
  111. package/src/server/app/cors.ts +44 -0
  112. package/src/server/app/index.ts +76 -76
  113. package/src/server/app/routes.ts +14 -5
  114. package/src/server/app/services.ts +49 -15
  115. package/src/server/auth/access-control.ts +13 -8
  116. package/src/server/auth/account.ts +13 -12
  117. package/src/server/auth/activity.ts +7 -2
  118. package/src/server/auth/adapter.ts +16 -3
  119. package/src/server/auth/email.ts +29 -17
  120. package/src/server/auth/endpoints.ts +4 -0
  121. package/src/server/auth/factory.ts +83 -64
  122. package/src/server/auth/index.ts +1 -1
  123. package/src/server/auth/methods.ts +162 -0
  124. package/src/server/auth/mfa-assurance.ts +147 -10
  125. package/src/server/auth/rate-limit.ts +31 -0
  126. package/src/server/auth/runtime.ts +19 -5
  127. package/src/server/auth/social-providers.ts +70 -24
  128. package/src/server/billing/index.ts +2 -0
  129. package/src/server/billing/notify.ts +55 -0
  130. package/src/server/billing/seats.ts +17 -0
  131. package/src/server/billing/tokens.ts +1 -1
  132. package/src/server/cleanup/documents.ts +5 -2
  133. package/src/server/cleanup/revisions.ts +6 -3
  134. package/src/server/cleanup/uploads.ts +2 -1
  135. package/src/server/collaboration/relay/connection.ts +7 -2
  136. package/src/server/collaboration/relay/hub.ts +55 -24
  137. package/src/server/collaboration/routes.ts +8 -5
  138. package/src/server/comments/index.ts +9 -0
  139. package/src/server/comments/notify.ts +277 -0
  140. package/src/server/comments/routes.ts +352 -0
  141. package/src/server/comments/rows.ts +249 -0
  142. package/src/server/comments/service.ts +570 -0
  143. package/src/server/community/routes.ts +6 -6
  144. package/src/server/config/deployment.ts +19 -6
  145. package/src/server/config/index.ts +1 -1
  146. package/src/server/config/public.ts +19 -6
  147. package/src/server/config/schema.ts +14 -2
  148. package/src/server/config/toml/schema.ts +27 -4
  149. package/src/server/db/index.ts +2 -1
  150. package/src/server/db/migrate.ts +21 -1
  151. package/src/server/db/migrations/015_comments.ts +57 -0
  152. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  153. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  154. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  155. package/src/server/db/tables.ts +92 -2
  156. package/src/server/documents/access.ts +17 -0
  157. package/src/server/documents/images.ts +6 -1
  158. package/src/server/documents/routes.ts +12 -12
  159. package/src/server/documents/service.ts +19 -5
  160. package/src/server/documents/summary.ts +15 -0
  161. package/src/server/documents/versions/routes.ts +7 -8
  162. package/src/server/documents/versions/service.ts +5 -2
  163. package/src/server/email/service.ts +8 -2
  164. package/src/server/email/types.ts +1 -0
  165. package/src/server/errors/index.ts +48 -3
  166. package/src/server/index.ts +15 -1
  167. package/src/server/internal/routes.ts +8 -2
  168. package/src/server/internal/service.ts +10 -0
  169. package/src/server/invitations/budget.ts +3 -1
  170. package/src/server/invitations/index.ts +1 -0
  171. package/src/server/invitations/links.ts +6 -0
  172. package/src/server/pictures/service.ts +3 -1
  173. package/src/server/policy/workspace.ts +5 -2
  174. package/src/server/reports/routes.ts +2 -2
  175. package/src/server/reports/service.ts +3 -1
  176. package/src/server/services/routes.ts +2 -2
  177. package/src/server/sharing/capabilities/service.ts +1 -1
  178. package/src/server/sharing/document-routes.ts +3 -3
  179. package/src/server/sharing/invitations/service.ts +3 -4
  180. package/src/server/sharing/routes.ts +15 -15
  181. package/src/server/validation.ts +33 -25
  182. package/src/server/workspaces/members.ts +50 -12
  183. package/src/server/workspaces/repository.ts +23 -12
  184. package/src/server/workspaces/routes.ts +8 -8
  185. package/src/services/app.ts +30 -19
  186. package/src/services/config.ts +47 -8
  187. package/src/services/metering.ts +15 -27
  188. package/src/client/billing.ts +0 -80
@@ -1,19 +1,28 @@
1
1
  import {
2
2
  CLOUD_BILLING_CONTRACT_VERSION,
3
+ type BillingFreePlan,
3
4
  CLOUD_SERVICES_CONTRACT_VERSION,
4
5
  CLOUD_PROTOCOL_VERSION,
5
6
  parseCloudDiscovery,
6
7
  type CloudDiscovery
7
8
  } from '#cloud/contract'
9
+ import { configuredSocialProviders } from '#cloud/server/auth/social-providers'
8
10
  import { withoutTrailingSlash } from 'ufo'
9
11
 
10
12
  import type { CloudServerConfig } from './schema'
11
13
 
12
- export function configuredSocialProviders(config: CloudServerConfig): Array<'apple' | 'google'> {
13
- return [
14
- ...(config.appleClientId ? (['apple'] as const) : []),
15
- ...(config.googleClientId ? (['google'] as const) : [])
16
- ]
14
+ /**
15
+ * The free plan billing compares its plans with: what an account takes before billing stores its
16
+ * own, as the deployment's default entitlements say. Services without an allowance have no monthly
17
+ * limit, as the services token says of them too.
18
+ */
19
+ function freePlan(config: CloudServerConfig): BillingFreePlan {
20
+ const { storage, services } = config.defaultEntitlements ?? {}
21
+ return {
22
+ storageBytes: storage?.maximumBytes ?? null,
23
+ services: services?.enabled ?? false,
24
+ monthlyCredits: services?.monthlyCreditAllowance ?? null
25
+ }
17
26
  }
18
27
 
19
28
  export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscovery {
@@ -64,7 +73,11 @@ export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscov
64
73
  ? { endpoint: config.servicesEndpoint, contractVersion: CLOUD_SERVICES_CONTRACT_VERSION }
65
74
  : undefined,
66
75
  billing: config.billingEndpoint
67
- ? { endpoint: config.billingEndpoint, contractVersion: CLOUD_BILLING_CONTRACT_VERSION }
76
+ ? {
77
+ endpoint: config.billingEndpoint,
78
+ contractVersion: CLOUD_BILLING_CONTRACT_VERSION,
79
+ freePlan: freePlan(config)
80
+ }
68
81
  : undefined,
69
82
  community: config.community,
70
83
  branding: config.branding,
@@ -114,6 +114,8 @@ const rawCloudServerConfigSchema = v.object({
114
114
  appleTeamId: optionalTextSchema,
115
115
  appleKeyId: optionalTextSchema,
116
116
  applePrivateKey: optionalTextSchema,
117
+ githubClientId: optionalTextSchema,
118
+ githubClientSecret: optionalTextSchema,
117
119
  appleAppBundleIdentifier: optionalTextSchema,
118
120
  s3Endpoint: httpURLSchema,
119
121
  s3Region: v.pipe(v.string(), v.trim(), v.minLength(1)),
@@ -133,6 +135,7 @@ const rawCloudServerConfigSchema = v.object({
133
135
  smtpUser: optionalTextSchema,
134
136
  smtpPassword: optionalTextSchema,
135
137
  emailFrom: optionalTextSchema,
138
+ emailReplyTo: v.optional(v.pipe(v.string(), v.email())),
136
139
  emailTransport: v.optional(v.picklist(['none', 'smtp', 'cloudflare']), 'none'),
137
140
  emailBatchSize: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000)), 50),
138
141
  emailIntervalMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1000)), 30_000),
@@ -191,7 +194,13 @@ const rawCloudServerConfigSchema = v.object({
191
194
  * The workspace whose documents anyone may open read-only, without signing in or a link: the
192
195
  * deployment's community gallery. Without it the server has none.
193
196
  */
194
- community: v.optional(v.object({ workspaceId: v.pipe(v.string(), v.uuid()) })),
197
+ community: v.optional(
198
+ v.object({
199
+ workspaceId: v.pipe(v.string(), v.uuid()),
200
+ /** The gallery document editors open as their tour. */
201
+ tourDocumentId: v.optional(v.pipe(v.string(), v.uuid()))
202
+ })
203
+ ),
195
204
  /** How a self-hosted server names itself on its public pages. */
196
205
  branding: v.optional(
197
206
  v.object({
@@ -205,7 +214,9 @@ const rawCloudServerConfigSchema = v.object({
205
214
  v.object({
206
215
  provider: v.literal('posthog'),
207
216
  host: httpURLSchema,
208
- projectAPIKey: v.pipe(v.string(), v.trim(), v.minLength(1))
217
+ projectAPIKey: v.pipe(v.string(), v.trim(), v.minLength(1)),
218
+ /** Error reports name the account and records involved; off unless a deployment sets it. */
219
+ includeIds: v.optional(v.boolean(), false)
209
220
  })
210
221
  )
211
222
  })
@@ -266,6 +277,7 @@ function validateAuthenticationConfig(config: CloudServerConfig): void {
266
277
  'appleKeyId',
267
278
  'applePrivateKey'
268
279
  ])
280
+ requireTogether(config, 'GitHub', ['githubClientId', 'githubClientSecret'])
269
281
  }
270
282
 
271
283
  function validateEmailConfig(config: CloudServerConfig): void {
@@ -17,6 +17,7 @@ const DEFAULT_SECRET_NAMES = {
17
17
  googleClientId: 'GOOGLE_CLIENT_ID',
18
18
  googleClientSecret: 'GOOGLE_CLIENT_SECRET',
19
19
  applePrivateKey: 'APPLE_PRIVATE_KEY',
20
+ githubClientSecret: 'GITHUB_CLIENT_SECRET',
20
21
  s3AccessKeyId: 'S3_ACCESS_KEY_ID',
21
22
  s3SecretAccessKey: 'S3_SECRET_ACCESS_KEY',
22
23
  s3SessionToken: 'S3_SESSION_TOKEN',
@@ -52,15 +53,25 @@ const providerSchema = v.strictObject({
52
53
  private_key: defaultReference(DEFAULT_SECRET_NAMES.applePrivateKey),
53
54
  app_bundle_identifier: v.optional(textSchema)
54
55
  })
56
+ ),
57
+ github: v.optional(
58
+ v.strictObject({
59
+ client_id: configurableTextSchema,
60
+ client_secret: defaultReference(DEFAULT_SECRET_NAMES.githubClientSecret)
61
+ })
55
62
  )
56
63
  })
57
64
 
65
+ /** Where replies go, when someone reads the email and writes back; `from` otherwise. */
66
+ const replyToSchema = v.optional(v.pipe(v.string(), v.email()))
67
+
58
68
  const emailSchema = v.optional(
59
69
  v.variant('transport', [
60
70
  v.strictObject({ transport: v.literal('none') }),
61
71
  v.strictObject({
62
72
  transport: v.literal('smtp'),
63
73
  from: textSchema,
74
+ reply_to: replyToSchema,
64
75
  smtp: v.strictObject({
65
76
  host: textSchema,
66
77
  port: positiveIntegerSchema,
@@ -73,7 +84,11 @@ const emailSchema = v.optional(
73
84
  })
74
85
  })
75
86
  }),
76
- v.strictObject({ transport: v.literal('cloudflare'), from: textSchema })
87
+ v.strictObject({
88
+ transport: v.literal('cloudflare'),
89
+ from: textSchema,
90
+ reply_to: replyToSchema
91
+ })
77
92
  ]),
78
93
  { transport: 'none' }
79
94
  )
@@ -286,9 +301,15 @@ export const cloudDeploymentConfigSchema = v.strictObject({
286
301
  ),
287
302
  /**
288
303
  * Optional: a workspace whose documents anyone may open read-only, without signing in or a
289
- * link, as the deployment's community gallery. Everything saved there is public.
304
+ * link, as the deployment's community gallery. Everything saved there is public. `tour` names
305
+ * the gallery document the editor opens as its tour, and the docs landing shows.
290
306
  */
291
- community: v.optional(v.strictObject({ workspace: v.pipe(v.string(), v.uuid()) })),
307
+ community: v.optional(
308
+ v.strictObject({
309
+ workspace: v.pipe(v.string(), v.uuid()),
310
+ tour: v.optional(v.pipe(v.string(), v.uuid()))
311
+ })
312
+ ),
292
313
  /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */
293
314
  error_tracking: v.optional(
294
315
  v.strictObject({
@@ -296,7 +317,9 @@ export const cloudDeploymentConfigSchema = v.strictObject({
296
317
  host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),
297
318
  project_api_key: v.optional(configurableTextSchema, {
298
319
  from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey
299
- })
320
+ }),
321
+ /** Send the account and record IDs an error involved; off, reports name neither. */
322
+ include_ids: v.optional(v.boolean(), false)
300
323
  })
301
324
  )
302
325
  })
@@ -1,10 +1,11 @@
1
1
  export { createCloudDatabase, type CloudDatabaseOptions } from './database'
2
- export { migrateCloudDatabase } from './migrate'
2
+ export { migrateCloudDatabase, pendingCloudMigrations } from './migrate'
3
3
  export { isBannedNow, userIdText } from './users'
4
4
  export type {
5
5
  CloudDatabase,
6
6
  Document,
7
7
  DocumentRevision,
8
+ MFAAssuranceMethod,
8
9
  NewDocument,
9
10
  NewDocumentRevision,
10
11
  NewStorageObject,
@@ -15,6 +15,10 @@ import * as accountIds from './migrations/011_account_ids'
15
15
  import * as emailLocales from './migrations/012_email_locales'
16
16
  import * as documentBlockEmails from './migrations/013_document_block_emails'
17
17
  import * as reportReplies from './migrations/014_report_replies'
18
+ import * as comments from './migrations/015_comments'
19
+ import * as commentNotifications from './migrations/016_comment_notifications'
20
+ import * as invitationEmails from './migrations/017_invitation_emails'
21
+ import * as enrollmentSource from './migrations/018_enrollment_source'
18
22
  import type { CloudDatabase } from './tables'
19
23
 
20
24
  /**
@@ -39,7 +43,11 @@ const migrations: Record<string, CloudMigration> = {
39
43
  '011_account_ids': accountIds,
40
44
  '012_email_locales': emailLocales,
41
45
  '013_document_block_emails': documentBlockEmails,
42
- '014_report_replies': reportReplies
46
+ '014_report_replies': reportReplies,
47
+ '015_comments': comments,
48
+ '016_comment_notifications': commentNotifications,
49
+ '017_invitation_emails': invitationEmails,
50
+ '018_enrollment_source': enrollmentSource
43
51
  }
44
52
 
45
53
  /** Cloud's migrations, in order. */
@@ -97,6 +105,18 @@ export async function migrateToLatest(migrator: Migrator, failure: string): Prom
97
105
  }
98
106
  }
99
107
 
108
+ /**
109
+ * Cloud's migrations this database has not run, in order: none once a deployment of this
110
+ * version has started. A tool that only reads or writes rows checks this instead of migrating,
111
+ * so running it never changes the schema under a server of another version.
112
+ */
113
+ export async function pendingCloudMigrations(database: Kysely<CloudDatabase>): Promise<string[]> {
114
+ const migrator = new Migrator({ db: database, provider: new CloudMigrationProvider() })
115
+ return (await migrator.getMigrations())
116
+ .filter((migration) => migration.executedAt === undefined)
117
+ .map((migration) => migration.name)
118
+ }
119
+
100
120
  export async function migrateCloudDatabase(
101
121
  database: Kysely<CloudDatabase>,
102
122
  authMigration?: CloudAuthMigration
@@ -0,0 +1,57 @@
1
+ import type { Kysely } from 'kysely'
2
+
3
+ import { addIndexes, dropTables, now, required } from './schema'
4
+
5
+ /**
6
+ * Comments on a Cloud document belong to the server, not to the file: each one keeps who wrote
7
+ * it as an account, can be deleted for good, and is open to people who may only view. A thread
8
+ * is the pin and whether it is resolved; its comments are its first message and the replies.
9
+ */
10
+ export async function up(database: Kysely<unknown>): Promise<void> {
11
+ await database.schema
12
+ .createTable('comment_thread')
13
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
14
+ .addColumn('document_id', 'uuid', (column) =>
15
+ column.notNull().references('document.id').onDelete('cascade')
16
+ )
17
+ .addColumn('page_id', 'text', required)
18
+ // The page and layer names when the pin was placed, for a file written without the layer.
19
+ .addColumn('page_name', 'text')
20
+ .addColumn('node_id', 'text')
21
+ .addColumn('node_name', 'text')
22
+ .addColumn('offset_x', 'double precision')
23
+ .addColumn('offset_y', 'double precision')
24
+ .addColumn('x', 'double precision', required)
25
+ .addColumn('y', 'double precision', required)
26
+ .addColumn('created_by', 'text', required)
27
+ .addColumn('created_at', 'timestamptz', now)
28
+ .addColumn('updated_at', 'timestamptz', now)
29
+ .addColumn('resolved_at', 'timestamptz')
30
+ .addColumn('resolved_by', 'text')
31
+ .execute()
32
+ await database.schema
33
+ .createTable('comment')
34
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
35
+ .addColumn('thread_id', 'uuid', (column) =>
36
+ column.notNull().references('comment_thread.id').onDelete('cascade')
37
+ )
38
+ // The account that wrote it. A comment brought in from a file has none and keeps the name
39
+ // the file gave instead, which no one vouches for.
40
+ .addColumn('author_id', 'text')
41
+ .addColumn('imported_author_name', 'text')
42
+ // The agent that wrote it on its author's behalf, if one did.
43
+ .addColumn('agent', 'text')
44
+ .addColumn('body', 'text', required)
45
+ .addColumn('created_at', 'timestamptz', now)
46
+ .addColumn('edited_at', 'timestamptz')
47
+ .execute()
48
+ await addIndexes(database, [
49
+ ['comment_thread', ['document_id', 'created_at']],
50
+ ['comment', ['thread_id', 'created_at']],
51
+ ['comment', ['author_id']]
52
+ ])
53
+ }
54
+
55
+ export async function down(database: Kysely<unknown>): Promise<void> {
56
+ await dropTables(database, ['comment_thread', 'comment'])
57
+ }
@@ -0,0 +1,76 @@
1
+ import type { Kysely } from 'kysely'
2
+
3
+ import { DOCUMENT_BLOCK_EMAIL_KINDS } from './013_document_block_emails'
4
+ import { addChecks, addIndexes, dropTables, now, replaceChecks, required } from './schema'
5
+
6
+ /** The kinds `014_report_replies` left email with. */
7
+ const REPORT_REPLY_EMAIL_KINDS = [
8
+ ...DOCUMENT_BLOCK_EMAIL_KINDS,
9
+ 'document-report-received',
10
+ 'document-report-decided'
11
+ ]
12
+
13
+ export const COMMENT_EMAIL_SETTINGS = ['all', 'mentions', 'off']
14
+
15
+ /** Every kind of transactional email once this migration has run. */
16
+ export const COMMENT_EMAIL_KINDS = [...REPORT_REPLY_EMAIL_KINDS, 'comment-notification']
17
+
18
+ /**
19
+ * Who a comment names, who has read a thread up to when, and which comments each account hears
20
+ * about by email: everything in threads it takes part in, only what names it, or nothing. Email
21
+ * gains the kind that tells someone, which the previous release never writes.
22
+ */
23
+ export async function up(database: Kysely<unknown>): Promise<void> {
24
+ await database.schema
25
+ .createTable('comment_mention')
26
+ .addColumn('comment_id', 'uuid', (column) =>
27
+ column.notNull().references('comment.id').onDelete('cascade')
28
+ )
29
+ .addColumn('user_id', 'text', required)
30
+ .addColumn('created_at', 'timestamptz', now)
31
+ .addPrimaryKeyConstraint('comment_mention_pkey', ['comment_id', 'user_id'])
32
+ .execute()
33
+ await database.schema
34
+ .createTable('comment_read')
35
+ .addColumn('user_id', 'text', required)
36
+ .addColumn('thread_id', 'uuid', (column) =>
37
+ column.notNull().references('comment_thread.id').onDelete('cascade')
38
+ )
39
+ .addColumn('read_at', 'timestamptz', now)
40
+ .addPrimaryKeyConstraint('comment_read_pkey', ['user_id', 'thread_id'])
41
+ .execute()
42
+ // An email sent about a comment, for each day's budget: who wrote it, and to whom.
43
+ await database.schema
44
+ .createTable('comment_email')
45
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
46
+ .addColumn('sender_id', 'text', required)
47
+ .addColumn('recipient_id', 'text', required)
48
+ .addColumn('sent_at', 'timestamptz', now)
49
+ .execute()
50
+ await database.schema
51
+ .createTable('notification_setting')
52
+ .addColumn('user_id', 'text', (column) => column.primaryKey())
53
+ .addColumn('comment_emails', 'text', required)
54
+ .addColumn('updated_at', 'timestamptz', now)
55
+ .execute()
56
+ await addChecks(database, [['notification_setting', 'comment_emails', COMMENT_EMAIL_SETTINGS]])
57
+ await addIndexes(database, [
58
+ ['comment_mention', ['user_id']],
59
+ ['comment_read', ['thread_id']],
60
+ ['comment_email', ['sender_id', 'sent_at']],
61
+ ['comment_email', ['recipient_id', 'sent_at']]
62
+ ])
63
+ await replaceChecks(database, 'widen', [['transactional_email', 'kind', COMMENT_EMAIL_KINDS]])
64
+ }
65
+
66
+ export async function down(database: Kysely<unknown>): Promise<void> {
67
+ await replaceChecks(database, 'narrow', [
68
+ ['transactional_email', 'kind', REPORT_REPLY_EMAIL_KINDS]
69
+ ])
70
+ await dropTables(database, [
71
+ 'comment_mention',
72
+ 'comment_read',
73
+ 'comment_email',
74
+ 'notification_setting'
75
+ ])
76
+ }
@@ -0,0 +1,19 @@
1
+ import type { Kysely } from 'kysely'
2
+
3
+ import { COMMENT_EMAIL_KINDS } from './016_comment_notifications'
4
+ import { replaceChecks } from './schema'
5
+
6
+ /**
7
+ * Email gains the official deployment's invitation letter, which approves a waiting request with a
8
+ * note from the founder instead of the plain approval; the previous release never writes it.
9
+ */
10
+ export async function up(database: Kysely<unknown>): Promise<void> {
11
+ await replaceChecks(database, 'widen', [
12
+ ['transactional_email', 'kind', [...COMMENT_EMAIL_KINDS, 'enrollment-invited']]
13
+ ])
14
+ }
15
+
16
+ // Narrowing back checks every row, so a rollback refuses while an invitation letter is kept.
17
+ export async function down(database: Kysely<unknown>): Promise<void> {
18
+ await replaceChecks(database, 'narrow', [['transactional_email', 'kind', COMMENT_EMAIL_KINDS]])
19
+ }
@@ -0,0 +1,17 @@
1
+ import { sql, type Kysely } from 'kysely'
2
+
3
+ /**
4
+ * Where an access request came from: null when the person asked on this server, `waitlist` when an
5
+ * administrator recorded someone from openpencil.dev's waitlist, whose approval with the invitation
6
+ * letter thanks them for joining the waitlist rather than for asking. Earlier requests asked here.
7
+ */
8
+ export async function up(database: Kysely<unknown>): Promise<void> {
9
+ await database.schema
10
+ .alterTable('enrollment')
11
+ .addColumn('source', 'text', (column) => column.check(sql`source in ('waitlist')`))
12
+ .execute()
13
+ }
14
+
15
+ export async function down(database: Kysely<unknown>): Promise<void> {
16
+ await database.schema.alterTable('enrollment').dropColumn('source').execute()
17
+ }
@@ -1,5 +1,10 @@
1
1
  import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'
2
- import type { CloudSignInMethod, DocumentPermission, WorkspaceRole } from '#cloud/contract'
2
+ import type {
3
+ CloudSignInMethod,
4
+ CommentEmailSetting,
5
+ DocumentPermission,
6
+ WorkspaceRole
7
+ } from '#cloud/contract'
3
8
  import type {
4
9
  EmailLocale,
5
10
  TransactionalEmailKind,
@@ -112,6 +117,66 @@ export interface DocumentTable {
112
117
  }
113
118
 
114
119
  /** A report someone filed about a document shared with them by link; see migration 032. */
120
+ /** A comment pin on a document: where it sits, and whether it is resolved. */
121
+ export interface CommentThreadTable {
122
+ id: string
123
+ documentId: string
124
+ pageId: string
125
+ pageName: string | null
126
+ nodeId: string | null
127
+ nodeName: string | null
128
+ offsetX: number | null
129
+ offsetY: number | null
130
+ x: number
131
+ y: number
132
+ createdBy: string
133
+ createdAt: TimestampColumn
134
+ updatedAt: TimestampColumn
135
+ resolvedAt: TimestampColumn | null
136
+ resolvedBy: string | null
137
+ }
138
+
139
+ /** A thread's first message or a reply to it. */
140
+ export interface CommentTable {
141
+ id: string
142
+ threadId: string
143
+ /** Null only for a comment brought in from a file, which has `importedAuthorName` instead. */
144
+ authorId: string | null
145
+ importedAuthorName: string | null
146
+ agent: string | null
147
+ body: string
148
+ createdAt: TimestampColumn
149
+ editedAt: TimestampColumn | null
150
+ }
151
+
152
+ /** Someone a comment names, by account. */
153
+ export interface CommentMentionTable {
154
+ commentId: string
155
+ userId: string
156
+ createdAt: TimestampColumn
157
+ }
158
+
159
+ /** How far an account has read a thread. */
160
+ export interface CommentReadTable {
161
+ userId: string
162
+ threadId: string
163
+ readAt: TimestampColumn
164
+ }
165
+
166
+ /** An email sent about a comment, counted against each day's budget. */
167
+ export interface CommentEmailTable {
168
+ id: string
169
+ senderId: string
170
+ recipientId: string
171
+ sentAt: TimestampColumn
172
+ }
173
+
174
+ export interface NotificationSettingTable {
175
+ userId: string
176
+ commentEmails: CommentEmailSetting
177
+ updatedAt: TimestampColumn
178
+ }
179
+
115
180
  export interface DocumentReportTable {
116
181
  id: string
117
182
  documentId: string
@@ -253,13 +318,29 @@ export interface PasskeyTable {
253
318
  aaguid: string | null
254
319
  }
255
320
 
321
+ /**
322
+ * How a session proved its second step: a code, a recovery code, a passkey, or for a desktop app,
323
+ * a device sign-in that only a session which proved it could approve.
324
+ */
325
+ export type MFAAssuranceMethod = 'totp' | 'recovery-code' | 'passkey' | 'device'
326
+
256
327
  export interface MFAAssuranceTable {
257
328
  sessionId: string
258
329
  userId: string
259
- method: 'totp' | 'recovery-code' | 'passkey'
330
+ method: MFAAssuranceMethod
260
331
  verifiedAt: TimestampColumn
261
332
  }
262
333
 
334
+ /** Better Auth's keyed values, which also hold an administrator's sign-in blocks. */
335
+ export interface VerificationTable {
336
+ id: string
337
+ identifier: string
338
+ value: string
339
+ expiresAt: TimestampColumn
340
+ createdAt: TimestampColumn
341
+ updatedAt: TimestampColumn
342
+ }
343
+
263
344
  export interface SignInTable {
264
345
  id: string
265
346
  userId: string
@@ -391,6 +472,8 @@ export interface EnrollmentTable {
391
472
  reviewNote: string | null
392
473
  requestRevision: Generated<number>
393
474
  approvedUserId: string | null
475
+ /** `waitlist` for someone an administrator recorded from openpencil.dev's waitlist. */
476
+ source: ColumnType<'waitlist' | null, 'waitlist' | null | undefined, 'waitlist' | null>
394
477
  }
395
478
 
396
479
  export interface APIRateLimitTable {
@@ -431,6 +514,7 @@ export interface CloudDatabase {
431
514
  passkey: PasskeyTable
432
515
  mfaAssurance: MFAAssuranceTable
433
516
  signIn: SignInTable
517
+ verification: VerificationTable
434
518
  userPicture: UserPictureTable
435
519
  user: AuthUserTable
436
520
  apikey: AccessTokenTable
@@ -462,6 +546,12 @@ export interface CloudDatabase {
462
546
  upload: UploadTable
463
547
  invitationSend: InvitationSendTable
464
548
  documentReport: DocumentReportTable
549
+ commentThread: CommentThreadTable
550
+ comment: CommentTable
551
+ commentMention: CommentMentionTable
552
+ commentRead: CommentReadTable
553
+ commentEmail: CommentEmailTable
554
+ notificationSetting: NotificationSettingTable
465
555
  }
466
556
 
467
557
  export type NewTransactionalEmail = Insertable<TransactionalEmailTable>
@@ -88,6 +88,23 @@ export async function resolveDocumentAccess(
88
88
  }
89
89
  }
90
90
 
91
+ /**
92
+ * What the user may do with a live document's comments, or undefined when they may not read it:
93
+ * everyone who can read may comment, and those who can edit may delete anyone's comments.
94
+ */
95
+ export async function resolveDocumentCommentAccess(
96
+ database: AccessDatabase,
97
+ userId: string,
98
+ documentId: string
99
+ ): Promise<{ canComment: boolean; canModerate: boolean } | undefined> {
100
+ const grants = await documentAccessGrants(database, userId, documentId)
101
+ if (!grantsAllow(grants, { document: ['read'] })) return undefined
102
+ return {
103
+ canComment: grantsAllow(grants, { document: ['comment'] }),
104
+ canModerate: grantsAllow(grants, { document: ['moderate'] })
105
+ }
106
+ }
107
+
91
108
  export function canEditDocument(access: DocumentAccess): boolean {
92
109
  return access.permission === 'edit'
93
110
  }
@@ -12,13 +12,18 @@ import type { StorageQuotaService } from '#cloud/server/quota'
12
12
  import { uniq, uniqBy } from 'es-toolkit'
13
13
  import type { Kysely, Transaction } from 'kysely'
14
14
 
15
+ import { DAY_MS, MINUTE_MS } from '@open-pencil/std/timing'
16
+
15
17
  /** Images are stored as the bytes their file holds, whatever format those are. */
16
18
  export const IMAGE_CONTENT_TYPE = 'application/octet-stream'
17
19
 
18
20
  type Executor = Kysely<CloudDatabase> | Transaction<CloudDatabase>
19
21
 
20
22
  /** An image no revision has used for this long may be released; a save uploads first. */
21
- export const IMAGE_RELEASE_GRACE_MS = 24 * 60 * 60_000
23
+ export const IMAGE_RELEASE_GRACE_MS = DAY_MS
24
+
25
+ /** How long a link to download a revision or its images works. */
26
+ export const DOWNLOAD_LIFETIME_MS = 5 * MINUTE_MS
22
27
 
23
28
  /**
24
29
  * The images a workspace's documents use, each stored once under the SHA-256 the object store
@@ -1,10 +1,10 @@
1
1
  import {
2
- parseCommitImageUploads,
3
- parseCommitUpload,
4
- parseCreateDocument,
5
- parseCreateUpload,
6
- parseRequestImageLinks,
7
- parseRequestImageUploads
2
+ commitImageUploadsSchema,
3
+ commitUploadSchema,
4
+ createDocumentSchema,
5
+ createUploadSchema,
6
+ requestImageLinksSchema,
7
+ requestImageUploadsSchema
8
8
  } from '#cloud/contract'
9
9
  import type { CloudActor } from '#cloud/server/auth'
10
10
  import type { CloudDatabase } from '#cloud/server/db'
@@ -162,7 +162,7 @@ export function createDocumentRoutes(
162
162
  .post(
163
163
  '/workspaces/:workspaceId/documents',
164
164
  workspaceParams,
165
- validatedJSON(parseCreateDocument),
165
+ validatedJSON(createDocumentSchema),
166
166
  async (context) => {
167
167
  try {
168
168
  const document = await service.create(
@@ -211,7 +211,7 @@ export function createDocumentRoutes(
211
211
  .post(
212
212
  '/documents/:documentId/uploads',
213
213
  documentParams,
214
- validatedJSON(parseCreateUpload),
214
+ validatedJSON(createUploadSchema),
215
215
  (context) =>
216
216
  documentResponse(context, async () =>
217
217
  context.json(
@@ -227,7 +227,7 @@ export function createDocumentRoutes(
227
227
  .post(
228
228
  '/documents/:documentId/images/commit',
229
229
  documentParams,
230
- validatedJSON(parseCommitImageUploads),
230
+ validatedJSON(commitImageUploadsSchema),
231
231
  (context) =>
232
232
  documentResponse(context, async () => {
233
233
  await service.commitImageUploads(
@@ -241,7 +241,7 @@ export function createDocumentRoutes(
241
241
  .post(
242
242
  '/documents/:documentId/images/links',
243
243
  documentParams,
244
- validatedJSON(parseRequestImageLinks),
244
+ validatedJSON(requestImageLinksSchema),
245
245
  (context) =>
246
246
  documentResponse(context, async () =>
247
247
  context.json(
@@ -256,7 +256,7 @@ export function createDocumentRoutes(
256
256
  .post(
257
257
  '/documents/:documentId/images',
258
258
  documentParams,
259
- validatedJSON(parseRequestImageUploads),
259
+ validatedJSON(requestImageUploadsSchema),
260
260
  (context) =>
261
261
  documentResponse(context, async () =>
262
262
  context.json(
@@ -272,7 +272,7 @@ export function createDocumentRoutes(
272
272
  .post(
273
273
  '/uploads/:uploadId/commit',
274
274
  uploadParams,
275
- validatedJSON(parseCommitUpload),
275
+ validatedJSON(commitUploadSchema),
276
276
  async (context) => {
277
277
  try {
278
278
  const document = await service.commitUpload(