@open-pencil/cloud 0.17.0-beta.1 → 0.17.0-beta.4

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 (235) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/{ai-relay.mjs → services.mjs} +8 -8
  3. package/dist/bin/services.mjs.map +1 -0
  4. package/dist/client.d.ts +236 -46
  5. package/dist/client.d.ts.map +1 -1
  6. package/dist/client.js +649 -400
  7. package/dist/client.js.map +1 -1
  8. package/dist/contract.d.ts +2 -2
  9. package/dist/contract.js +2 -2
  10. package/dist/contract2.js +680 -443
  11. package/dist/contract2.js.map +1 -1
  12. package/dist/email.d.ts +9 -1
  13. package/dist/email.d.ts.map +1 -1
  14. package/dist/email.js +99 -58
  15. package/dist/email.js.map +1 -1
  16. package/dist/index.d.ts +468 -64
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/listen.mjs +575 -738
  19. package/dist/listen.mjs.map +1 -1
  20. package/dist/runtime-node.d.mts +6564 -2934
  21. package/dist/runtime-node.d.mts.map +1 -1
  22. package/dist/runtime-node.mjs +6 -5
  23. package/dist/runtime-node.mjs.map +1 -1
  24. package/dist/server.d.ts +8931 -4198
  25. package/dist/server.d.ts.map +1 -1
  26. package/dist/server.js +5260 -3859
  27. package/dist/server.js.map +1 -1
  28. package/dist/server.mjs +5686 -3736
  29. package/dist/server.mjs.map +1 -1
  30. package/dist/server2.mjs +101 -79
  31. package/dist/server2.mjs.map +1 -1
  32. package/package.json +9 -6
  33. package/src/admin/api/routes.ts +103 -33
  34. package/src/admin/audit/service.ts +25 -6
  35. package/src/admin/documents/service.ts +361 -0
  36. package/src/admin/errors.ts +9 -1
  37. package/src/admin/index.ts +6 -0
  38. package/src/admin/operations/service.ts +7 -0
  39. package/src/admin/reports/service.ts +147 -0
  40. package/src/admin/schema.ts +6 -0
  41. package/src/client/api.ts +36 -21
  42. package/src/client/auth/navigation.ts +6 -5
  43. package/src/client/index.ts +7 -7
  44. package/src/client/portal/account.ts +25 -0
  45. package/src/client/portal/administration.ts +56 -0
  46. package/src/client/{ai.ts → services.ts} +44 -27
  47. package/src/contract/account.ts +58 -2
  48. package/src/contract/admin/index.ts +67 -3
  49. package/src/contract/collaboration.ts +6 -1
  50. package/src/contract/discovery.ts +22 -4
  51. package/src/contract/documents.ts +27 -0
  52. package/src/contract/entitlements.ts +2 -2
  53. package/src/contract/index.ts +63 -37
  54. package/src/contract/relay.ts +6 -0
  55. package/src/contract/reports.ts +42 -0
  56. package/src/contract/services.ts +233 -0
  57. package/src/contract/sharing.ts +3 -9
  58. package/src/email/render.ts +26 -0
  59. package/src/email/schema.ts +11 -1
  60. package/src/email/templates/brand.ts +1 -1
  61. package/src/runtime/cloudflare/environment.ts +31 -6
  62. package/src/runtime/cloudflare/index.ts +1 -1
  63. package/src/runtime/cloudflare/logging.ts +15 -0
  64. package/src/runtime/cloudflare/maintenance.ts +31 -0
  65. package/src/runtime/cloudflare/relay/index.ts +176 -0
  66. package/src/runtime/cloudflare/relay/sockets.ts +112 -0
  67. package/src/runtime/cloudflare/worker.ts +89 -26
  68. package/src/runtime/node/application.ts +5 -3
  69. package/src/runtime/node/bootstrap.ts +20 -4
  70. package/src/runtime/node/cleanup.ts +16 -3
  71. package/src/runtime/node/entitlements/main.ts +14 -11
  72. package/src/runtime/node/index.ts +1 -1
  73. package/src/runtime/node/migrate.ts +5 -1
  74. package/src/runtime/node/relay.ts +8 -2
  75. package/src/runtime/node/request-id.ts +13 -0
  76. package/src/runtime/node/server.ts +71 -15
  77. package/src/runtime/node/{ai-relay → services}/main.ts +6 -6
  78. package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
  79. package/src/runtime/postgres/database.ts +20 -1
  80. package/src/runtime/posthog/errors.ts +32 -0
  81. package/src/runtime/s3/objects.ts +50 -1
  82. package/src/runtime/site/server.ts +33 -4
  83. package/src/server/account/actions.ts +5 -0
  84. package/src/server/account/deletion.ts +302 -0
  85. package/src/server/account/routes.ts +47 -3
  86. package/src/server/account/terms.ts +42 -0
  87. package/src/server/api/router.ts +12 -7
  88. package/src/server/api/types.ts +9 -0
  89. package/src/server/app.ts +93 -15
  90. package/src/server/auth/access-control.ts +63 -0
  91. package/src/server/auth/adapter.ts +11 -0
  92. package/src/server/auth/endpoints.ts +5 -1
  93. package/src/server/auth/factory.ts +30 -3
  94. package/src/server/auth/index.ts +10 -1
  95. package/src/server/cleanup/configured.ts +12 -5
  96. package/src/server/cleanup/documents.ts +165 -71
  97. package/src/server/cleanup/objects.ts +10 -2
  98. package/src/server/cleanup/revisions.ts +24 -7
  99. package/src/server/cleanup/uploads.ts +8 -2
  100. package/src/server/cleanup/worker.ts +5 -2
  101. package/src/server/collaboration/index.ts +3 -0
  102. package/src/server/collaboration/relay/connection.ts +196 -0
  103. package/src/server/collaboration/relay/documents.ts +13 -10
  104. package/src/server/collaboration/relay/hub.ts +279 -195
  105. package/src/server/collaboration/relay/index.ts +3 -1
  106. package/src/server/collaboration/relay/log.ts +79 -0
  107. package/src/server/collaboration/relay/persistence.ts +147 -22
  108. package/src/server/collaboration/relay/resume.ts +28 -0
  109. package/src/server/collaboration/routes.ts +27 -16
  110. package/src/server/collaboration/service.ts +27 -31
  111. package/src/server/config/deployment.ts +35 -4
  112. package/src/server/config/public.ts +5 -4
  113. package/src/server/config/schema.ts +104 -16
  114. package/src/server/db/expressions.ts +15 -1
  115. package/src/server/db/migrate.ts +34 -114
  116. package/src/server/db/migrations/001_accounts.ts +79 -0
  117. package/src/server/db/migrations/002_workspaces.ts +48 -0
  118. package/src/server/db/migrations/003_storage.ts +44 -0
  119. package/src/server/db/migrations/004_documents.ts +193 -0
  120. package/src/server/db/migrations/005_sharing.ts +95 -0
  121. package/src/server/db/migrations/006_operations.ts +110 -0
  122. package/src/server/db/migrations/007_trash.ts +33 -0
  123. package/src/server/db/migrations/008_terms.ts +18 -0
  124. package/src/server/db/migrations/schema.ts +71 -0
  125. package/src/server/db/tables.ts +70 -7
  126. package/src/server/documents/access.ts +66 -55
  127. package/src/server/documents/errors.ts +7 -0
  128. package/src/server/documents/images.ts +2 -1
  129. package/src/server/documents/limits.ts +9 -9
  130. package/src/server/documents/purge.ts +75 -0
  131. package/src/server/documents/repository.ts +2 -0
  132. package/src/server/documents/routes.ts +132 -80
  133. package/src/server/documents/service.ts +18 -4
  134. package/src/server/documents/summary.ts +1 -0
  135. package/src/server/documents/trash.ts +203 -0
  136. package/src/server/documents/versions/checkpoint.ts +2 -1
  137. package/src/server/documents/versions/history.ts +11 -7
  138. package/src/server/documents/versions/routes.ts +36 -25
  139. package/src/server/documents/versions/service.ts +22 -4
  140. package/src/server/errors/index.ts +99 -0
  141. package/src/server/errors/posthog.ts +80 -0
  142. package/src/server/index.ts +56 -16
  143. package/src/server/internal/index.ts +3 -3
  144. package/src/server/internal/routes.ts +7 -15
  145. package/src/server/internal/schema.ts +1 -1
  146. package/src/server/internal/service.ts +17 -23
  147. package/src/server/invitations/budget.ts +66 -0
  148. package/src/server/invitations/index.ts +1 -0
  149. package/src/server/logging.ts +76 -0
  150. package/src/server/objects/types.ts +12 -0
  151. package/src/server/pictures/routes.ts +4 -2
  152. package/src/server/pictures/service.ts +2 -1
  153. package/src/server/policy/database.ts +39 -25
  154. package/src/server/policy/index.ts +2 -1
  155. package/src/server/policy/keys.ts +5 -2
  156. package/src/server/policy/policy.ts +1 -0
  157. package/src/server/policy/schema.ts +2 -2
  158. package/src/server/policy/service.ts +12 -9
  159. package/src/server/policy/static.ts +5 -5
  160. package/src/server/policy/workspace.ts +41 -0
  161. package/src/server/quota/reconcile.ts +2 -0
  162. package/src/server/quota/storage.ts +69 -31
  163. package/src/server/rate-limit/cleanup.ts +17 -5
  164. package/src/server/rate-limit/index.ts +4 -1
  165. package/src/server/rate-limit/middleware.ts +100 -12
  166. package/src/server/reports/index.ts +8 -0
  167. package/src/server/reports/routes.ts +37 -0
  168. package/src/server/reports/service.ts +123 -0
  169. package/src/server/services/errors.ts +7 -0
  170. package/src/server/services/index.ts +8 -0
  171. package/src/server/{ai → services}/keys.ts +11 -11
  172. package/src/server/services/routes.ts +47 -0
  173. package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
  174. package/src/server/sharing/capabilities/service.ts +68 -22
  175. package/src/server/sharing/document-routes.ts +30 -22
  176. package/src/server/sharing/grants/service.ts +11 -18
  177. package/src/server/sharing/http.ts +4 -0
  178. package/src/server/sharing/invitations/service.ts +21 -11
  179. package/src/server/sharing/policy.ts +9 -14
  180. package/src/server/sharing/routes.ts +108 -85
  181. package/src/server/sharing/service.ts +1 -17
  182. package/src/server/validation.ts +59 -2
  183. package/src/server/workspaces/index.ts +1 -0
  184. package/src/server/workspaces/members.ts +89 -38
  185. package/src/server/workspaces/repository.ts +2 -1
  186. package/src/server/workspaces/routes.ts +67 -45
  187. package/src/{ai-relay → services}/app.ts +48 -44
  188. package/src/{ai-relay → services}/config.ts +25 -19
  189. package/src/services/db/index.ts +10 -0
  190. package/src/services/db/migrate.ts +37 -0
  191. package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
  192. package/src/services/db/schema.ts +22 -0
  193. package/src/services/index.ts +18 -0
  194. package/src/{ai-relay → services}/metering.ts +2 -2
  195. package/src/{ai-relay → services}/usage.ts +43 -19
  196. package/dist/bin/ai-relay.mjs.map +0 -1
  197. package/src/ai-relay/db/index.ts +0 -10
  198. package/src/ai-relay/db/migrate.ts +0 -32
  199. package/src/ai-relay/db/schema.ts +0 -20
  200. package/src/ai-relay/index.ts +0 -18
  201. package/src/contract/ai.ts +0 -150
  202. package/src/runtime/cloudflare/relay.ts +0 -136
  203. package/src/server/ai/errors.ts +0 -7
  204. package/src/server/ai/index.ts +0 -4
  205. package/src/server/ai/routes.ts +0 -43
  206. package/src/server/auth/workspace-access.ts +0 -23
  207. package/src/server/db/migrations/001_foundation.ts +0 -164
  208. package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
  209. package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
  210. package/src/server/db/migrations/004_document_sharing.ts +0 -82
  211. package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
  212. package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
  213. package/src/server/db/migrations/007_collaboration_state.ts +0 -25
  214. package/src/server/db/migrations/008_storage_reservations.ts +0 -37
  215. package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
  216. package/src/server/db/migrations/010_upload_finalization.ts +0 -22
  217. package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
  218. package/src/server/db/migrations/012_transactional_email.ts +0 -48
  219. package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
  220. package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
  221. package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
  222. package/src/server/db/migrations/016_auth_schema.ts +0 -16
  223. package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
  224. package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
  225. package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
  226. package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
  227. package/src/server/db/migrations/021_document_versions.ts +0 -66
  228. package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
  229. package/src/server/db/migrations/023_document_images.ts +0 -61
  230. package/src/server/db/migrations/024_account_activity.ts +0 -66
  231. package/src/server/db/migrations/025_table_names.ts +0 -58
  232. package/src/server/db/migrations/026_user_picture.ts +0 -30
  233. package/src/server/db/migrations/027_document_kind.ts +0 -19
  234. package/src/server/db/migrations/helpers.ts +0 -78
  235. /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
