@open-pencil/cloud 0.17.0-beta.4 → 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 (206) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/services.mjs +1 -1
  5. package/dist/bin/services.mjs.map +1 -1
  6. package/dist/client.d.ts +296 -27
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +649 -295
  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 +331 -21
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1773 -32
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3478 -288
  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 +466 -13
  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 +447 -290
  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 +2963 -294
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/server.d.ts +3473 -842
  34. package/dist/server.d.ts.map +1 -1
  35. package/dist/server.js +12187 -8244
  36. package/dist/server.js.map +1 -1
  37. package/dist/server.mjs +7739 -3548
  38. package/dist/server.mjs.map +1 -1
  39. package/dist/server2.mjs +5 -5
  40. package/dist/server2.mjs.map +1 -1
  41. package/package.json +22 -5
  42. package/src/admin/audit/service.ts +2 -2
  43. package/src/admin/documents/service.ts +76 -6
  44. package/src/admin/reports/service.ts +7 -1
  45. package/src/client/api.ts +23 -471
  46. package/src/client/auth/client.ts +22 -3
  47. package/src/client/billing.ts +80 -0
  48. package/src/client/community.ts +40 -0
  49. package/src/client/discovery.ts +35 -9
  50. package/src/client/documents.ts +160 -0
  51. package/src/client/index.ts +7 -0
  52. package/src/client/portal/account.ts +54 -2
  53. package/src/client/portal/request.ts +2 -0
  54. package/src/client/response.ts +21 -0
  55. package/src/client/schema.ts +8 -0
  56. package/src/client/services.ts +23 -18
  57. package/src/client/sharing.ts +262 -0
  58. package/src/client/versions.ts +104 -0
  59. package/src/contract/account.ts +50 -0
  60. package/src/contract/billing.ts +166 -0
  61. package/src/contract/collaboration.ts +5 -0
  62. package/src/contract/community.ts +60 -0
  63. package/src/contract/discovery.ts +63 -2
  64. package/src/contract/entitlements.ts +10 -0
  65. package/src/contract/index.ts +54 -5
  66. package/src/contract/links.ts +57 -4
  67. package/src/contract/locale.ts +27 -0
  68. package/src/contract/portal.ts +12 -1
  69. package/src/contract/routes.ts +10 -0
  70. package/src/contract/services.ts +18 -16
  71. package/src/email/i18n.ts +174 -0
  72. package/src/email/index.ts +13 -2
  73. package/src/email/locales/ar.json +141 -0
  74. package/src/email/locales/de.json +141 -0
  75. package/src/email/locales/es.json +141 -0
  76. package/src/email/locales/fr.json +141 -0
  77. package/src/email/locales/it.json +141 -0
  78. package/src/email/locales/ja.json +141 -0
  79. package/src/email/locales/pl.json +141 -0
  80. package/src/email/locales/pt-br.json +141 -0
  81. package/src/email/locales/ru.json +141 -0
  82. package/src/email/locales/zh-cn.json +141 -0
  83. package/src/email/messages.ts +200 -0
  84. package/src/email/render.ts +142 -276
  85. package/src/email/samples.ts +115 -0
  86. package/src/email/schema.ts +70 -6
  87. package/src/email/templates/BrandEmail.vue +54 -0
  88. package/src/email/templates/DocumentBlocked.vue +45 -0
  89. package/src/email/templates/DocumentInvitation.vue +24 -0
  90. package/src/email/templates/DocumentReport.vue +32 -0
  91. package/src/email/templates/DocumentReportDecided.vue +36 -0
  92. package/src/email/templates/DocumentReportReceived.vue +18 -0
  93. package/src/email/templates/DocumentRestored.vue +24 -0
  94. package/src/email/templates/EmailChangeRequested.vue +24 -0
  95. package/src/email/templates/EmailRoot.vue +19 -0
  96. package/src/email/templates/EmailText.vue +9 -0
  97. package/src/email/templates/EmailVerification.vue +38 -0
  98. package/src/email/templates/EnrollmentNotification.vue +24 -0
  99. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  100. package/src/email/templates/NewSignIn.vue +37 -0
  101. package/src/email/templates/PasswordChanged.vue +22 -0
  102. package/src/email/templates/PasswordReset.vue +23 -0
  103. package/src/email/templates/StorageLimitReached.vue +28 -0
  104. package/src/email/templates/TwoStepChanged.vue +32 -0
  105. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  106. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  107. package/src/email/templates/brand.ts +9 -61
  108. package/src/email/templates/localization.ts +17 -0
  109. package/src/errors/index.ts +6 -0
  110. package/src/global.d.ts +7 -0
  111. package/src/runtime/cloudflare/relay/index.ts +7 -1
  112. package/src/runtime/cloudflare/tsconfig.json +2 -1
  113. package/src/runtime/cloudflare/worker.ts +8 -1
  114. package/src/runtime/node/cleanup.ts +5 -1
  115. package/src/runtime/node/email/transport.ts +13 -10
  116. package/src/runtime/node/main.ts +1 -1
  117. package/src/runtime/node/server.ts +12 -2
  118. package/src/runtime/node/services/main.ts +1 -1
  119. package/src/runtime/posthog/errors.ts +2 -1
  120. package/src/runtime/s3/objects.ts +17 -0
  121. package/src/runtime/site/community.ts +101 -0
  122. package/src/runtime/site/server.ts +17 -1
  123. package/src/server/account/deletion.ts +2 -0
  124. package/src/server/account/routes.ts +271 -240
  125. package/src/server/account/tokens.ts +57 -0
  126. package/src/server/api/router.ts +23 -0
  127. package/src/server/app/checks.ts +84 -0
  128. package/src/server/app/editors.ts +20 -0
  129. package/src/server/app/index.ts +128 -0
  130. package/src/server/app/indexing.ts +40 -0
  131. package/src/server/app/limiters.ts +53 -0
  132. package/src/server/app/routes.ts +114 -0
  133. package/src/server/app/services.ts +185 -0
  134. package/src/server/auth/access-tokens.ts +62 -0
  135. package/src/server/auth/adapter.ts +21 -1
  136. package/src/server/auth/email.ts +4 -1
  137. package/src/server/auth/enrollment.ts +116 -0
  138. package/src/server/auth/factory.ts +88 -131
  139. package/src/server/auth/logger.ts +23 -0
  140. package/src/server/auth/mfa-assurance.ts +51 -0
  141. package/src/server/auth/passwords.ts +43 -0
  142. package/src/server/auth/session.ts +2 -0
  143. package/src/server/billing/index.ts +6 -0
  144. package/src/server/billing/routes.ts +27 -0
  145. package/src/server/billing/tokens.ts +37 -0
  146. package/src/server/cleanup/configured.ts +16 -3
  147. package/src/server/cleanup/worker.ts +10 -1
  148. package/src/server/collaboration/relay/hub.ts +25 -142
  149. package/src/server/collaboration/relay/room.ts +154 -0
  150. package/src/server/collaboration/service.ts +21 -2
  151. package/src/server/community/index.ts +2 -0
  152. package/src/server/community/routes.ts +93 -0
  153. package/src/server/community/service.ts +134 -0
  154. package/src/server/config/deployment.ts +17 -5
  155. package/src/server/config/index.ts +1 -1
  156. package/src/server/config/public.ts +7 -1
  157. package/src/server/config/schema.ts +40 -292
  158. package/src/server/config/toml/schema.ts +307 -0
  159. package/src/server/db/index.ts +1 -0
  160. package/src/server/db/migrate.ts +13 -1
  161. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  162. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  163. package/src/server/db/migrations/011_account_ids.ts +30 -0
  164. package/src/server/db/migrations/012_email_locales.ts +34 -0
  165. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  166. package/src/server/db/migrations/014_report_replies.ts +28 -0
  167. package/src/server/db/migrations/schema.ts +26 -1
  168. package/src/server/db/tables.ts +30 -1
  169. package/src/server/db/users.ts +22 -0
  170. package/src/server/documents/index.ts +1 -1
  171. package/src/server/documents/limits.ts +7 -1
  172. package/src/server/documents/service.ts +12 -402
  173. package/src/server/documents/uploads.ts +450 -0
  174. package/src/server/documents/versions/service.ts +81 -24
  175. package/src/server/email/invitations.ts +1 -0
  176. package/src/server/email/service.ts +31 -4
  177. package/src/server/email/types.ts +12 -0
  178. package/src/server/errors/index.ts +1 -9
  179. package/src/server/index.ts +12 -5
  180. package/src/server/invitations/types.ts +5 -1
  181. package/src/server/objects/types.ts +5 -0
  182. package/src/server/policy/configured.ts +9 -3
  183. package/src/server/policy/database.ts +13 -2
  184. package/src/server/policy/policy.ts +39 -12
  185. package/src/server/policy/service.ts +71 -52
  186. package/src/server/policy/storage.ts +33 -0
  187. package/src/server/quota/index.ts +6 -0
  188. package/src/server/quota/notices.ts +121 -0
  189. package/src/server/quota/storage.ts +5 -0
  190. package/src/server/rate-limit/middleware.ts +4 -0
  191. package/src/server/reports/index.ts +1 -0
  192. package/src/server/reports/replies.ts +55 -0
  193. package/src/server/reports/routes.ts +3 -1
  194. package/src/server/reports/service.ts +24 -2
  195. package/src/server/sharing/capabilities/service.ts +2 -3
  196. package/src/server/sharing/invitations/service.ts +14 -4
  197. package/src/server/validation.ts +3 -0
  198. package/src/server/workspaces/members.ts +7 -19
  199. package/src/services/app.ts +1 -3
  200. package/src/services/config.ts +1 -0
  201. package/src/services/usage.ts +6 -14
  202. package/src/email/templates/document-invitation.ts +0 -35
  203. package/src/email/templates/enrollment.ts +0 -27
  204. package/src/email/templates/layout.ts +0 -18
  205. package/src/server/app.ts +0 -453
  206. /package/src/{server/errors → errors}/posthog.ts +0 -0
