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

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 (339) hide show
  1. package/README.md +3 -2
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/{ai-relay.mjs → services.mjs} +9 -9
  5. package/dist/bin/services.mjs.map +1 -0
  6. package/dist/client.d.ts +525 -66
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +1257 -654
  9. package/dist/client.js.map +1 -1
  10. package/dist/contract.d.ts +2 -2
  11. package/dist/contract.js +2 -2
  12. package/dist/contract2.js +1028 -481
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1780 -31
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3556 -325
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +48 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +929 -72
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +35 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +802 -927
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +89 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +15667 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +7166 -3101
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/runtime-node.mjs +6 -5
  34. package/dist/runtime-node.mjs.map +1 -1
  35. package/dist/server.d.ts +6525 -2205
  36. package/dist/server.d.ts.map +1 -1
  37. package/dist/server.js +12500 -7613
  38. package/dist/server.js.map +1 -1
  39. package/dist/server.mjs +8625 -2878
  40. package/dist/server.mjs.map +1 -1
  41. package/dist/server2.mjs +101 -79
  42. package/dist/server2.mjs.map +1 -1
  43. package/package.json +27 -9
  44. package/src/admin/api/routes.ts +59 -0
  45. package/src/admin/audit/service.ts +27 -8
  46. package/src/admin/documents/service.ts +431 -0
  47. package/src/admin/errors.ts +9 -1
  48. package/src/admin/index.ts +6 -0
  49. package/src/admin/operations/service.ts +7 -0
  50. package/src/admin/reports/service.ts +153 -0
  51. package/src/admin/schema.ts +6 -0
  52. package/src/client/api.ts +28 -461
  53. package/src/client/auth/client.ts +22 -3
  54. package/src/client/auth/navigation.ts +6 -5
  55. package/src/client/billing.ts +80 -0
  56. package/src/client/community.ts +40 -0
  57. package/src/client/discovery.ts +35 -9
  58. package/src/client/documents.ts +160 -0
  59. package/src/client/index.ts +14 -7
  60. package/src/client/portal/account.ts +79 -2
  61. package/src/client/portal/administration.ts +56 -0
  62. package/src/client/portal/request.ts +2 -0
  63. package/src/client/response.ts +21 -0
  64. package/src/client/schema.ts +8 -0
  65. package/src/client/services.ts +118 -0
  66. package/src/client/sharing.ts +262 -0
  67. package/src/client/versions.ts +104 -0
  68. package/src/contract/account.ts +108 -2
  69. package/src/contract/admin/index.ts +67 -3
  70. package/src/contract/billing.ts +166 -0
  71. package/src/contract/collaboration.ts +11 -1
  72. package/src/contract/community.ts +60 -0
  73. package/src/contract/discovery.ts +83 -4
  74. package/src/contract/documents.ts +27 -0
  75. package/src/contract/entitlements.ts +12 -2
  76. package/src/contract/index.ts +114 -39
  77. package/src/contract/links.ts +57 -4
  78. package/src/contract/locale.ts +27 -0
  79. package/src/contract/portal.ts +12 -1
  80. package/src/contract/relay.ts +6 -0
  81. package/src/contract/reports.ts +42 -0
  82. package/src/contract/routes.ts +10 -0
  83. package/src/contract/services.ts +235 -0
  84. package/src/contract/sharing.ts +3 -9
  85. package/src/email/i18n.ts +174 -0
  86. package/src/email/index.ts +13 -2
  87. package/src/email/locales/ar.json +141 -0
  88. package/src/email/locales/de.json +141 -0
  89. package/src/email/locales/es.json +141 -0
  90. package/src/email/locales/fr.json +141 -0
  91. package/src/email/locales/it.json +141 -0
  92. package/src/email/locales/ja.json +141 -0
  93. package/src/email/locales/pl.json +141 -0
  94. package/src/email/locales/pt-br.json +141 -0
  95. package/src/email/locales/ru.json +141 -0
  96. package/src/email/locales/zh-cn.json +141 -0
  97. package/src/email/messages.ts +200 -0
  98. package/src/email/render.ts +138 -246
  99. package/src/email/samples.ts +115 -0
  100. package/src/email/schema.ts +79 -5
  101. package/src/email/templates/BrandEmail.vue +54 -0
  102. package/src/email/templates/DocumentBlocked.vue +45 -0
  103. package/src/email/templates/DocumentInvitation.vue +24 -0
  104. package/src/email/templates/DocumentReport.vue +32 -0
  105. package/src/email/templates/DocumentReportDecided.vue +36 -0
  106. package/src/email/templates/DocumentReportReceived.vue +18 -0
  107. package/src/email/templates/DocumentRestored.vue +24 -0
  108. package/src/email/templates/EmailChangeRequested.vue +24 -0
  109. package/src/email/templates/EmailRoot.vue +19 -0
  110. package/src/email/templates/EmailText.vue +9 -0
  111. package/src/email/templates/EmailVerification.vue +38 -0
  112. package/src/email/templates/EnrollmentNotification.vue +24 -0
  113. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  114. package/src/email/templates/NewSignIn.vue +37 -0
  115. package/src/email/templates/PasswordChanged.vue +22 -0
  116. package/src/email/templates/PasswordReset.vue +23 -0
  117. package/src/email/templates/StorageLimitReached.vue +28 -0
  118. package/src/email/templates/TwoStepChanged.vue +32 -0
  119. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  120. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  121. package/src/email/templates/brand.ts +9 -61
  122. package/src/email/templates/localization.ts +17 -0
  123. package/src/errors/index.ts +6 -0
  124. package/src/errors/posthog.ts +80 -0
  125. package/src/global.d.ts +7 -0
  126. package/src/runtime/cloudflare/environment.ts +22 -11
  127. package/src/runtime/cloudflare/index.ts +1 -1
  128. package/src/runtime/cloudflare/logging.ts +15 -0
  129. package/src/runtime/cloudflare/maintenance.ts +31 -0
  130. package/src/runtime/cloudflare/relay/index.ts +69 -15
  131. package/src/runtime/cloudflare/tsconfig.json +2 -1
  132. package/src/runtime/cloudflare/worker.ts +46 -13
  133. package/src/runtime/node/application.ts +5 -3
  134. package/src/runtime/node/bootstrap.ts +15 -4
  135. package/src/runtime/node/cleanup.ts +20 -3
  136. package/src/runtime/node/email/transport.ts +13 -10
  137. package/src/runtime/node/entitlements/main.ts +14 -11
  138. package/src/runtime/node/index.ts +1 -1
  139. package/src/runtime/node/main.ts +1 -1
  140. package/src/runtime/node/migrate.ts +5 -1
  141. package/src/runtime/node/relay.ts +8 -2
  142. package/src/runtime/node/request-id.ts +13 -0
  143. package/src/runtime/node/server.ts +50 -16
  144. package/src/runtime/node/{ai-relay → services}/main.ts +7 -7
  145. package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
  146. package/src/runtime/postgres/database.ts +20 -1
  147. package/src/runtime/posthog/errors.ts +15 -30
  148. package/src/runtime/s3/objects.ts +41 -1
  149. package/src/runtime/site/community.ts +101 -0
  150. package/src/runtime/site/server.ts +49 -6
  151. package/src/server/account/actions.ts +5 -0
  152. package/src/server/account/deletion.ts +304 -0
  153. package/src/server/account/routes.ts +281 -206
  154. package/src/server/account/terms.ts +42 -0
  155. package/src/server/account/tokens.ts +57 -0
  156. package/src/server/api/router.ts +32 -5
  157. package/src/server/api/types.ts +2 -0
  158. package/src/server/app/checks.ts +84 -0
  159. package/src/server/app/editors.ts +20 -0
  160. package/src/server/app/index.ts +128 -0
  161. package/src/server/app/indexing.ts +40 -0
  162. package/src/server/app/limiters.ts +53 -0
  163. package/src/server/app/routes.ts +114 -0
  164. package/src/server/app/services.ts +185 -0
  165. package/src/server/auth/access-control.ts +63 -0
  166. package/src/server/auth/access-tokens.ts +62 -0
  167. package/src/server/auth/adapter.ts +32 -1
  168. package/src/server/auth/email.ts +4 -1
  169. package/src/server/auth/endpoints.ts +5 -1
  170. package/src/server/auth/enrollment.ts +116 -0
  171. package/src/server/auth/factory.ts +116 -132
  172. package/src/server/auth/index.ts +10 -1
  173. package/src/server/auth/logger.ts +23 -0
  174. package/src/server/auth/mfa-assurance.ts +51 -0
  175. package/src/server/auth/passwords.ts +43 -0
  176. package/src/server/auth/session.ts +2 -0
  177. package/src/server/billing/index.ts +6 -0
  178. package/src/server/billing/routes.ts +27 -0
  179. package/src/server/billing/tokens.ts +37 -0
  180. package/src/server/cleanup/configured.ts +27 -7
  181. package/src/server/cleanup/documents.ts +165 -71
  182. package/src/server/cleanup/revisions.ts +16 -5
  183. package/src/server/cleanup/uploads.ts +8 -2
  184. package/src/server/cleanup/worker.ts +15 -3
  185. package/src/server/collaboration/relay/connection.ts +4 -3
  186. package/src/server/collaboration/relay/documents.ts +13 -10
  187. package/src/server/collaboration/relay/hub.ts +77 -122
  188. package/src/server/collaboration/relay/log.ts +5 -2
  189. package/src/server/collaboration/relay/room.ts +154 -0
  190. package/src/server/collaboration/service.ts +48 -33
  191. package/src/server/community/index.ts +2 -0
  192. package/src/server/community/routes.ts +93 -0
  193. package/src/server/community/service.ts +134 -0
  194. package/src/server/config/deployment.ts +41 -9
  195. package/src/server/config/index.ts +1 -1
  196. package/src/server/config/public.ts +11 -4
  197. package/src/server/config/schema.ts +91 -277
  198. package/src/server/config/toml/schema.ts +307 -0
  199. package/src/server/db/expressions.ts +15 -1
  200. package/src/server/db/index.ts +1 -0
  201. package/src/server/db/migrate.ts +46 -116
  202. package/src/server/db/migrations/001_accounts.ts +79 -0
  203. package/src/server/db/migrations/002_workspaces.ts +48 -0
  204. package/src/server/db/migrations/003_storage.ts +44 -0
  205. package/src/server/db/migrations/004_documents.ts +193 -0
  206. package/src/server/db/migrations/005_sharing.ts +95 -0
  207. package/src/server/db/migrations/006_operations.ts +110 -0
  208. package/src/server/db/migrations/007_trash.ts +33 -0
  209. package/src/server/db/migrations/008_terms.ts +18 -0
  210. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  211. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  212. package/src/server/db/migrations/011_account_ids.ts +30 -0
  213. package/src/server/db/migrations/012_email_locales.ts +34 -0
  214. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  215. package/src/server/db/migrations/014_report_replies.ts +28 -0
  216. package/src/server/db/migrations/schema.ts +96 -0
  217. package/src/server/db/tables.ts +82 -4
  218. package/src/server/db/users.ts +22 -0
  219. package/src/server/documents/access.ts +66 -55
  220. package/src/server/documents/errors.ts +7 -0
  221. package/src/server/documents/images.ts +2 -1
  222. package/src/server/documents/index.ts +1 -1
  223. package/src/server/documents/limits.ts +14 -8
  224. package/src/server/documents/purge.ts +75 -0
  225. package/src/server/documents/repository.ts +2 -0
  226. package/src/server/documents/routes.ts +26 -0
  227. package/src/server/documents/service.ts +30 -406
  228. package/src/server/documents/summary.ts +1 -0
  229. package/src/server/documents/trash.ts +203 -0
  230. package/src/server/documents/uploads.ts +450 -0
  231. package/src/server/documents/versions/checkpoint.ts +2 -1
  232. package/src/server/documents/versions/history.ts +11 -7
  233. package/src/server/documents/versions/service.ts +94 -28
  234. package/src/server/email/invitations.ts +1 -0
  235. package/src/server/email/service.ts +31 -4
  236. package/src/server/email/types.ts +12 -0
  237. package/src/server/errors/index.ts +51 -16
  238. package/src/server/index.ts +52 -16
  239. package/src/server/internal/index.ts +3 -3
  240. package/src/server/internal/routes.ts +7 -10
  241. package/src/server/internal/schema.ts +1 -1
  242. package/src/server/internal/service.ts +17 -23
  243. package/src/server/invitations/budget.ts +66 -0
  244. package/src/server/invitations/index.ts +1 -0
  245. package/src/server/invitations/types.ts +5 -1
  246. package/src/server/logging.ts +76 -0
  247. package/src/server/objects/types.ts +5 -0
  248. package/src/server/pictures/service.ts +2 -1
  249. package/src/server/policy/configured.ts +9 -3
  250. package/src/server/policy/database.ts +52 -27
  251. package/src/server/policy/index.ts +2 -1
  252. package/src/server/policy/keys.ts +5 -2
  253. package/src/server/policy/policy.ts +40 -12
  254. package/src/server/policy/schema.ts +2 -2
  255. package/src/server/policy/service.ts +78 -56
  256. package/src/server/policy/static.ts +5 -5
  257. package/src/server/policy/storage.ts +33 -0
  258. package/src/server/policy/workspace.ts +41 -0
  259. package/src/server/quota/index.ts +6 -0
  260. package/src/server/quota/notices.ts +121 -0
  261. package/src/server/quota/reconcile.ts +2 -0
  262. package/src/server/quota/storage.ts +74 -31
  263. package/src/server/rate-limit/cleanup.ts +17 -5
  264. package/src/server/rate-limit/middleware.ts +6 -2
  265. package/src/server/reports/index.ts +9 -0
  266. package/src/server/reports/replies.ts +55 -0
  267. package/src/server/reports/routes.ts +39 -0
  268. package/src/server/reports/service.ts +145 -0
  269. package/src/server/services/errors.ts +7 -0
  270. package/src/server/services/index.ts +8 -0
  271. package/src/server/{ai → services}/keys.ts +11 -11
  272. package/src/server/services/routes.ts +47 -0
  273. package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
  274. package/src/server/sharing/capabilities/service.ts +68 -23
  275. package/src/server/sharing/grants/service.ts +11 -18
  276. package/src/server/sharing/http.ts +4 -0
  277. package/src/server/sharing/invitations/service.ts +35 -15
  278. package/src/server/sharing/policy.ts +9 -14
  279. package/src/server/sharing/routes.ts +0 -16
  280. package/src/server/sharing/service.ts +1 -17
  281. package/src/server/validation.ts +4 -0
  282. package/src/server/workspaces/index.ts +1 -0
  283. package/src/server/workspaces/members.ts +91 -52
  284. package/src/server/workspaces/repository.ts +2 -1
  285. package/src/server/workspaces/routes.ts +4 -0
  286. package/src/{ai-relay → services}/app.ts +46 -44
  287. package/src/{ai-relay → services}/config.ts +26 -19
  288. package/src/services/db/index.ts +10 -0
  289. package/src/services/db/migrate.ts +37 -0
  290. package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
  291. package/src/services/db/schema.ts +22 -0
  292. package/src/services/index.ts +18 -0
  293. package/src/{ai-relay → services}/metering.ts +2 -2
  294. package/src/{ai-relay → services}/usage.ts +35 -19
  295. package/dist/bin/ai-relay.mjs.map +0 -1
  296. package/src/ai-relay/db/index.ts +0 -10
  297. package/src/ai-relay/db/migrate.ts +0 -32
  298. package/src/ai-relay/db/schema.ts +0 -20
  299. package/src/ai-relay/index.ts +0 -18
  300. package/src/client/ai.ts +0 -96
  301. package/src/contract/ai.ts +0 -150
  302. package/src/email/templates/document-invitation.ts +0 -35
  303. package/src/email/templates/enrollment.ts +0 -27
  304. package/src/email/templates/layout.ts +0 -18
  305. package/src/server/ai/errors.ts +0 -7
  306. package/src/server/ai/index.ts +0 -4
  307. package/src/server/ai/routes.ts +0 -43
  308. package/src/server/app.ts +0 -379
  309. package/src/server/auth/workspace-access.ts +0 -23
  310. package/src/server/db/migrations/001_foundation.ts +0 -164
  311. package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
  312. package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
  313. package/src/server/db/migrations/004_document_sharing.ts +0 -82
  314. package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
  315. package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
  316. package/src/server/db/migrations/007_collaboration_state.ts +0 -25
  317. package/src/server/db/migrations/008_storage_reservations.ts +0 -37
  318. package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
  319. package/src/server/db/migrations/010_upload_finalization.ts +0 -22
  320. package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
  321. package/src/server/db/migrations/012_transactional_email.ts +0 -48
  322. package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
  323. package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
  324. package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
  325. package/src/server/db/migrations/016_auth_schema.ts +0 -16
  326. package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
  327. package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
  328. package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
  329. package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
  330. package/src/server/db/migrations/021_document_versions.ts +0 -66
  331. package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
  332. package/src/server/db/migrations/023_document_images.ts +0 -61
  333. package/src/server/db/migrations/024_account_activity.ts +0 -66
  334. package/src/server/db/migrations/025_table_names.ts +0 -58
  335. package/src/server/db/migrations/026_user_picture.ts +0 -30
  336. package/src/server/db/migrations/027_document_kind.ts +0 -19
  337. package/src/server/db/migrations/028_collaboration_updates.ts +0 -84
  338. package/src/server/db/migrations/helpers.ts +0 -78
  339. /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