@@ -1,41 +1,55 @@
1
1
  export * from './account'
2
2
  export {
3
- AI_ERROR_STATUS,
4
- aiCatalogSchema,
5
- aiCreditBucketSchema,
6
- aiErrorCodeSchema,
7
- aiErrorSchema,
8
- aiModelSchema,
9
- aiTokenClaimsSchema,
10
- aiTokenSchema,
11
- aiUsageEntrySchema,
12
- aiUsagePageSchema,
13
- aiUsageQuerySchema,
14
- aiWalletSchema,
15
- CLOUD_AI_API_PATHS,
16
- CLOUD_AI_CONTRACT_VERSION,
17
- CLOUD_AI_JWKS_PATH,
18
- CLOUD_AI_TOKEN_AUDIENCE,
19
- cloudAIDiscoverySchema,
3
+ SERVICE_ERROR_STATUS,
4
+ serviceCatalogSchema,
5
+ creditBucketSchema,
6
+ serviceErrorCodeSchema,
7
+ serviceErrorSchema,
8
+ chatModelSchema,
9
+ servicesTokenClaimsSchema,
10
+ servicesTokenSchema,
11
+ usageEntrySchema,
12
+ usagePageSchema,
13
+ usageQuerySchema,
14
+ creditWalletSchema,
15
+ searchPricingSchema,
16
+ searchRequestSchema,
17
+ searchResultSchema,
18
+ searchResponseSchema,
19
+ MAX_SEARCH_RESULTS,
20
+ MAX_SEARCH_QUERY_LENGTH,
21
+ CLOUD_SERVICES_API_PATHS,
22
+ CLOUD_SERVICES_CONTRACT_VERSION,
23
+ CLOUD_SERVICES_JWKS_PATH,
24
+ CLOUD_SERVICES_TOKEN_AUDIENCE,
25
+ cloudServicesDiscoverySchema,
20
26
  cloudBillingDiscoverySchema,
21
- createAITokenSchema,
22
- parseAIUsageQuery,
23
- parseCreateAIToken,
24
- type AICatalog,
25
- type AICreditBucket,
26
- type AIError,
27
- type AIErrorCode,
28
- type AIModel,
29
- type AIToken,
30
- type AITokenClaims,
31
- type AIUsageEntry,
32
- type AIUsagePage,
33
- type AIUsageQuery,
34
- type AIWallet,
35
- type CloudAIDiscovery,
27
+ createServicesTokenSchema,
28
+ parseUsageQuery,
29
+ parseSearchRequest,
30
+ parseCreateServicesToken,
31
+ type ServiceCatalog,
32
+ type CreditBucket,
33
+ type ServiceError,
34
+ type ServiceErrorCode,
35
+ type ChatModel,
36
+ type ServicesToken,
37
+ type ServicesTokenClaims,
38
+ type UsageEntry,
39
+ type UsagePage,
40
+ type UsageQuery,
41
+ type CreditWallet,
42
+ type SearchPricing,
43
+ type SearchRequest,
44
+ type SearchRequestInput,
45
+ type SearchResult,
46
+ type SearchResponse,
47
+ type CloudServicesDiscovery,
36
48
  type CloudBillingDiscovery,
37
- type CreateAITokenInput
38
- } from './ai'
49
+ type CreateServicesTokenInput,
50
+ type CloudServicesAPI,
51
+ type CloudServicesSchema
52
+ } from './services'
39
53
  export * from './admin'