@@ -0,0 +1,134 @@
1
+ import {
2
+ communityThumbnailPath,
3
+ type CommunityDocument,
4
+ type CommunityDownload,
5
+ type CommunityVersion,
6
+ type DocumentVersion
7
+ } from '#cloud/contract'
8
+ import { isBannedNow, userIdText, type CloudDatabase } from '#cloud/server/db'
9
+ import { DocumentNotFoundError, type DocumentService } from '#cloud/server/documents'
10
+ import type { DocumentVersionService } from '#cloud/server/documents/versions'
11
+ import type { ObjectStore } from '#cloud/server/objects'
12
+ import type { Kysely } from 'kysely'
13
+
14
+ import { extractFigThumbnailFromReader } from '@open-pencil/fig'
15
+
16
+ const communityVersion = (version: DocumentVersion): CommunityVersion => ({
17
+ id: version.id,
18
+ name: version.name ?? '',
19
+ description: version.description || null,
20
+ createdAt: version.createdAt,
21
+ current: version.current
22
+ })
23
+
24
+ /**
25
+ * The deployment's community gallery: the documents of the workspace its config names, which
26
+ * anyone may open read-only without signing in or a link. Nothing marks a document as published;
27
+ * saving it to the workspace publishes it and moving it out takes it down. A document the
28
+ * workspace's members could not open either — deleted, taken down by an administrator, never
29
+ * saved, or made by a banned account — is not in the gallery.
30
+ */
31
+ export function createCommunityService(
32
+ database: Kysely<CloudDatabase>,
33
+ objects: ObjectStore,
34
+ documents: Pick<DocumentService, 'downloadShared' | 'imageLinksShared'>,
35
+ versions: Pick<DocumentVersionService, 'namedSharedIn' | 'downloadNamedShared'>,
36
+ workspaceId: string | null
37
+ ) {
38
+ function published() {
39
+ return database
40
+ .selectFrom('document')
41
+ .innerJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')
42
+ .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
43
+ .select([
44
+ 'document.id',
45
+ 'document.name',
46
+ 'document.kind',
47
+ 'document.updatedAt',
48
+ 'document.currentRevisionId as revisionId',
49
+ 'storageObject.objectKey',
50
+ 'storageObject.byteSize'
51
+ ])
52
+ .where('document.workspaceId', '=', workspaceId ?? '')
53
+ .where('document.deletedAt', 'is', null)
54
+ .where('document.disabledAt', 'is', null)
55
+ .where((expression) =>
56
+ expression.not(
57
+ expression.exists(
58
+ expression
59
+ .selectFrom('user')
60
+ .select('user.id')
61
+ .whereRef(userIdText, '=', 'document.createdBy')
62
+ .where(isBannedNow)
63
+ )
64
+ )
65
+ )
66
+ }
67
+
68
+ /** A document of the gallery, or not found for any other, so nothing outside it shows. */
69
+ async function find(documentId: string) {
70
+ if (!workspaceId) throw new DocumentNotFoundError()
71
+ const row = await published().where('document.id', '=', documentId).executeTakeFirst()
72
+ if (!row?.revisionId) throw new DocumentNotFoundError()
73
+ return { ...row, revisionId: row.revisionId }
74
+ }
75
+
76
+ return {
77
+ /** Whether the deployment has a gallery at all. */
78
+ enabled: workspaceId !== null,
79
+
80
+ /** The gallery's documents, most recently changed first, each with its named versions. */
81
+ async list(): Promise<CommunityDocument[]> {
82
+ if (!workspaceId) return []
83
+ const rows = (await published().orderBy('document.updatedAt', 'desc').execute()).flatMap(
84
+ ({ revisionId, ...row }) => (revisionId ? [{ ...row, revisionId }] : [])
85
+ )
86
+ const named = await versions.namedSharedIn(
87
+ workspaceId,
88
+ rows.map((row) => ({ id: row.id, currentRevisionId: row.revisionId }))
89
+ )
90
+ return rows.map((row) => ({
91
+ id: row.id,
92
+ name: row.name,
93
+ kind: row.kind,
94
+ updatedAt: new Date(row.updatedAt).toISOString(),
95
+ revisionId: row.revisionId,
96
+ thumbnailPath: communityThumbnailPath(row.id, row.revisionId),
97
+ versions: (named.get(row.id) ?? []).map(communityVersion)
98
+ }))
99
+ },
100
+
101
+ /** A gallery document as it is now, or one of its named versions, with where to download it. */
102
+ async download(documentId: string, versionId?: string): Promise<CommunityDownload> {
103
+ await find(documentId)
104
+ if (!versionId) return { document: await documents.downloadShared(documentId), version: null }
105
+ const named = await versions.downloadNamedShared(documentId, versionId)
106
+ return { document: named.document, version: communityVersion(named.version) }
107
+ },
108
+
109
+ /** Links for the images a gallery document's live room names. */
110
+ async imageLinks(documentId: string, checksums: string[]) {
111
+ await find(documentId)
112
+ return documents.imageLinksShared(documentId, checksums)
113
+ },
114
+
115
+ /**
116
+ * The thumbnail a gallery document's stored file carries, read from storage in ranges, for
117
+ * the revision it is now; null when that revision is not current any more or has none.
118
+ */
119
+ async thumbnail(documentId: string, revisionId: string): Promise<Uint8Array | null> {
120
+ const row = await find(documentId)
121
+ if (row.revisionId !== revisionId) return null
122
+ return extractFigThumbnailFromReader({
123
+ size: Number(row.byteSize),
124
+ read: async (start, endExclusive) => {
125
+ const bytes = await objects.readRange(row.objectKey, start, endExclusive)
126
+ if (!bytes) throw new DocumentNotFoundError()
127
+ return bytes
128
+ }
129
+ })
130
+ }
131
+ }
132
+ }
133
+
134
+ export type CommunityService = ReturnType<typeof createCommunityService>
@@ -2,13 +2,12 @@ import { staticEntitlementsFromTOML } from '#cloud/server/policy/static'
2
2
  import { parse as parseTOML } from 'smol-toml'