@@ -0,0 +1,307 @@
1
+ import { cloudEditorVersionSchema } from '#cloud/contract'
2
+ import { deletedPrefixSchema } from '#cloud/server/config/schema'
3
+ import { staticEntitlementsTOMLSchema } from '#cloud/server/policy/schema'
4
+ import * as v from 'valibot'
5
+
6
+ /*
7
+ * The deployment file, `openpencil-cloud.toml`: what an operator writes, with secrets named by the
8
+ * environment variables that hold them. `../deployment.ts` reads it into the server's configuration.
9
+ */
10
+
11
+ /** PostHog's EU Cloud ingestion host, where OpenPencil's own project is. */
12
+ const POSTHOG_DEFAULT_HOST = 'https://eu.i.posthog.com'
13
+
14
+ const DEFAULT_SECRET_NAMES = {
15
+ databaseURL: 'DATABASE_URL',
16
+ authSecret: 'BETTER_AUTH_SECRET',
17
+ googleClientId: 'GOOGLE_CLIENT_ID',
18
+ googleClientSecret: 'GOOGLE_CLIENT_SECRET',
19
+ applePrivateKey: 'APPLE_PRIVATE_KEY',
20
+ s3AccessKeyId: 'S3_ACCESS_KEY_ID',
21
+ s3SecretAccessKey: 'S3_SECRET_ACCESS_KEY',
22
+ s3SessionToken: 'S3_SESSION_TOKEN',
23
+ smtpUser: 'OPENPENCIL_CLOUD_SMTP_USER',
24
+ smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',
25
+ turnstileSecretKey: 'TURNSTILE_SECRET_KEY',
26
+ servicesSigningKey: 'OPENPENCIL_CLOUD_SERVICES_SIGNING_KEY',
27
+ internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN',
28
+ posthogProjectAPIKey: 'POSTHOG_PROJECT_API_KEY'
29
+ } as const
30
+
31
+ const urlSchema = v.pipe(v.string(), v.url())
32
+ const textSchema = v.pipe(v.string(), v.trim(), v.minLength(1))
33
+ const positiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1))
34
+ const secretReferenceSchema = v.strictObject({ from_env: textSchema })
35
+ const configurableTextSchema = v.union([textSchema, secretReferenceSchema])
36
+ const defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })
37
+
38
+ const providerSchema = v.strictObject({
39
+ google: v.optional(
40
+ v.strictObject({
41
+ client_id: v.optional(configurableTextSchema, {
42
+ from_env: DEFAULT_SECRET_NAMES.googleClientId
43
+ }),
44
+ client_secret: defaultReference(DEFAULT_SECRET_NAMES.googleClientSecret)
45
+ })
46
+ ),
47
+ apple: v.optional(
48
+ v.strictObject({
49
+ client_id: textSchema,
50
+ team_id: textSchema,
51
+ key_id: textSchema,
52
+ private_key: defaultReference(DEFAULT_SECRET_NAMES.applePrivateKey),
53
+ app_bundle_identifier: v.optional(textSchema)
54
+ })
55
+ )
56
+ })
57
+
58
+ const emailSchema = v.optional(
59
+ v.variant('transport', [
60
+ v.strictObject({ transport: v.literal('none') }),
61
+ v.strictObject({
62
+ transport: v.literal('smtp'),
63
+ from: textSchema,
64
+ smtp: v.strictObject({
65
+ host: textSchema,
66
+ port: positiveIntegerSchema,
67
+ secure: v.optional(v.boolean()),
68
+ user: v.optional(secretReferenceSchema, {
69
+ from_env: DEFAULT_SECRET_NAMES.smtpUser
70
+ }),
71
+ password: v.optional(secretReferenceSchema, {
72
+ from_env: DEFAULT_SECRET_NAMES.smtpPassword
73
+ })
74
+ })
75
+ }),
76
+ v.strictObject({ transport: v.literal('cloudflare'), from: textSchema })
77
+ ]),
78
+ { transport: 'none' }
79
+ )
80
+
81
+ /**
82
+ * Every table is strict: a key the schema doesn't know, such as one renamed since, stops startup
83
+ * instead of leaving its setting at a default the operator never chose.
84
+ */
85
+ export const cloudDeploymentConfigSchema = v.strictObject({
86
+ schema_version: v.literal(2),
87
+ deployment: v.strictObject({
88
+ mode: v.picklist(['official', 'self-hosted']),
89
+ public_url: urlSchema,
90
+ indexing: v.optional(v.picklist(['allow', 'deny']), 'deny'),
91
+ trusted_origins: v.optional(v.array(urlSchema), []),
92
+ // The server's editor works with files on this device without signing in to the server.
93
+ local_editor: v.optional(v.boolean(), true),
94
+ listing: v.optional(v.strictObject({ minimum_editor_version: cloudEditorVersionSchema })),
95
+ // How a self-hosted server names itself on its public pages.
96
+ branding: v.optional(
97
+ v.strictObject({
98
+ name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
99
+ logo_url: v.optional(urlSchema),
100
+ help_url: v.optional(urlSchema)
101
+ })
102
+ ),
103
+ // Older editors ask to be updated, and the server refuses their requests.
104
+ minimum_editor_version: v.optional(cloudEditorVersionSchema)
105
+ }),
106
+ database: v.optional(
107
+ v.strictObject({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }),
108
+ {
109
+ url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }
110
+ }
111
+ ),
112
+ authentication: v.strictObject({
113
+ secret: defaultReference(DEFAULT_SECRET_NAMES.authSecret),
114
+ enrollment: v.optional(
115
+ v.strictObject({
116
+ mode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
117
+ notification_emails: v.optional(v.array(v.pipe(v.string(), v.email())), [])
118
+ }),
119
+ { mode: 'open', notification_emails: [] }
120
+ ),
121
+ email_password: v.optional(
122
+ v.strictObject({
123
+ enabled: v.optional(v.boolean(), false),
124
+ sign_up: v.optional(v.boolean(), true),
125
+ minimum_password_length: v.optional(
126
+ v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),
127
+ 8
128
+ ),
129
+ maximum_password_length: v.optional(
130
+ v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),
131
+ 128
132
+ ),
133
+ verification_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
134
+ password_reset_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
135
+ compromised_password_check: v.optional(v.boolean(), false)
136
+ }),
137
+ {
138
+ enabled: false,
139
+ sign_up: true,
140
+ minimum_password_length: 8,
141
+ maximum_password_length: 128,
142
+ verification_link_lifetime_minutes: 60,
143
+ password_reset_link_lifetime_minutes: 60,
144
+ compromised_password_check: false
145
+ }
146
+ ),
147
+ mfa: v.optional(
148
+ v.strictObject({
149
+ required_for_admins: v.optional(v.boolean(), false),
150
+ totp: v.optional(v.boolean(), false),
151
+ recovery_codes: v.optional(v.boolean(), false),
152
+ trusted_device_lifetime_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14)
153
+ }),
154
+ {
155
+ required_for_admins: false,
156
+ totp: false,
157
+ recovery_codes: false,
158
+ trusted_device_lifetime_days: 14
159
+ }
160
+ ),
161
+ // Passkeys belong to public_url's host and origin.
162
+ passkeys: v.optional(
163
+ v.strictObject({
164
+ enabled: v.optional(v.boolean(), false),
165
+ rp_name: v.optional(textSchema, 'OpenPencil Cloud')
166
+ }),
167
+ { enabled: false, rp_name: 'OpenPencil Cloud' }
168
+ ),
169
+ captcha: v.optional(
170
+ v.strictObject({
171
+ provider: v.literal('cloudflare-turnstile'),
172
+ site_key: textSchema,
173
+ secret_key: defaultReference(DEFAULT_SECRET_NAMES.turnstileSecretKey),
174
+ allowed_hostnames: v.optional(v.array(textSchema), [])
175
+ })
176
+ ),
177
+ trusted_proxies: v.optional(
178
+ v.strictObject({
179
+ headers: v.optional(v.array(textSchema), []),
180
+ addresses: v.optional(v.array(textSchema), [])
181
+ }),
182
+ { headers: [], addresses: [] }
183
+ ),
184
+ providers: v.optional(providerSchema, {})
185
+ }),
186
+ object_storage: v.strictObject({
187
+ endpoint: urlSchema,
188
+ region: textSchema,
189
+ bucket: textSchema,
190
+ credentials: v.optional(
191
+ v.strictObject({
192
+ access_key_id: defaultReference(DEFAULT_SECRET_NAMES.s3AccessKeyId),
193
+ secret_access_key: defaultReference(DEFAULT_SECRET_NAMES.s3SecretAccessKey),
194
+ session_token: v.optional(secretReferenceSchema, {
195
+ from_env: DEFAULT_SECRET_NAMES.s3SessionToken
196
+ })
197
+ }),
198
+ {
199
+ access_key_id: { from_env: DEFAULT_SECRET_NAMES.s3AccessKeyId },
200
+ secret_access_key: { from_env: DEFAULT_SECRET_NAMES.s3SecretAccessKey }
201
+ }
202
+ ),
203
+ force_path_style: v.optional(v.boolean(), true),
204
+ checksum_verification: v.optional(v.picklist(['native', 'metadata']), 'native'),
205
+ server_side_encryption: v.optional(v.picklist(['AES256', 'aws:kms'])),
206
+ kms_key_id: v.optional(textSchema),
207
+ /**
208
+ * Keeps each file cleanup deletes under this prefix, such as `deleted/`, so a database restored
209
+ * to an earlier time still finds it; a lifecycle rule on the prefix expires them.
210
+ */
211
+ deleted_prefix: v.optional(deletedPrefixSchema),
212
+ maximum_upload_bytes: v.optional(positiveIntegerSchema)
213
+ }),
214
+ collaboration: v.optional(
215
+ v.strictObject({
216
+ relay_url: v.optional(urlSchema),
217
+ maximum_message_bytes: v.optional(positiveIntegerSchema),
218
+ maximum_connections_per_room: v.optional(positiveIntegerSchema)
219
+ }),
220
+ {}
221
+ ),
222
+ documents: v.optional(
223
+ v.strictObject({
224
+ retention_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 30),
225
+ purge_grace_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 7)
226
+ }),
227
+ { retention_days: 30, purge_grace_days: 7 }
228
+ ),
229
+ email: emailSchema,
230
+ workers: v.optional(
231
+ v.strictObject({
232
+ email: v.optional(
233
+ v.strictObject({
234
+ batch_size: v.optional(positiveIntegerSchema, 50),
235
+ interval_ms: v.optional(positiveIntegerSchema, 30_000),
236
+ lease_ms: v.optional(positiveIntegerSchema, 300_000),
237
+ maximum_attempts: v.optional(positiveIntegerSchema, 5)
238
+ }),
239
+ { batch_size: 50, interval_ms: 30_000, lease_ms: 300_000, maximum_attempts: 5 }
240
+ ),
241
+ cleanup: v.optional(
242
+ v.strictObject({
243
+ enabled: v.optional(v.boolean(), true),
244
+ batch_size: v.optional(positiveIntegerSchema, 100),
245
+ interval_ms: v.optional(positiveIntegerSchema, 60_000),
246
+ lease_ms: v.optional(positiveIntegerSchema, 300_000)
247
+ }),
248
+ { enabled: true, batch_size: 100, interval_ms: 60_000, lease_ms: 300_000 }
249
+ )
250
+ })
251
+ ),
252
+ entitlements: v.optional(
253
+ v.variant('source', [
254
+ v.strictObject({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),
255
+ // The values every account takes until billing or an operator stores its own: the free plan.
256
+ v.strictObject({ source: v.literal('database'), ...staticEntitlementsTOMLSchema.entries })
257
+ ])
258
+ ),
259
+ services: v.optional(
260
+ v.strictObject({
261
+ endpoint: urlSchema,
262
+ signing_key: defaultReference(DEFAULT_SECRET_NAMES.servicesSigningKey),
263
+ token_lifetime_minutes: v.optional(
264
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(60)),
265
+ 10
266
+ )
267
+ })
268
+ ),
269
+ billing: v.optional(v.strictObject({ endpoint: urlSchema })),
270
+ internal_api: v.optional(
271
+ v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
272
+ ),
273
+ /**
274
+ * Optional: the operator's terms and privacy policy, linked at sign-up and in the portal, and
275
+ * with `require_acceptance`, accepted once per `terms_version` before an account uses the server.
276
+ */
277
+ legal: v.optional(
278
+ v.strictObject({
279
+ terms_url: v.optional(urlSchema),
280
+ privacy_url: v.optional(urlSchema),
281
+ terms_version: v.optional(textSchema),
282
+ require_acceptance: v.optional(v.boolean(), false),
283
+ abuse_email: v.optional(v.pipe(v.string(), v.email())),
284
+ minimum_age: v.optional(v.pipe(v.number(), v.integer(), v.minValue(13), v.maxValue(21)))
285
+ })
286
+ ),
287
+ /**
288
+ * 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.
290
+ */
291
+ community: v.optional(v.strictObject({ workspace: v.pipe(v.string(), v.uuid()) })),
292
+ /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */
293
+ error_tracking: v.optional(
294
+ v.strictObject({
295
+ provider: v.literal('posthog'),
296
+ host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),
297
+ project_api_key: v.optional(configurableTextSchema, {
298
+ from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey
299
+ })
300
+ })
301
+ )
302
+ })
303
+
304
+ export type CloudDeploymentConfig = v.InferOutput<typeof cloudDeploymentConfigSchema>
305
+ /** Deployment configuration as an operator writes it, before defaults are applied. */
306
+ export type CloudDeploymentInput = v.InferInput<typeof cloudDeploymentConfigSchema>
307
+ export type CloudSecretReference = v.InferOutput<typeof secretReferenceSchema>
@@ -1,4 +1,6 @@
1
- import { sql, type Expression } from 'kysely'
1
+ import { sql, type Expression, type Transaction } from 'kysely'
2
+
3
+ import type { CloudDatabase } from './tables'
2
4
 