40
54
  export {
41
55
  cloudPresenceSchema,
@@ -55,6 +69,7 @@ export {
55
69
  cloudDeploymentSchema,
56
70
  cloudDiscoverySchema,
57
71
  cloudEditorVersionSchema,
72
+ cloudLegalDiscoverySchema,
58
73
  cloudListingSchema,
59
74
  cloudServerOrigin,
60
75
  parseCloudDiscovery,
@@ -62,11 +77,13 @@ export {
62
77
  type CloudCapabilities,
63
78
  type CloudDeployment,
64
79
  type CloudDiscovery,
80
+ type CloudLegalDiscovery,
65
81
  type CloudListing
66
82
  } from './discovery'
67
83
  export {
68
84
  CLOUD_DOCUMENT_NAME_MAX_LENGTH,
69
85
  CLOUD_IMAGE_NAME_PATTERN,
86
+ CLOUD_API_MAX_BODY_BYTES,
70
87
  CLOUD_MAX_DOCUMENT_IMAGES,
71
88
  CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,
72
89
  cloudActorSchema,
@@ -86,6 +103,9 @@ export {
86
103
  documentSummarySchema,
87
104
  sharedDocumentSchema,
88
105
  type SharedDocument,
106
+ trashSchema,
107
+ trashedDocumentSchema,
108
+ type TrashedDocument,
89
109
  workspaceUsageSchema,
90
110
  isCloudChecksum,
91
111
  parseCommitImageUploads,
@@ -129,12 +149,10 @@ export {
129
149
  documentShareSchema,
130
150
  invitationContinuationSchema,
131
151
  invitationPreviewSchema,
132
- lookupCloudUserSchema,
133
152
  parseAcceptDocumentInvitation,
134
153
  parseCreateInvitationContinuation,
135
154
  parseCreateDocumentInvitation,
136
155
  parseCreateDocumentShare,
137
- parseLookupCloudUser,
138
156
  parsePutDocumentGrant,
139
157
  parseRequestSharedImageLinks,
140
158
  parseResolveDocumentShare,
@@ -155,7 +173,6 @@ export {
155
173
  type DocumentShare,
156
174
  type InvitationContinuation,
157
175
  type InvitationPreview,
158
- type LookupCloudUserInput,
159
176
  type PutDocumentGrantInput,
160
177
  type RequestSharedImageLinksInput,
161
178
  type ResolveDocumentShareInput,
@@ -202,3 +219,12 @@ export {
202
219
  } from './links'
203
220
  export { CLOUD_PORTAL_PAGE_ROOTS, isCloudPortalPage } from './portal'
204
221
  export * from './versions'
222
+ export {
223
+ DOCUMENT_REPORT_DESCRIPTION_MAX,
224
+ documentReportReasonSchema,
225
+ fileDocumentReportResponseSchema,
226
+ fileDocumentReportSchema,
227
+ parseFileDocumentReport,
228
+ type DocumentReportReason,
229
+ type FileDocumentReportInput
230
+ } from './reports'
@@ -109,6 +109,12 @@ export const RELAY_CLOSE = {
109
109
  restored: 4410
110
110
  } as const
111
111
 
112
+ /**
113
+ * The text a peer sends to learn whether the relay still hears it, and the relay's answer. Relay
114
+ * frames are binary, so neither is taken for one, and a Durable Object answers without waking.
115
+ */
116
+ export const RELAY_HEARTBEAT = { ping: 'ping', pong: 'pong' } as const
117
+
112
118
  const CLIENT_AUTH = 0
113
119
  const CLIENT_MESSAGE = 1
114
120
  const CLIENT_FRAGMENT = 2
@@ -0,0 +1,42 @@
1
+ import * as v from 'valibot'
2
+
3
+ import { resolveDocumentShareSchema } from './sharing'
4
+
5
+ /** Why someone reports a document shared with them. */
6
+ export const documentReportReasonSchema = v.picklist([
7
+ 'spam-phishing',
8
+ 'illegal',
9
+ 'copyright',
10
+ 'harassment',
11
+ 'other'
12
+ ])
13
+ export type DocumentReportReason = v.InferOutput<typeof documentReportReasonSchema>
14
+
15
+ /** How long a report's description may be. */
16
+ export const DOCUMENT_REPORT_DESCRIPTION_MAX = 2000
17
+
18
+ /**
19
+ * A report about a document someone opened from a share link: the link's secret proves they can
20
+ * see it, as resolving the link does, and a guest names themselves as they do there.
21
+ */
22
+ export const fileDocumentReportSchema = v.object({
23
+ secret: resolveDocumentShareSchema.entries.secret,
24
+ guestId: resolveDocumentShareSchema.entries.guestId,
25
+ reason: documentReportReasonSchema,
26
+ description: v.pipe(
27
+ v.string(),
28
+ v.trim(),
29
+ v.minLength(1),
30
+ v.maxLength(DOCUMENT_REPORT_DESCRIPTION_MAX)
31
+ ),
32
+ /** Where an administrator may answer; optional, and never shown to the document's people. */
33
+ replyEmail: v.optional(v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email(), v.maxLength(254)))
34
+ })
35
+ export type FileDocumentReportInput = v.InferOutput<typeof fileDocumentReportSchema>
36
+
37
+ export function parseFileDocumentReport(input: unknown): FileDocumentReportInput {
38
+ return v.parse(fileDocumentReportSchema, input)
39
+ }
40
+
41
+ /** What filing a report answers: that it arrived, and nothing about the document. */
42
+ export const fileDocumentReportResponseSchema = v.object({ received: v.literal(true) })
@@ -0,0 +1,233 @@
1
+ import type { Hono, TypedResponse } from 'hono'
2
+ import type { BlankEnv, BlankInput, ToSchema } from 'hono/types'
3
+ import * as v from 'valibot'
4
+
5
+ /**
6
+ * The contract between editors, Cloud, and the services Cloud advertises: AI models today, and
7
+ * other paid capabilities such as image generation and search as they arrive. Cloud only
8
+ * advertises the service and signs short-lived tokens for it; the service, official or
9
+ * self-hosted, calls the providers and keeps the credit wallet. It is versioned apart from the
10
+ * Cloud protocol so a service can change without a Cloud release.
11
+ */
12
+ export const CLOUD_SERVICES_CONTRACT_VERSION = '1' as const
13
+ /** The `aud` of every token Cloud signs for its services. */
14
+ export const CLOUD_SERVICES_TOKEN_AUDIENCE = 'openpencil-services' as const
15
+ /** Where Cloud publishes the public keys a service verifies its tokens with. */
16
+ export const CLOUD_SERVICES_JWKS_PATH = '/.well-known/jwks.json' as const
17
+
18
+ /**
19
+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
20
+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
21
+ */
22
+ export const CLOUD_SERVICES_API_PATHS = {
23
+ base: '/v1',
24
+ chatCompletions: '/v1/chat/completions',
25
+ catalog: '/v1/catalog',
26
+ wallet: '/v1/wallet',
27
+ usage: '/v1/usage',
28
+ search: '/v1/search'
29
+ } as const
30
+
31
+ const urlSchema = v.pipe(v.string(), v.url())
32
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0))
33
+
34
+ export const cloudServicesDiscoverySchema = v.object({
35
+ endpoint: urlSchema,
36
+ contractVersion: v.literal(CLOUD_SERVICES_CONTRACT_VERSION)
37
+ })
38
+ export type CloudServicesDiscovery = v.InferOutput<typeof cloudServicesDiscoverySchema>
39
+
40
+ export const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema })
41
+ export type CloudBillingDiscovery = v.InferOutput<typeof cloudBillingDiscoverySchema>
42
+
43
+ export const createServicesTokenSchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) })
44
+ export type CreateServicesTokenInput = v.InferOutput<typeof createServicesTokenSchema>
45
+
46
+ export function parseCreateServicesToken(input: unknown): CreateServicesTokenInput {
47
+ return v.parse(createServicesTokenSchema, input)
48
+ }
49
+
50
+ export const servicesTokenSchema = v.object({
51
+ token: v.pipe(v.string(), v.minLength(1)),
52
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
53
+ })
54
+ export type ServicesToken = v.InferOutput<typeof servicesTokenSchema>
55
+
56
+ /** What a service may rely on once a token's signature, issuer, audience, and expiry check. */
57
+ export const servicesTokenClaimsSchema = v.object({
58
+ iss: urlSchema,
59
+ aud: v.literal(CLOUD_SERVICES_TOKEN_AUDIENCE),
60
+ sub: v.pipe(v.string(), v.minLength(1)),
61
+ workspaceId: v.pipe(v.string(), v.uuid()),
62
+ /**
63
+ * The account whose credits the request spends: the workspace's owner, whose allowance every
64
+ * workspace they own shares. Absent from tokens a Cloud from before account plans issued, which
65
+ * a relay takes as the workspace's own allowance, as such a Cloud meant.
66
+ */
67
+ accountId: v.optional(v.pipe(v.string(), v.minLength(1))),
68
+ /** Credits the owner's plan grants each month; `null` when Cloud sets no allowance. */
69
+ monthlyCreditAllowance: v.nullable(creditsSchema),
70
+ iat: v.pipe(v.number(), v.integer()),
71
+ exp: v.pipe(v.number(), v.integer())
72
+ })
73
+ export type ServicesTokenClaims = v.InferOutput<typeof servicesTokenClaimsSchema>
74
+
75
+ export const chatModelSchema = v.object({
76
+ id: v.pipe(v.string(), v.minLength(1)),
77
+ label: v.pipe(v.string(), v.minLength(1)),
78
+ /** Credits per million input and output tokens. */
79
+ creditsPerMillionInputTokens: creditsSchema,
80
+ creditsPerMillionOutputTokens: creditsSchema,
81
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
82
+ capabilities: v.object({ reasoning: v.boolean(), vision: v.boolean(), tools: v.boolean() })
83
+ })
84
+ export type ChatModel = v.InferOutput<typeof chatModelSchema>
85
+
86
+ /** What one web search costs; a service without search leaves it out of its catalog. */
87
+ export const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema })
88
+ export type SearchPricing = v.InferOutput<typeof searchPricingSchema>
89
+
90
+ export const serviceCatalogSchema = v.object({
91
+ models: v.array(chatModelSchema),
92
+ defaultModelID: v.pipe(v.string(), v.minLength(1)),
93
+ search: v.optional(searchPricingSchema)
94
+ })
95
+ export type ServiceCatalog = v.InferOutput<typeof serviceCatalogSchema>
96
+
97
+ export const creditBucketSchema = v.object({
98
+ kind: v.picklist(['allowance', 'purchased', 'grant']),
99
+ remaining: creditsSchema,
100
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
101
+ })
102
+ export type CreditBucket = v.InferOutput<typeof creditBucketSchema>
103
+
104
+ /**
105
+ * A service records a request's charge before the request's answer ends, so a wallet read after
106
+ * an answer includes what it cost.
107
+ */
108
+ export const creditWalletSchema = v.object({
109
+ /** Credits left to spend; `null` when the service sets no limit. */
110
+ balance: v.nullable(creditsSchema),
111
+ /** Spent first to last. */
112
+ buckets: v.array(creditBucketSchema)
113
+ })
114
+ export type CreditWallet = v.InferOutput<typeof creditWalletSchema>
115
+
116
+ export const usageEntrySchema = v.object({
117
+ id: v.pipe(v.string(), v.minLength(1)),
118
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
119
+ kind: v.picklist(['model', 'image', 'search']),
120
+ modelID: v.nullable(v.string()),
121
+ userId: v.pipe(v.string(), v.minLength(1)),
122
+ credits: creditsSchema
123
+ })
124
+ export type UsageEntry = v.InferOutput<typeof usageEntrySchema>
125
+
126
+ /** The most results one search returns. */
127
+ export const MAX_SEARCH_RESULTS = 10
128
+ /** The longest query a search takes, in characters. */
129
+ export const MAX_SEARCH_QUERY_LENGTH = 1_000
130
+
131
+ export const searchRequestSchema = v.object({
132
+ query: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(MAX_SEARCH_QUERY_LENGTH)),
133
+ numResults: v.optional(
134
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(MAX_SEARCH_RESULTS)),
135
+ 5
136
+ )
137
+ })
138
+ export type SearchRequestInput = v.InferInput<typeof searchRequestSchema>
139
+ export type SearchRequest = v.InferOutput<typeof searchRequestSchema>
140
+
141
+ export function parseSearchRequest(input: unknown): SearchRequest {
142
+ return v.parse(searchRequestSchema, input)
143
+ }
144
+
145
+ /** One page a search found, with the part of its text that answers the query. */
146
+ export const searchResultSchema = v.object({
147
+ // Only web pages: editors open it when clicked, so a `javascript:` URL must never pass.
148
+ url: v.pipe(urlSchema, v.regex(/^https?:\/\//i, 'A search result links to an HTTP(S) page')),
149
+ title: v.string(),
150
+ publishedAt: v.nullable(v.pipe(v.string(), v.isoTimestamp())),
151
+ author: v.nullable(v.string()),
152
+ text: v.string()
153
+ })
154
+ export type SearchResult = v.InferOutput<typeof searchResultSchema>
155
+
156
+ export const searchResponseSchema = v.object({ results: v.array(searchResultSchema) })
157
+ export type SearchResponse = v.InferOutput<typeof searchResponseSchema>
158
+
159
+ export const usageQuerySchema = v.object({
160
+ cursor: v.optional(v.pipe(v.string(), v.minLength(1)))
161
+ })
162
+ export type UsageQuery = v.InferOutput<typeof usageQuerySchema>
163
+
164
+ export function parseUsageQuery(input: unknown): UsageQuery {
165
+ return v.parse(usageQuerySchema, input)
166
+ }
167
+
168
+ export const usagePageSchema = v.object({
169
+ entries: v.array(usageEntrySchema),
170
+ next: v.nullable(v.string())
171
+ })
172
+ export type UsagePage = v.InferOutput<typeof usagePageSchema>
173
+
174
+ /** Errors a service answers with, beside the upstream provider's own. */
175
+ export const serviceErrorCodeSchema = v.picklist([
176
+ 'invalid_request',
177
+ 'unauthorized',
178
+ 'insufficient_credits',
179
+ 'model_not_allowed',
180
+ 'capability_unavailable',
181
+ 'rate_limited'
182
+ ])
183
+ export type ServiceErrorCode = v.InferOutput<typeof serviceErrorCodeSchema>
184
+
185
+ export const serviceErrorSchema = v.object({
186
+ error: v.object({
187
+ code: serviceErrorCodeSchema,
188
+ message: v.optional(v.string()),
189
+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
190
+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
191
+ })
192
+ })
193
+ export type ServiceError = v.InferOutput<typeof serviceErrorSchema>
194
+
195
+ export const SERVICE_ERROR_STATUS = {
196
+ invalid_request: 400,
197
+ unauthorized: 401,
198
+ insufficient_credits: 402,
199
+ model_not_allowed: 403,
200
+ /** A capability, such as search, the service does not offer. */
201
+ capability_unavailable: 404,
202
+ rate_limited: 429
203
+ } as const satisfies Record<ServiceErrorCode, number>
204
+
205
+ /** A route's input, and the JSON it answers with a 200. */
206
+ type JSONRoute<
207
+ Method extends string,
208
+ Path extends string,
209
+ Input extends BlankInput,
210
+ Output
211
+ > = ToSchema<Method, Path, Input, TypedResponse<Output, 200, 'json'>>
212
+
213
+ /**
214
+ * Every route a service answers besides chat completions, which OpenAI-compatible clients call
215
+ * themselves. Editors build a typed client from it with Hono's `hc`; a service's own app must
216
+ * match it, so the two cannot drift apart.
217
+ */
218
+ export type CloudServicesSchema = JSONRoute<
219
+ 'get',
220
+ typeof CLOUD_SERVICES_API_PATHS.catalog,
221
+ BlankInput,
222
+ ServiceCatalog
223
+ > &
224
+ JSONRoute<'get', typeof CLOUD_SERVICES_API_PATHS.wallet, BlankInput, CreditWallet> &
225
+ JSONRoute<'get', typeof CLOUD_SERVICES_API_PATHS.usage, { query: UsageQuery }, UsagePage> &
226
+ JSONRoute<
227
+ 'post',
228
+ typeof CLOUD_SERVICES_API_PATHS.search,
229
+ { json: SearchRequestInput },
230
+ SearchResponse
231
+ >
232
+
233
+ export type CloudServicesAPI = Hono<BlankEnv, CloudServicesSchema>
@@ -53,7 +53,10 @@ export function parseRequestSharedImageLinks(input: unknown): RequestSharedImage
53
53
 
54
54
  export const resolvedDocumentShareSchema = v.object({
55
55
  documentId: v.pipe(v.string(), v.uuid()),
56
+ /** What this person may do; a guest on an edit link may only view where guests may not edit. */
56
57
  permission: documentPermissionSchema,
58
+ /** What the link lets someone signed in to the server do. */
59
+ linkPermission: documentPermissionSchema,
57
60
  principal: collaborationPrincipalSchema,
58
61
  roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
59
62
  })
@@ -89,11 +92,6 @@ export const acceptedInvitationSchema = v.variant('kind', [
89
92
  ])
90
93
  export type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>
91
94
 
92
- export const lookupCloudUserSchema = v.object({
93
- email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email())
94
- })
95
- export type LookupCloudUserInput = v.InferOutput<typeof lookupCloudUserSchema>
96
-
97
95
  export const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })
98
96
  export type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>
99
97
 
@@ -162,10 +160,6 @@ export function parseCreateInvitationContinuation(
162
160
  return v.parse(createInvitationContinuationSchema, input)
163
161
  }
164
162
 
165
- export function parseLookupCloudUser(input: unknown): LookupCloudUserInput {
166
- return v.parse(lookupCloudUserSchema, input)
167
- }
168
-
169
163
  export function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {
170
164
  return v.parse(createDocumentShareSchema, input)
171
165
  }
@@ -5,6 +5,7 @@ import type {
5
5
  AdminEnrollmentNotificationPayload,
6
6
  AuthenticationEmailPayload,
7
7
  DocumentInvitationEmailPayload,
8
+ DocumentReportPayload,
8
9
  EmailChangeRequestedPayload,
9
10
  EnrollmentEmailPayload,
10
11
  NewSignInPayload,
@@ -74,6 +75,7 @@ type EnrollmentMessageKind = Exclude<
74
75
  | 'email-change-requested'
75
76
  | 'new-sign-in'
76
77
  | 'two-step-changed'
78
+ | 'document-report'
77
79
  >
78
80
 
79
81
  type EnrollmentCopy = {
@@ -141,6 +143,29 @@ async function renderAdminNotification(payload: AdminEnrollmentNotificationPaylo
141
143
  )
142
144
  }
143
145
 
146
+ const REPORT_REASON_LABELS: Record<string, string> = {
147
+ 'spam-phishing': 'spam or phishing',
148
+ illegal: 'illegal content',
149
+ copyright: 'copyright',
150
+ harassment: 'harassment',
151
+ other: 'something else'
152
+ }
153
+
154
+ async function renderDocumentReport(payload: DocumentReportPayload) {
155
+ const reason = REPORT_REASON_LABELS[payload.reason] ?? payload.reason
156
+ return rendered(
157
+ EnrollmentEmail,
158
+ {
159
+ heading: 'A shared document was reported',
160
+ preview: `“${payload.documentName}” was reported for ${reason}.`,
161
+ message: `Someone who opened “${payload.documentName}” from a share link reported it for ${reason}: ${payload.description}`,
162
+ actionLabel: 'Review report',
163
+ actionURL: payload.actionURL
164
+ },
165
+ 'A shared OpenPencil Cloud document was reported'
166
+ )
167
+ }
168
+
144
169
  async function renderAuthentication(
145
170
  kind: 'email-verification' | 'password-reset' | 'password-changed',
146
171
  payload: AuthenticationEmailPayload
@@ -272,5 +297,6 @@ export async function renderTransactionalEmail(
272
297
  if (content.kind === 'email-change-requested') return renderEmailChangeRequested(content.payload)
273
298
  if (content.kind === 'new-sign-in') return renderNewSignIn(content.payload)
274
299
  if (content.kind === 'two-step-changed') return renderTwoStepChanged(content.payload)
300
+ if (content.kind === 'document-report') return renderDocumentReport(content.payload)
275
301
  return renderEnrollment(content.kind, content.payload)
276
302
  }
@@ -15,6 +15,7 @@ export type TransactionalEmailKind =
15
15
  | 'email-change-requested'
16
16
  | 'new-sign-in'
17
17
  | 'two-step-changed'
18
+ | 'document-report'
18
19
 
19
20
  const documentInvitationEmailPayloadSchema = v.object({
20
21
  inviterName: v.string(),
@@ -44,6 +45,13 @@ const adminEnrollmentNotificationPayloadSchema = v.object({
44
45
  actionURL: v.string()
45
46
  })
46
47
 
48
+ const documentReportPayloadSchema = v.object({
49
+ documentName: v.string(),
50
+ reason: v.string(),
51
+ description: v.string(),
52
+ actionURL: v.string()
53
+ })
54
+
47
55
  const authenticationEmailPayloadSchema = v.object({
48
56
  name: v.string(),
49
57
  actionURL: v.optional(v.string()),
@@ -102,7 +110,8 @@ export const transactionalEmailContentSchema = v.variant('kind', [
102
110
  content('password-changed', authenticationEmailPayloadSchema),
103
111
  content('email-change-requested', emailChangeRequestedPayloadSchema),
104
112
  content('new-sign-in', newSignInPayloadSchema),
105
- content('two-step-changed', twoStepChangedPayloadSchema)
113
+ content('two-step-changed', twoStepChangedPayloadSchema),
114
+ content('document-report', documentReportPayloadSchema)
106
115
  ])
107
116
 
108
117
  /** A transactional email's kind with the payload that kind renders. */
@@ -142,3 +151,4 @@ export type RenderedTransactionalEmail = {
142
151
  html: string
143
152
  text: string
144
153
  }
154
+ export type DocumentReportPayload = v.InferOutput<typeof documentReportPayloadSchema>
@@ -4,7 +4,7 @@ import {
4
4
  Container,
5
5
  Head,
6
6
  Heading,
7
- // eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.
7
+ // eslint-disable-next-line @open-pencil/structure/no-mixed-case-acronym-identifiers -- Upstream export spelling.
8
8
  Html as HTML,
9
9
  Img,
10
10
  Link,
@@ -1,11 +1,15 @@
1
+ import { createCloudErrorReporter } from '#cloud/runtime/posthog/errors'
1
2
  import {
2
- loadAISigningKey,
3
+ createLoggingErrorReporter,
4
+ loadServicesSigningKey,
3
5
  parseCloudDeploymentTOML,
4
- type AISigningKey,
6
+ type ServicesSigningKey,
5
7
  type CloudEnvironment,
8
+ type CloudErrorReporter,
6
9
  type CloudServerConfig
7
10
  } from '#cloud/server'
8
11
 
12
+ import { writeWorkersLogLine } from './logging'
9
13
  import type { CollaborationRelayRPC } from './relay'
10
14
 
11
15
  /** The bindings `deploy/cloudflare/wrangler.jsonc` gives the Worker and its relay objects. */
@@ -25,7 +29,9 @@ export type CloudflareCloudEnvironment = CloudflareCloudBindings & Record<string
25
29
 
26
30
  export type PreparedCloudflareCloud = {
27
31
  config: CloudServerConfig
28
- aiSigningKey: AISigningKey | undefined
32
+ servicesSigningKey: ServicesSigningKey | undefined
33
+ /** Logs errors, and sends them to error tracking when the deployment configures it. */
34
+ reportError: CloudErrorReporter
29
35
  }
30
36
 
31
37
  /** The Worker's string variables and secrets, with `DATABASE_URL` from Hyperdrive. */
@@ -39,19 +45,38 @@ function configEnvironment(env: CloudflareCloudEnvironment): CloudEnvironment {
39
45
  }
40
46
 
41
47
  /**
42
- * Reads the deployment TOML once per isolate: its config and AI signing key stay the same for the
48
+ * Reads the deployment TOML once per isolate: its config and services signing key stay the same for the
43
49
  * Worker's lifetime. A failure is not kept, so the next request tries again.
44
50
  */
51
+ /** Logs errors from before a config parsed, which has no error tracking to send them to. */
52
+ const logOnly = createLoggingErrorReporter(writeWorkersLogLine)
53
+
45
54
  export function cloudflareCloudSetup(source: string) {
46
55
  let prepared: Promise<PreparedCloudflareCloud> | null = null
47
- return (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {
56
+ /** Set once an attempt's config parses, so its later setup steps that fail can be reported. */
57
+ let reportError: CloudErrorReporter | undefined
58
+ const prepare = (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {
48
59
  prepared ??= (async () => {
60
+ // An attempt whose config fails to parse has no project to report to, not an earlier one's.
61
+ reportError = undefined
49
62
  const config = parseCloudDeploymentTOML(source, configEnvironment(env))
50
- return { config, aiSigningKey: await loadAISigningKey(config) }
63
+ reportError = createLoggingErrorReporter(
64
+ writeWorkersLogLine,
65
+ createCloudErrorReporter(config, 'cloudflare')
66
+ )
67
+ return { config, servicesSigningKey: await loadServicesSigningKey(config), reportError }
51
68
  })().catch((error: unknown) => {
52
69
  prepared = null
53
70
  throw error
54
71
  })
55
72
  return prepared
56
73
  }
74
+ return {
75
+ prepare,
76
+ /**
77
+ * The reporter of the latest attempt once its config parsed, which also sends to error tracking
78
+ * when the config has it; before that, one that only logs.
79
+ */
80
+ reporter: () => reportError ?? logOnly
81
+ }
57
82
  }
@@ -1,3 +1,3 @@
1
1
  export { createCloudflareEmailTransport, type CloudflareEmailBinding } from './email'
2
2
  export type { CloudflareCloudBindings, CloudflareCloudEnvironment } from './environment'
3
- export { createCloudflareCloud } from './worker'
3
+ export { createCloudflareCloud, type CloudflareCloudOptions } from './worker'
@@ -0,0 +1,15 @@
1
+ import type { CloudLogWriter, ForwardedRequestId } from '#cloud/server'
2
+
3
+ /** Workers Logs indexes the keys of an object passed to `console`, so the line goes as one. */
4
+ export const writeWorkersLogLine: CloudLogWriter = (line) => {
5
+ console[line.level](line)
6
+ }
7
+
8
+ /** Cloudflare's ray ID, such as `8f1e2d3c4b5a6978-FRA`. */
9
+ const RAY_ID = /^[0-9a-f]{16}(-[A-Z]{3})?$/
10
+
11
+ /** Names a request by the ray ID Cloudflare's edge set on it, which a client cannot choose. */
12
+ export const cloudflareRayId: ForwardedRequestId = (headers) => {
13
+ const ray = headers.get('cf-ray')
14
+ return ray && RAY_ID.test(ray) ? ray : undefined
15
+ }