3
3
  import * as v from 'valibot'
4
4
 
5
+ import { parseCloudServerConfig, type CloudServerConfig } from './schema'
5
6
  import {
6
7
  cloudDeploymentConfigSchema,
7
- parseCloudServerConfig,
8
8
  type CloudDeploymentConfig,
9
- type CloudSecretReference,
10
- type CloudServerConfig
11
- } from './schema'
9
+ type CloudSecretReference
10
+ } from './toml/schema'
12
11
 
13
12
  export type CloudEnvironment = Readonly<Record<string, string | undefined>>
14
13
 
@@ -41,6 +40,11 @@ function staticEntitlements(config: CloudDeploymentConfig) {
41
40
  return staticEntitlementsFromTOML(config.entitlements)
42
41
  }
43
42
 
43
+ function defaultEntitlements(config: CloudDeploymentConfig) {
44
+ if (config.entitlements?.source !== 'database') return undefined
45
+ return staticEntitlementsFromTOML(config.entitlements)
46
+ }
47
+
44
48
  function emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
45
49
  if (config.email.transport === 'none') return { emailTransport: 'none' as const }
46
50
  if (config.email.transport === 'cloudflare') {
@@ -97,7 +101,7 @@ function serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironm
97
101
  servicesTokenLifetimeSeconds: config.services
98
102
  ? config.services.token_lifetime_minutes * 60
99
103
  : undefined,
100
- billingPortalURL: config.billing?.portal_url,
104
+ billingEndpoint: config.billing?.endpoint,
101
105
  internalServiceToken: config.internal_api
102
106
  ? requiredSecret(environment, config.internal_api.service_token)
103
107
  : undefined
@@ -148,6 +152,7 @@ export function parseCloudDeploymentConfig(
148
152
  trustedOrigins: config.deployment.trusted_origins,
149
153
  localEditor: config.deployment.local_editor,
150
154
  listingMinimumEditorVersion: config.deployment.listing?.minimum_editor_version,
155
+ minimumEditorVersion: config.deployment.minimum_editor_version,
151
156
  databaseURL: requiredSecret(environment, config.database.url),
152
157
  authSecret: requiredSecret(environment, config.authentication.secret),
153
158
  enrollmentMode: config.authentication.enrollment.mode,
@@ -192,10 +197,17 @@ export function parseCloudDeploymentConfig(
192
197
  s3DeletedPrefix: config.object_storage.deleted_prefix,
193
198
  relayURL: config.collaboration.relay_url,
194
199
  staticEntitlements: staticEntitlements(config),
200
+ defaultEntitlements: defaultEntitlements(config),
195
201
  ...emailConfig(config, environment),
196
202
  ...workerConfig(config),
197
203
  ...serviceConfig(config, environment),
198
204
  legal: legalConfig(config),
205
+ community: config.community ? { workspaceId: config.community.workspace } : undefined,
206
+ branding: config.deployment.branding && {
207
+ name: config.deployment.branding.name,
208
+ logoURL: config.deployment.branding.logo_url,
209
+ helpURL: config.deployment.branding.help_url
210
+ },
199
211
  errorTracking: errorTrackingConfig(config, environment),
200
212
  technicalLimits: technicalLimits(config)
201
213
  })
@@ -9,7 +9,7 @@ export {
9
9
  type CloudDeploymentConfig,
10
10
  type CloudDeploymentInput,
11
11
  type CloudSecretReference
12
- } from './schema'
12
+ } from './toml/schema'
13
13
  export { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/contract'
14
14
  export {
15
15
  CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES,
@@ -1,4 +1,5 @@
1
1
  import {
2
+ CLOUD_BILLING_CONTRACT_VERSION,
2
3
  CLOUD_SERVICES_CONTRACT_VERSION,
3
4
  CLOUD_PROTOCOL_VERSION,
4
5
  parseCloudDiscovery,
@@ -58,10 +59,15 @@ export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscov
58
59
  listing: config.listingMinimumEditorVersion
59
60
  ? { minimumEditorVersion: config.listingMinimumEditorVersion }
60
61
  : undefined,
62
+ minimumEditorVersion: config.minimumEditorVersion,
61
63
  services: config.servicesEndpoint
62
64
  ? { endpoint: config.servicesEndpoint, contractVersion: CLOUD_SERVICES_CONTRACT_VERSION }
63
65
  : undefined,
64
- billing: config.billingPortalURL ? { portalURL: config.billingPortalURL } : undefined,
66
+ billing: config.billingEndpoint
67
+ ? { endpoint: config.billingEndpoint, contractVersion: CLOUD_BILLING_CONTRACT_VERSION }
68
+ : undefined,
69
+ community: config.community,
70
+ branding: config.branding,
65
71
  legal: config.legal
66
72
  })
67
73
  }
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,
3
3
  cloudEditorVersionSchema,