3
5
  export const CURRENT_TIMESTAMP = sql<Date>`current_timestamp`
4
6
  export const EMPTY_JSON_OBJECT = sql`'{}'::jsonb`
@@ -11,3 +13,15 @@ export function checkColumnIn(column: string, values: readonly string[]): Expres
11
13
  }
12
14
  return sql<boolean>`${sql.ref(column)} in (${sql.join(values.map((value) => sql.lit(value)))})`
13
15
  }
16
+
17
+ /**
18
+ * Holds a lock named `key` until the transaction ends, for a check and a write that must not
19
+ * interleave with another transaction's, such as reserving storage from an account's allowance,
20
+ * which spans rows no single one of which could be locked for it.
21
+ */
22
+ export async function lockForTransaction(
23
+ transaction: Transaction<CloudDatabase>,
24
+ key: string
25
+ ): Promise<void> {
26
+ await sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`.execute(transaction)
27
+ }
@@ -1,5 +1,6 @@
1
1
  export { createCloudDatabase, type CloudDatabaseOptions } from './database'
2
2
  export { migrateCloudDatabase } from './migrate'
3
+ export { isBannedNow, userIdText } from './users'
3
4
  export type {
4
5
  CloudDatabase,
5
6
  Document,
@@ -1,69 +1,50 @@
1
1
  import type { Kysely } from 'kysely'
2
2
  import { Migrator, type Migration, type MigrationProvider } from 'kysely/migration'
3
3
 
4
- import * as foundation from './migrations/001_foundation'
5
- import * as cleanupClaims from './migrations/002_upload_cleanup_claims'
6
- import * as documentCleanupClaims from './migrations/003_document_cleanup_claims'
7
- import * as documentSharing from './migrations/004_document_sharing'
8
- import * as documentCollaborationEpoch from './migrations/005_document_collaboration_epoch'
9
- import * as invitationContinuation from './migrations/006_invitation_continuation'
10
- import * as collaborationState from './migrations/007_collaboration_state'
11
- import * as storageReservations from './migrations/008_storage_reservations'
12
- import * as workspaceEntitlements from './migrations/009_workspace_entitlements'
13
- import * as uploadFinalization from './migrations/010_upload_finalization'
14
- import * as uploadFinalizationLease from './migrations/011_upload_finalization_lease'
15
- import * as transactionalEmail from './migrations/012_transactional_email'
16
- import * as adminEnrollment from './migrations/013_admin_enrollment'
17
- import * as enrollmentEmailKinds from './migrations/014_enrollment_email_kinds'
18
- import * as cloudRateLimit from './migrations/015_cloud_rate_limit'
19
- import * as authSchema from './migrations/016_auth_schema'
20
- import * as authenticationEmailKinds from './migrations/017_authentication_email_kinds'
21
- import * as authenticationMFA from './migrations/018_authentication_mfa'
22
- import * as betterAuthAccountIssuer from './migrations/019_better_auth_account_issuer'
23
- import * as workspaceInvitations from './migrations/020_workspace_invitations'
24
- import * as documentVersions from './migrations/021_document_versions'
25
- import * as entitlementExternalVersion from './migrations/022_entitlement_external_version'
26
- import * as documentImages from './migrations/023_document_images'
27
- import * as accountActivity from './migrations/024_account_activity'
28
- import * as tableNames from './migrations/025_table_names'
29
- import * as userPicture from './migrations/026_user_picture'
30
- import * as documentKind from './migrations/027_document_kind'
31
- import * as collaborationUpdates from './migrations/028_collaboration_updates'
4
+ import * as accounts from './migrations/001_accounts'
5
+ import * as workspaces from './migrations/002_workspaces'
6
+ import * as storage from './migrations/003_storage'
7
+ import * as documents from './migrations/004_documents'
8
+ import * as sharing from './migrations/005_sharing'
9
+ import * as operations from './migrations/006_operations'
10
+ import * as trash from './migrations/007_trash'
11
+ import * as terms from './migrations/008_terms'
12
+ import * as accessTokens from './migrations/009_access_tokens'
13
+ import * as storageLimitNotices from './migrations/010_storage_limit_notices'
14
+ import * as accountIds from './migrations/011_account_ids'
15
+ import * as emailLocales from './migrations/012_email_locales'
16
+ import * as documentBlockEmails from './migrations/013_document_block_emails'
17
+ import * as reportReplies from './migrations/014_report_replies'
32
18
  import type { CloudDatabase } from './tables'
33
19
 
34
- const migrations: Record<string, Migration> = {
35
- '001_foundation': foundation,
36
- '002_upload_cleanup_claims': cleanupClaims,
37
- '003_document_cleanup_claims': documentCleanupClaims,
38
- '004_document_sharing': documentSharing,
39
- '005_document_collaboration_epoch': documentCollaborationEpoch,
40
- '006_invitation_continuation': invitationContinuation,
41
- '007_collaboration_state': collaborationState,
42
- '008_storage_reservations': storageReservations,
43
- '009_workspace_entitlements': workspaceEntitlements,
44
- '010_upload_finalization': uploadFinalization,
45
- '011_upload_finalization_lease': uploadFinalizationLease,
46
- '012_transactional_email': transactionalEmail,
47
- '013_admin_enrollment': adminEnrollment,
48
- '014_enrollment_email_kinds': enrollmentEmailKinds,
49
- '015_cloud_rate_limit': cloudRateLimit,
50
- '016_auth_schema': authSchema,
51
- '017_authentication_email_kinds': authenticationEmailKinds,
52
- '018_authentication_mfa': authenticationMFA,
53
- '019_better_auth_account_issuer': betterAuthAccountIssuer,
54
- '020_workspace_invitations': workspaceInvitations,
55
- '021_document_versions': documentVersions,
56
- '022_entitlement_external_version': entitlementExternalVersion,
57
- '023_document_images': documentImages,
58
- '024_account_activity': accountActivity,
59
- '025_table_names': tableNames,
60
- '026_user_picture': userPicture,
61
- '027_document_kind': documentKind,
62
- '028_collaboration_updates': collaborationUpdates
20
+ /**
21
+ * A migration runs before the code it ships with, while the previous release still serves, so it
22
+ * only adds (expand): no table or column dropped, renamed, retyped, or newly required. One that
23
+ * must (contract) names each table or `table.column` it changes in `contracts`, and ships a
24
+ * release after the last code that used them (`tests/integration/server/db/expand.test.ts`).
25
+ */
26
+ export type CloudMigration = Migration & { contracts?: readonly string[] }
27
+
28
+ const migrations: Record<string, CloudMigration> = {
29
+ '001_accounts': accounts,
30
+ '002_workspaces': workspaces,
31
+ '003_storage': storage,
32
+ '004_documents': documents,
33
+ '005_sharing': sharing,
34
+ '006_operations': operations,
35
+ '007_trash': trash,
36
+ '008_terms': terms,
37
+ '009_access_tokens': accessTokens,
38
+ '010_storage_limit_notices': storageLimitNotices,
39
+ '011_account_ids': accountIds,
40
+ '012_email_locales': emailLocales,
41
+ '013_document_block_emails': documentBlockEmails,
42
+ '014_report_replies': reportReplies
63
43
  }
64
44
 
65
- class CloudMigrationProvider implements MigrationProvider {
66
- async getMigrations(): Promise<Record<string, Migration>> {
45
+ /** Cloud's migrations, in order. */
46
+ export class CloudMigrationProvider implements MigrationProvider {
47
+ async getMigrations(): Promise<Record<string, CloudMigration>> {
67
48
  return migrations
68
49
  }
69
50
  }
@@ -73,46 +54,11 @@ export type CloudAuthMigration = {
73
54
  schemaVersion: string
74
55
  }
75
56
 
76
- const REQUIRED_AUTH_SCHEMA: Record<string, string[]> = {
77
- user: [
78
- 'id',
79
- 'name',
80
- 'email',
81
- 'email_verified',
82
- 'created_at',
83
- 'updated_at',
84
- 'role',
85
- 'banned',
86
- 'two_factor_enabled'
87
- ],
88
- session: ['id', 'expires_at', 'token', 'user_id', 'impersonated_by'],
89
- account: ['id', 'account_id', 'provider_id', 'user_id'],
90
- verification: ['id', 'identifier', 'value', 'expires_at'],
91
- device_code: ['id', 'device_code', 'user_code', 'status', 'client_id'],
92
- rate_limit: ['id', 'key', 'count', 'last_request'],
93
- two_factor: [
94
- 'id',
95
- 'secret',
96
- 'backup_codes',
97
- 'user_id',
98
- 'verified',
99
- 'failed_verification_count',
100
- 'locked_until'
101
- ],
102
- passkey: ['id', 'public_key', 'user_id', 'credential_id', 'counter', 'device_type', 'backed_up']
103
- }
104
-
105
- async function existingAuthSchema(
106
- database: Kysely<CloudDatabase>
107
- ): Promise<Map<string, Set<string>>> {
108
- const tables = await database.introspection.getTables()
109
- return new Map(
110
- tables
111
- .filter((table) => Object.hasOwn(REQUIRED_AUTH_SCHEMA, table.name))
112
- .map((table) => [table.name, new Set(table.columns.map((column) => column.name))])
113
- )
114
- }
115
-
57
+ /**
58
+ * Better Auth's tables come from its own migration API, once, after Cloud's: the version they
59
+ * were built for is recorded, and a different one stops startup until someone migrates it
60
+ * deliberately, since Better Auth cannot say what an upgrade between its versions changes.
61
+ */
116
62
  async function migrateAuthSchema(
117
63
  database: Kysely<CloudDatabase>,
118
64
  migration: CloudAuthMigration
@@ -130,23 +76,7 @@ async function migrateAuthSchema(
130
76
  }
131
77
  return
132
78
  }
133
-
134
- const existing = await existingAuthSchema(database)
135
- if (existing.size === 0) {
136
- await migration.run()
137
- } else {
138
- const missing = Object.entries(REQUIRED_AUTH_SCHEMA).flatMap(([table, requiredColumns]) => {
139
- const columns = existing.get(table)
140
- if (!columns) return [table]
141
- return requiredColumns
142
- .filter((column) => !columns.has(column))
143
- .map((column) => `${table}.${column}`)
144
- })
145
- if (missing.length > 0) {
146
- throw new Error(`Existing Better Auth schema is incomplete: ${missing.join(', ')}`)
147
- }
148
- }
149
-
79
+ await migration.run()
150
80
  await database
151
81
  .insertInto('authSchemaVersion')
152
82
  .values({ id: 'better-auth', version: migration.schemaVersion, updatedAt: new Date() })
@@ -0,0 +1,79 @@
1
+ import type { Kysely } from 'kysely'
2
+
3
+ import { addChecks, addIndexes, dropTables, now, required } from './schema'
4
+
5
+ /** What Cloud keeps about an account beside Better Auth's tables: its plan, sign-ins, and picture. */
6
+ const TABLES = [
7
+ 'auth_schema_version',
8
+ 'account_entitlement',
9
+ 'mfa_assurance',
10
+ 'sign_in',
11
+ 'user_picture',
12
+ 'api_rate_limit'
13
+ ]
14
+
15
+ export async function up(database: Kysely<unknown>): Promise<void> {
16
+ // The Better Auth schema version this database was built for.
17
+ await database.schema
18
+ .createTable('auth_schema_version')
19
+ .addColumn('id', 'text', (column) => column.primaryKey())
20
+ .addColumn('version', 'text', required)
21
+ .addColumn('updated_at', 'timestamptz', now)
22
+ .execute()
23
+ // An account's plan, as billing or an operator set it; its workspaces share it.
24
+ await database.schema
25
+ .createTable('account_entitlement')
26
+ .addColumn('user_id', 'text', (column) => column.primaryKey())
27
+ .addColumn('values', 'jsonb', required)
28
+ .addColumn('source', 'text', required)
29
+ .addColumn('revision', 'integer', (column) => column.notNull().defaultTo(1))
30
+ .addColumn('external_version', 'bigint')
31
+ .addColumn('updated_at', 'timestamptz', now)
32
+ .execute()
33
+ await database.schema
34
+ .createTable('mfa_assurance')
35
+ .addColumn('session_id', 'uuid', (column) => column.primaryKey())
36
+ .addColumn('user_id', 'uuid', required)
37
+ .addColumn('method', 'text', required)
38
+ .addColumn('verified_at', 'timestamptz', required)
39
+ .execute()
40
+ await database.schema
41
+ .createTable('sign_in')
42
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
43
+ .addColumn('user_id', 'uuid', required)
44
+ .addColumn('session_id', 'uuid')
45
+ .addColumn('method', 'text', required)
46
+ .addColumn('ip_address', 'text')
47
+ .addColumn('user_agent', 'text')
48
+ .addColumn('created_at', 'timestamptz', now)
49
+ .execute()
50
+ await database.schema
51
+ .createTable('user_picture')
52
+ .addColumn('user_id', 'uuid', (column) => column.primaryKey())
53
+ .addColumn('bytes', 'bytea', required)
54
+ .addColumn('format', 'text', required)
55
+ .addColumn('checksum', 'text', required)
56
+ .addColumn('source', 'text', required)
57
+ .addColumn('created_at', 'timestamptz', now)
58
+ .execute()
59
+ // OpenPencil's own rate limits; Better Auth keeps its own in `rate_limit`.
60
+ await database.schema
61
+ .createTable('api_rate_limit')
62
+ .addColumn('key_hash', 'text', (column) => column.primaryKey())
63
+ .addColumn('window_started_at', 'timestamptz', required)
64
+ .addColumn('request_count', 'integer', (column) => column.notNull().defaultTo(1))
65
+ .addColumn('updated_at', 'timestamptz', now)
66
+ .execute()
67
+ await addChecks(database, [
68
+ ['user_picture', 'format', ['png', 'jpeg']],
69
+ ['user_picture', 'source', ['upload', 'provider']]
70
+ ])
71
+ await addIndexes(database, [
72
+ ['sign_in', ['user_id', 'created_at']],
73
+ ['sign_in', ['session_id']]
74
+ ])
75
+ }
76
+
77
+ export async function down(database: Kysely<unknown>): Promise<void> {
78
+ await dropTables(database, TABLES)
79
+ }
@@ -0,0 +1,48 @@
1
+ import type { Kysely } from 'kysely'
2
+
3
+ import { addChecks, addIndexes, dropTables, now, required, ROLES, withInvitation } from './schema'
4
+
5
+ /** Workspaces, their members, and the people invited to join. */
6
+ const TABLES = ['workspace', 'workspace_member', 'workspace_invitation']
7
+
8
+ export async function up(database: Kysely<unknown>): Promise<void> {
9
+ // A workspace takes its limits from its owner's plan.
10
+ await database.schema
11
+ .createTable('workspace')
12
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
13
+ .addColumn('name', 'text', required)
14
+ .addColumn('slug', 'text', (column) => column.notNull().unique())
15
+ .addColumn('created_by', 'text', required)
16
+ .addColumn('owner_id', 'text', required)
17
+ .addColumn('created_at', 'timestamptz', now)
18
+ .addColumn('updated_at', 'timestamptz', now)
19
+ .execute()
20
+ await database.schema
21
+ .createTable('workspace_member')
22
+ .addColumn('workspace_id', 'uuid', (column) =>
23
+ column.notNull().references('workspace.id').onDelete('cascade')
24
+ )
25
+ .addColumn('user_id', 'text', required)
26
+ .addColumn('role', 'text', required)
27
+ .addColumn('created_at', 'timestamptz', now)
28
+ .addPrimaryKeyConstraint('workspace_member_pkey', ['workspace_id', 'user_id'])
29
+ .execute()
30
+ await withInvitation(database.schema.createTable('workspace_invitation'), 'role')
31
+ .addColumn('workspace_id', 'uuid', (column) =>
32
+ column.notNull().references('workspace.id').onDelete('cascade')
33
+ )
34
+ .execute()
35
+ await addChecks(database, [
36
+ ['workspace_member', 'role', ROLES],
37
+ ['workspace_invitation', 'role', ROLES]
38
+ ])
39
+ await addIndexes(database, [
40
+ ['workspace', ['owner_id']],
41
+ ['workspace_member', ['user_id']],
42
+ ['workspace_invitation', ['workspace_id', 'revoked_at']]
43
+ ])
44
+ }
45
+
46
+ export async function down(database: Kysely<unknown>): Promise<void> {
47
+ await dropTables(database, TABLES)
48
+ }