4
- RELAY_MINIMUM_MESSAGE_BYTES
4
+ RELAY_MINIMUM_MESSAGE_BYTES,
5
+ sendsTokenSafely
5
6
  } from '#cloud/contract'
6
- import { staticEntitlementsSchema, staticEntitlementsTOMLSchema } from '#cloud/server/policy/schema'
7
+ import { staticEntitlementsSchema } from '#cloud/server/policy/schema'
7
8
  import * as v from 'valibot'
8
9
 
9
10
  import {
@@ -35,7 +36,7 @@ const optionalTextSchema = v.optional(v.pipe(v.string(), v.trim(), v.minLength(1
35
36
  * A prefix deleted files move under: one lowercase path segment and a slash, which no object key
36
37
  * the server makes starts with (they start with `documents/`).
37
38
  */
38
- const deletedPrefixSchema = v.pipe(
39
+ export const deletedPrefixSchema = v.pipe(
39
40
  v.string(),
40
41
  v.regex(/^[a-z0-9][a-z0-9-]*\/$/),
41
42
  v.check((prefix) => prefix !== 'documents/', 'deleted_prefix cannot be documents/')
@@ -45,6 +46,7 @@ const rawCloudServerConfigSchema = v.object({
45
46
  deployment: v.picklist(['official', 'self-hosted']),
46
47
  publicURL: httpURLSchema,
47
48
  listingMinimumEditorVersion: v.optional(cloudEditorVersionSchema),
49
+ minimumEditorVersion: v.optional(cloudEditorVersionSchema),
48
50
  relayURL: v.optional(websocketURLSchema),
49
51
  technicalLimits: v.optional(
50
52
  v.object({
@@ -68,6 +70,8 @@ const rawCloudServerConfigSchema = v.object({
68
70
  }
69
71
  ),
70
72
  staticEntitlements: v.optional(staticEntitlementsSchema),
73
+ /** With database entitlements, what an account without stored ones takes, value by value. */
74
+ defaultEntitlements: v.optional(staticEntitlementsSchema),
71
75
  databaseURL: v.pipe(v.string(), v.url()),
72
76
  authSecret: v.pipe(v.string(), v.minLength(32)),
73
77
  trustedOrigins: v.optional(v.array(httpURLSchema), []),
@@ -164,7 +168,8 @@ const rawCloudServerConfigSchema = v.object({
164
168
  v.pipe(v.number(), v.integer(), v.minValue(60), v.maxValue(60 * 60)),
165
169
  10 * 60
166
170
  ),
167
- billingPortalURL: v.optional(httpURLSchema),
171
+ /** The billing service accounts buy plans and credits from, which discovery advertises. */
172
+ billingEndpoint: v.optional(httpURLSchema),
168
173
  /** The bearer token services such as billing present to the internal API. */
169
174
  internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32))),
170
175
  /**
@@ -182,6 +187,19 @@ const rawCloudServerConfigSchema = v.object({
182
187
  minimumAge: v.optional(v.pipe(v.number(), v.integer(), v.minValue(13), v.maxValue(21)))
183
188
  })
184
189
  ),
190
+ /**
191
+ * The workspace whose documents anyone may open read-only, without signing in or a link: the
192
+ * deployment's community gallery. Without it the server has none.
193
+ */
194
+ community: v.optional(v.object({ workspaceId: v.pipe(v.string(), v.uuid()) })),
195
+ /** How a self-hosted server names itself on its public pages. */
196
+ branding: v.optional(
197
+ v.object({
198
+ name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
199
+ logoURL: v.optional(httpURLSchema),
200
+ helpURL: v.optional(httpURLSchema)
201
+ })
202
+ ),
185
203
  /** Where server errors are reported; without it the server reports nothing. */
186
204
  errorTracking: v.optional(
187
205
  v.object({
@@ -269,17 +287,29 @@ function validateEmailConfig(config: CloudServerConfig): void {
269
287
 
270
288
  function validateServiceConfig(config: CloudServerConfig): void {
271
289
  requireTogether(config, 'Services', ['servicesEndpoint', 'servicesSigningKey'])
290
+ // Billing tokens are signed with the services' key, and billing sets plans through the
291
+ // internal API, which static entitlements would hide.
292
+ if (config.billingEndpoint && !config.servicesSigningKey) {
293
+ throw new CloudConfigError('Billing needs the services signing key to sign its tokens')
294
+ }
295
+ if (config.billingEndpoint && !config.internalServiceToken) {
296
+ throw new CloudConfigError('Billing needs the internal API to set the plans it sells')
297
+ }
272
298
  if (config.internalServiceToken && config.staticEntitlements) {
273
299
  throw new CloudConfigError(
274
300
  'The internal API writes database entitlements, which static entitlements would hide'
275
301
  )
276
302
  }
277
- if (
278
- config.deployment === 'official' &&
279
- config.servicesEndpoint &&
280
- new URL(config.servicesEndpoint).protocol !== 'https:'
281
- ) {
282
- throw new CloudConfigError('Official services endpoint must use HTTPS')
303
+ // Editors send these endpoints a bearer token, which must not cross the network in the clear.
304
+ for (const [name, endpoint] of [
305
+ ['services', config.servicesEndpoint],
306
+ ['billing', config.billingEndpoint]
307
+ ] as const) {
308
+ if (endpoint && !sendsTokenSafely(endpoint)) {
309
+ throw new CloudConfigError(
310
+ `The ${name} endpoint must use HTTPS, or HTTP only to 127.0.0.1 or [::1] for development`
311
+ )
312
+ }
283
313
  }
284
314
  }
285
315
 
@@ -316,285 +346,3 @@ export function parseCloudServerConfig(input: unknown): CloudServerConfig {
316
346
  validateLegalConfig(config)
317
347
  return config
318
348
  }
319
-
320
- /** PostHog's EU Cloud ingestion host, where OpenPencil's own project is. */
321
- const POSTHOG_DEFAULT_HOST = 'https://eu.i.posthog.com'
322
-
323
- const DEFAULT_SECRET_NAMES = {
324
- databaseURL: 'DATABASE_URL',
325
- authSecret: 'BETTER_AUTH_SECRET',
326
- googleClientId: 'GOOGLE_CLIENT_ID',
327
- googleClientSecret: 'GOOGLE_CLIENT_SECRET',
328
- applePrivateKey: 'APPLE_PRIVATE_KEY',
329
- s3AccessKeyId: 'S3_ACCESS_KEY_ID',
330
- s3SecretAccessKey: 'S3_SECRET_ACCESS_KEY',
331
- s3SessionToken: 'S3_SESSION_TOKEN',
332
- smtpUser: 'OPENPENCIL_CLOUD_SMTP_USER',
333
- smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',
334
- turnstileSecretKey: 'TURNSTILE_SECRET_KEY',
335
- servicesSigningKey: 'OPENPENCIL_CLOUD_SERVICES_SIGNING_KEY',
336
- internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN',
337
- posthogProjectAPIKey: 'POSTHOG_PROJECT_API_KEY'
338
- } as const
339
-
340
- const urlSchema = v.pipe(v.string(), v.url())
341
- const textSchema = v.pipe(v.string(), v.trim(), v.minLength(1))
342
- const positiveIntegerSchema = v.pipe(v.number(), v.integer(), v.minValue(1))
343
- const secretReferenceSchema = v.strictObject({ from_env: textSchema })
344
- const configurableTextSchema = v.union([textSchema, secretReferenceSchema])
345
- const defaultReference = (name: string) => v.optional(secretReferenceSchema, { from_env: name })
346
-
347
- const providerSchema = v.strictObject({
348
- google: v.optional(
349
- v.strictObject({
350
- client_id: v.optional(configurableTextSchema, {
351
- from_env: DEFAULT_SECRET_NAMES.googleClientId
352
- }),
353
- client_secret: defaultReference(DEFAULT_SECRET_NAMES.googleClientSecret)
354
- })
355
- ),
356
- apple: v.optional(
357
- v.strictObject({
358
- client_id: textSchema,
359
- team_id: textSchema,
360
- key_id: textSchema,
361
- private_key: defaultReference(DEFAULT_SECRET_NAMES.applePrivateKey),
362
- app_bundle_identifier: v.optional(textSchema)
363
- })
364
- )
365
- })
366
-
367
- const emailSchema = v.optional(
368
- v.variant('transport', [
369
- v.strictObject({ transport: v.literal('none') }),
370
- v.strictObject({
371
- transport: v.literal('smtp'),
372
- from: textSchema,
373
- smtp: v.strictObject({
374
- host: textSchema,
375
- port: positiveIntegerSchema,
376
- secure: v.optional(v.boolean()),
377
- user: v.optional(secretReferenceSchema, {
378
- from_env: DEFAULT_SECRET_NAMES.smtpUser
379
- }),
380
- password: v.optional(secretReferenceSchema, {
381
- from_env: DEFAULT_SECRET_NAMES.smtpPassword
382
- })
383
- })
384
- }),
385
- v.strictObject({ transport: v.literal('cloudflare'), from: textSchema })
386
- ]),
387
- { transport: 'none' }
388
- )
389
-
390
- /**
391
- * Every table is strict: a key the schema doesn't know, such as one renamed since, stops startup
392
- * instead of leaving its setting at a default the operator never chose.
393
- */
394
- export const cloudDeploymentConfigSchema = v.strictObject({
395
- schema_version: v.literal(2),
396
- deployment: v.strictObject({
397
- mode: v.picklist(['official', 'self-hosted']),
398
- public_url: urlSchema,
399
- indexing: v.optional(v.picklist(['allow', 'deny']), 'deny'),
400
- trusted_origins: v.optional(v.array(urlSchema), []),
401
- // The server's editor works with files on this device without signing in to the server.
402
- local_editor: v.optional(v.boolean(), true),
403
- listing: v.optional(v.strictObject({ minimum_editor_version: cloudEditorVersionSchema }))
404
- }),
405
- database: v.optional(
406
- v.strictObject({ url: defaultReference(DEFAULT_SECRET_NAMES.databaseURL) }),
407
- {
408
- url: { from_env: DEFAULT_SECRET_NAMES.databaseURL }
409
- }
410
- ),
411
- authentication: v.strictObject({
412
- secret: defaultReference(DEFAULT_SECRET_NAMES.authSecret),
413
- enrollment: v.optional(
414
- v.strictObject({
415
- mode: v.optional(v.picklist(['open', 'approval', 'closed']), 'open'),
416
- notification_emails: v.optional(v.array(v.pipe(v.string(), v.email())), [])
417
- }),
418
- { mode: 'open', notification_emails: [] }
419
- ),
420
- email_password: v.optional(
421
- v.strictObject({
422
- enabled: v.optional(v.boolean(), false),
423
- sign_up: v.optional(v.boolean(), true),
424
- minimum_password_length: v.optional(
425
- v.pipe(v.number(), v.integer(), v.minValue(8), v.maxValue(128)),
426
- 8
427
- ),
428
- maximum_password_length: v.optional(
429
- v.pipe(v.number(), v.integer(), v.minValue(15), v.maxValue(128)),
430
- 128
431
- ),
432
- verification_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
433
- password_reset_link_lifetime_minutes: v.optional(positiveIntegerSchema, 60),
434
- compromised_password_check: v.optional(v.boolean(), false)
435
- }),
436
- {
437
- enabled: false,
438
- sign_up: true,
439
- minimum_password_length: 8,
440
- maximum_password_length: 128,
441
- verification_link_lifetime_minutes: 60,
442
- password_reset_link_lifetime_minutes: 60,
443
- compromised_password_check: false
444
- }
445
- ),
446
- mfa: v.optional(
447
- v.strictObject({
448
- required_for_admins: v.optional(v.boolean(), false),
449
- totp: v.optional(v.boolean(), false),
450
- recovery_codes: v.optional(v.boolean(), false),
451
- trusted_device_lifetime_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 14)
452
- }),
453
- {
454
- required_for_admins: false,
455
- totp: false,
456
- recovery_codes: false,
457
- trusted_device_lifetime_days: 14
458
- }
459
- ),
460
- // Passkeys belong to public_url's host and origin.
461
- passkeys: v.optional(
462
- v.strictObject({
463
- enabled: v.optional(v.boolean(), false),
464
- rp_name: v.optional(textSchema, 'OpenPencil Cloud')
465
- }),
466
- { enabled: false, rp_name: 'OpenPencil Cloud' }
467
- ),
468
- captcha: v.optional(
469
- v.strictObject({
470
- provider: v.literal('cloudflare-turnstile'),
471
- site_key: textSchema,
472
- secret_key: defaultReference(DEFAULT_SECRET_NAMES.turnstileSecretKey),
473
- allowed_hostnames: v.optional(v.array(textSchema), [])
474
- })
475
- ),
476
- trusted_proxies: v.optional(
477
- v.strictObject({
478
- headers: v.optional(v.array(textSchema), []),
479
- addresses: v.optional(v.array(textSchema), [])
480
- }),
481
- { headers: [], addresses: [] }
482
- ),
483
- providers: v.optional(providerSchema, {})
484
- }),
485
- object_storage: v.strictObject({
486
- endpoint: urlSchema,
487
- region: textSchema,
488
- bucket: textSchema,
489
- credentials: v.optional(
490
- v.strictObject({
491
- access_key_id: defaultReference(DEFAULT_SECRET_NAMES.s3AccessKeyId),
492
- secret_access_key: defaultReference(DEFAULT_SECRET_NAMES.s3SecretAccessKey),
493
- session_token: v.optional(secretReferenceSchema, {
494
- from_env: DEFAULT_SECRET_NAMES.s3SessionToken
495
- })
496
- }),
497
- {
498
- access_key_id: { from_env: DEFAULT_SECRET_NAMES.s3AccessKeyId },
499
- secret_access_key: { from_env: DEFAULT_SECRET_NAMES.s3SecretAccessKey }
500
- }
501
- ),
502
- force_path_style: v.optional(v.boolean(), true),
503
- checksum_verification: v.optional(v.picklist(['native', 'metadata']), 'native'),
504
- server_side_encryption: v.optional(v.picklist(['AES256', 'aws:kms'])),
505
- kms_key_id: v.optional(textSchema),
506
- /**
507
- * Keeps each file cleanup deletes under this prefix, such as `deleted/`, so a database restored
508
- * to an earlier time still finds it; a lifecycle rule on the prefix expires them.
509
- */
510
- deleted_prefix: v.optional(deletedPrefixSchema),
511
- maximum_upload_bytes: v.optional(positiveIntegerSchema)
512
- }),
513
- collaboration: v.optional(
514
- v.strictObject({
515
- relay_url: v.optional(urlSchema),
516
- maximum_message_bytes: v.optional(positiveIntegerSchema),
517
- maximum_connections_per_room: v.optional(positiveIntegerSchema)
518
- }),
519
- {}
520
- ),
521
- documents: v.optional(
522
- v.strictObject({
523
- retention_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 30),
524
- purge_grace_days: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0)), 7)
525
- }),
526
- { retention_days: 30, purge_grace_days: 7 }
527
- ),
528
- email: emailSchema,
529
- workers: v.optional(
530
- v.strictObject({
531
- email: v.optional(
532
- v.strictObject({
533
- batch_size: v.optional(positiveIntegerSchema, 50),
534
- interval_ms: v.optional(positiveIntegerSchema, 30_000),
535
- lease_ms: v.optional(positiveIntegerSchema, 300_000),
536
- maximum_attempts: v.optional(positiveIntegerSchema, 5)
537
- }),
538
- { batch_size: 50, interval_ms: 30_000, lease_ms: 300_000, maximum_attempts: 5 }
539
- ),
540
- cleanup: v.optional(
541
- v.strictObject({
542
- enabled: v.optional(v.boolean(), true),
543
- batch_size: v.optional(positiveIntegerSchema, 100),
544
- interval_ms: v.optional(positiveIntegerSchema, 60_000),
545
- lease_ms: v.optional(positiveIntegerSchema, 300_000)
546
- }),
547
- { enabled: true, batch_size: 100, interval_ms: 60_000, lease_ms: 300_000 }
548
- )
549
- })
550
- ),
551
- entitlements: v.optional(
552
- v.variant('source', [
553
- v.strictObject({ source: v.literal('static'), ...staticEntitlementsTOMLSchema.entries }),
554
- v.strictObject({ source: v.literal('database') })
555
- ])
556
- ),
557
- services: v.optional(
558
- v.strictObject({
559
- endpoint: urlSchema,
560
- signing_key: defaultReference(DEFAULT_SECRET_NAMES.servicesSigningKey),
561
- token_lifetime_minutes: v.optional(
562
- v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(60)),
563
- 10
564
- )
565
- })
566
- ),
567
- billing: v.optional(v.strictObject({ portal_url: urlSchema })),
568
- internal_api: v.optional(
569
- v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
570
- ),
571
- /**
572
- * Optional: the operator's terms and privacy policy, linked at sign-up and in the portal, and
573
- * with `require_acceptance`, accepted once per `terms_version` before an account uses the server.
574
- */
575
- legal: v.optional(
576
- v.strictObject({
577
- terms_url: v.optional(urlSchema),
578
- privacy_url: v.optional(urlSchema),
579
- terms_version: v.optional(textSchema),
580
- require_acceptance: v.optional(v.boolean(), false),
581
- abuse_email: v.optional(v.pipe(v.string(), v.email())),
582
- minimum_age: v.optional(v.pipe(v.number(), v.integer(), v.minValue(13), v.maxValue(21)))
583
- })
584
- ),
585
- /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */
586
- error_tracking: v.optional(
587
- v.strictObject({
588
- provider: v.literal('posthog'),
589
- host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),
590
- project_api_key: v.optional(configurableTextSchema, {
591
- from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey
592
- })
593
- })
594
- )
595
- })
596
-
597
- export type CloudDeploymentConfig = v.InferOutput<typeof cloudDeploymentConfigSchema>
598
- /** Deployment configuration as an operator writes it, before defaults are applied. */
599
- export type CloudDeploymentInput = v.InferInput<typeof cloudDeploymentConfigSchema>
600
- export type CloudSecretReference = v.InferOutput<typeof secretReferenceSchema>