@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
@@ -1,6 +1,7 @@
1
1
  import type { CloudDatabase } from '#cloud/server/db'
2
- import { DocumentForbiddenError } from '#cloud/server/documents/errors'
3
- import { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'
2
+ import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'
3
+ import { CLOUD_FEATURE_KEYS, type CloudPolicy } from '#cloud/server/policy'
4
+ import { workspacePolicyContext } from '#cloud/server/policy/workspace'
4
5
  import type { Kysely } from 'kysely'
5
6
 
6
7
  export type SharingPolicyOptions = {
@@ -19,18 +20,12 @@ export function createSharingPolicy(
19
20
  ) {
20
21
  async function requireCapabilityLink(input: CapabilityLinkPolicyInput): Promise<void> {
21
22
  if (!options.policy) return
22
- const document = await database
23
- .selectFrom('document')
24
- .select('workspaceId')
25
- .where('id', '=', input.documentId)
26
- .executeTakeFirstOrThrow()
27
- const context: CloudPolicyContext = {
28
- targetingKey: document.workspaceId,
29
- actorId: input.actorId,
30
- workspaceId: document.workspaceId,
31
- documentId: input.documentId,
32
- deploymentMode: options.deploymentMode ?? 'self-hosted'
33
- }
23
+ const context = await workspacePolicyContext(
24
+ database,
25
+ { documentId: input.documentId },
26
+ { actorId: input.actorId, deploymentMode: options.deploymentMode ?? 'self-hosted' }
27
+ )
28
+ if (!context) throw new DocumentNotFoundError()
34
29
  // Whether guests may follow the link is checked when they do, so edit links still work for
35
30
  // people signed in to the server.
36
31
  if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.links, false, context))) {
@@ -2,7 +2,6 @@ import {
2
2
  parseAcceptDocumentInvitation,
3
3
  parseCreateInvitationContinuation,
4
4
  parseCreateDocumentInvitation,
5
- parseLookupCloudUser,
6
5
  parseCreateDocumentShare,
7
6
  parsePutDocumentGrant,
8
7
  parseResolveDocumentShare,
@@ -54,21 +53,6 @@ export function createDocumentSharingRoutes(
54
53
  )
55
54
  }
56
55
  return router
57
- .post(
58
- '/documents/:documentId/users/lookup',
59
- documentParams,
60
- validatedJSON(parseLookupCloudUser),
61
- (context) =>
62
- sharingRoute(context, async () =>
63
- context.json({
64
- user: await service.lookupUser(
65
- context.get('actor').userId,
66
- context.req.valid('param').documentId,
67
- context.req.valid('json')
68
- )
69
- })
70
- )
71
- )
72
56
  .get('/documents/:documentId/users/:userId', documentUserParams, (context) =>
73
57
  sharingRoute(context, async () =>
74
58
  context.json({
@@ -1,4 +1,4 @@
1
- import type { CloudUserProfile, LookupCloudUserInput } from '#cloud/contract'
1
+ import type { CloudUserProfile } from '#cloud/contract'
2
2
  import type { CloudDatabase } from '#cloud/server/db'
3
3
  import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
4
4
  import type { CloudPolicy } from '#cloud/server/policy/policy'
@@ -35,22 +35,6 @@ export function createDocumentSharingService(
35
35
  const invitations = createInvitationService(database, options)
36
36
 
37
37
  return {
38
- async lookupUser(
39
- userId: string,
40
- documentId: string,
41
- input: LookupCloudUserInput
42
- ): Promise<CloudUserProfile | null> {
43
- await requireSharingAccess(database, userId, documentId)
44
- const user = await database
45
- .selectFrom('user')
46
- .select(['id', 'name', 'email', 'image'])
47
- .where((expression) =>
48
- expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)
49
- )
50
- .executeTakeFirst()
51
- return user ?? null
52
- },
53
-
54
38
  async userProfile(
55
39
  userId: string,
56
40
  documentId: string,
@@ -66,7 +66,11 @@ export const workspaceInvitationParams = validatedParams(
66
66
  export const workspaceMemberParams = validatedParams(
67
67
  v.object({ workspaceId: uuidParamSchema, userId: textParamSchema })
68
68
  )
69
+ export const accountParams = validatedParams(v.object({ userId: uuidParamSchema }))
69
70
  export const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }))
71
+ export const communityThumbnailParams = validatedParams(
72
+ v.object({ documentId: uuidParamSchema, revisionId: uuidParamSchema })
73
+ )
70
74
  export const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }))
71
75
  export const invitationContinuationParams = validatedParams(
72
76
  v.object({ continuationId: textParamSchema })
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  createWorkspaceMemberService,
3
+ handOverOwnership,
3
4
  WorkspaceAlreadyMemberError,
4
5
  WorkspaceForbiddenError,
5
6
  WorkspaceInvitationInvalidError,
@@ -9,8 +9,11 @@ import type {
9
9
  } from '#cloud/contract'
10
10
  import { cloudInvitationURL } from '#cloud/contract'
11
11
  import type { CloudActor } from '#cloud/server/auth'
12
- import type { CloudDatabase } from '#cloud/server/db'
12
+ import { workspaceRoleCan, type AccessRequest } from '#cloud/server/auth/access-control'
13
+ import { userIdText, type CloudDatabase } from '#cloud/server/db'
13
14
  import type { TransactionalEmailService } from '#cloud/server/email/types'
15
+ import { spendInvitationBudget } from '#cloud/server/invitations'
16
+ import { lockStorageAllowance } from '#cloud/server/quota/storage'
14
17
  import {
15
18
  invitationMatchesActor,
16
19
  invitationTokenIsActive,
@@ -19,7 +22,7 @@ import {
19
22
  import { dateString } from '#cloud/server/sharing/contracts'
20
23
  import { hashCapability } from '#cloud/server/sharing/crypto'
21
24
  import { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'
22
- import type { Kysely } from 'kysely'
25
+ import type { Kysely, Transaction } from 'kysely'
23
26
 
24
27
  import { randomHex } from '@open-pencil/scene-graph/random'
25
28
 
@@ -101,6 +104,45 @@ function invitationContract(row: {
101
104
  }
102
105
  }
103
106
 
107
+ /**
108
+ * Passes the workspace to its longest-standing other admin when its owner leaves or stops being
109
+ * an admin, so its limits come from someone still running it. The last-admin guard keeps one.
110
+ */
111
+ export async function handOverOwnership(
112
+ database: Transaction<CloudDatabase>,
113
+ workspaceId: string,
114
+ leavingUserId: string
115
+ ): Promise<void> {
116
+ const workspace = await database
117
+ .selectFrom('workspace')
118
+ .select('ownerId')
119
+ .where('id', '=', workspaceId)
120
+ // Changing the owner changes no key, so a reservation's foreign-key check on this row is
121
+ // never kept waiting behind it while the transfer waits for that reservation's lock.
122
+ .forNoKeyUpdate()
123
+ .executeTakeFirstOrThrow()
124
+ if (workspace.ownerId !== leavingUserId) return
125
+ const successor = await database
126
+ .selectFrom('workspaceMember')
127
+ .select('userId')
128
+ .where('workspaceId', '=', workspaceId)
129
+ .where('role', '=', 'admin')
130
+ .where('userId', '!=', leavingUserId)
131
+ .orderBy('createdAt')
132
+ .orderBy('userId')
133
+ .executeTakeFirst()
134
+ if (!successor) return
135
+ // Reservations count this workspace under its owner's lock: hold both owners', in one order.
136
+ for (const owner of [leavingUserId, successor.userId].toSorted()) {
137
+ await lockStorageAllowance(database, owner)
138
+ }
139
+ await database
140
+ .updateTable('workspace')
141
+ .set({ ownerId: successor.userId, updatedAt: new Date() })
142
+ .where('id', '=', workspaceId)
143
+ .execute()
144
+ }
145
+
104
146
  async function adminCount(database: WorkspaceDatabase, workspaceId: string): Promise<number> {
105
147
  const rows = await database
106
148
  .selectFrom('workspaceMember')
@@ -143,9 +185,13 @@ export function createWorkspaceMemberService(
143
185
  return workspace
144
186
  }
145
187
 
146
- async function requireAdmin(userId: string, workspaceId: string): Promise<WorkspaceSummary> {
188
+ async function requireAccess(
189
+ userId: string,
190
+ workspaceId: string,
191
+ request: AccessRequest
192
+ ): Promise<WorkspaceSummary> {
147
193
  const workspace = await membership(userId, workspaceId)
148
- if (workspace.role !== 'admin') throw new WorkspaceForbiddenError()
194
+ if (!workspaceRoleCan(workspace.role, request)) throw new WorkspaceForbiddenError()
149
195
  return workspace
150
196
  }
151
197
 
@@ -153,15 +199,7 @@ export function createWorkspaceMemberService(
153
199
  function memberUsers(workspaceId: string) {
154
200
  return database
155
201
  .selectFrom('workspaceMember')
156
- .innerJoin('user', (join) =>
157
- join.on((expression) =>
158
- expression(
159
- expression.cast(expression.ref('user.id'), 'text'),
160
- '=',
161
- expression.ref('workspaceMember.userId')
162
- )
163
- )
164
- )
202
+ .innerJoin('user', (join) => join.onRef(userIdText, '=', 'workspaceMember.userId'))
165
203
  .where('workspaceMember.workspaceId', '=', workspaceId)
166
204
  }
167
205
 
@@ -175,7 +213,7 @@ export function createWorkspaceMemberService(
175
213
  workspaceId: string,
176
214
  input: CreateWorkspaceInvitationInput
177
215
  ): Promise<CreatedWorkspaceInvitation> {
178
- const workspace = await requireAdmin(userId, workspaceId)
216
+ const workspace = await requireAccess(userId, workspaceId, { workspace: ['invite'] })
179
217
  const existing = await memberUsers(workspaceId)
180
218
  .select('workspaceMember.userId')
181
219
  .where((expression) =>
@@ -185,7 +223,7 @@ export function createWorkspaceMemberService(
185
223
  if (existing) throw new WorkspaceAlreadyMemberError()
186
224
  const inviter = await database
187
225
  .selectFrom('user')
188
- .select('name')
226
+ .select(['name', 'locale'])
189
227
  .where('id', '=', userId)
190
228
  .executeTakeFirst()
191
229
  const id = crypto.randomUUID()
@@ -193,6 +231,7 @@ export function createWorkspaceMemberService(
193
231
  const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)
194
232
  const url = acceptanceURL(id, token)
195
233
  const row = await database.transaction().execute(async (transaction) => {
234
+ await spendInvitationBudget(transaction, { senderId: userId, email: input.email })
196
235
  await transaction
197
236
  .updateTable('workspaceInvitation')
198
237
  .set({ revokedAt: new Date() })
@@ -221,8 +260,10 @@ export function createWorkspaceMemberService(
221
260
  idempotencyKey: `workspace-invitation/${id}`,
222
261
  kind: 'workspace-invitation',
223
262
  recipientEmail: input.email,
263
+ // Someone without an account yet reads the inviter's language.
264
+ fallbackLocale: inviter?.locale,
224
265
  payload: {
225
- inviterName: inviter?.name ?? 'An OpenPencil user',
266
+ inviterName: inviter?.name ?? null,
226
267
  workspaceName: workspace.name,
227
268
  role: input.role,
228
269
  expiresAt: expiresAt.toISOString(),
@@ -241,7 +282,7 @@ export function createWorkspaceMemberService(
241
282
 
242
283
  return {
243
284
  async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {
244
- await requireAdmin(userId, workspaceId)
285
+ await requireAccess(userId, workspaceId, { workspace: ['update'] })
245
286
  await database
246
287
  .updateTable('workspace')
247
288
  .set({ name, updatedAt: new Date() })
@@ -263,35 +304,28 @@ export function createWorkspaceMemberService(
263
304
  ])
264
305
  .orderBy('workspaceMember.createdAt')
265
306
  .execute()
266
- const invitations =
267
- workspace.role === 'admin'
268
- ? await database
269
- .selectFrom('workspaceInvitation')
270
- .leftJoin('user', (join) =>
271
- join.on((expression) =>
272
- expression(
273
- expression.cast(expression.ref('user.id'), 'text'),
274
- '=',
275
- expression.ref('workspaceInvitation.invitedBy')
276
- )
277
- )
278
- )
279
- .select([
280
- 'workspaceInvitation.id',
281
- 'workspaceInvitation.emailNormalized',
282
- 'workspaceInvitation.role',
283
- 'workspaceInvitation.invitedAt',
284
- 'workspaceInvitation.expiresAt',
285
- 'workspaceInvitation.invitedBy',
286
- 'user.name as inviterName'
287
- ])
288
- .where('workspaceInvitation.workspaceId', '=', workspaceId)
289
- .where('workspaceInvitation.acceptedAt', 'is', null)
290
- .where('workspaceInvitation.revokedAt', 'is', null)
291
- .where('workspaceInvitation.expiresAt', '>', new Date())
292
- .orderBy('workspaceInvitation.invitedAt')
293
- .execute()
294
- : []
307
+ const invitations = workspaceRoleCan(workspace.role, { workspace: ['invite'] })
308
+ ? await database
309
+ .selectFrom('workspaceInvitation')
310
+ .leftJoin('user', (join) =>
311
+ join.onRef(userIdText, '=', 'workspaceInvitation.invitedBy')
312
+ )
313
+ .select([
314
+ 'workspaceInvitation.id',
315
+ 'workspaceInvitation.emailNormalized',
316
+ 'workspaceInvitation.role',
317
+ 'workspaceInvitation.invitedAt',
318
+ 'workspaceInvitation.expiresAt',
319
+ 'workspaceInvitation.invitedBy',
320
+ 'user.name as inviterName'
321
+ ])
322
+ .where('workspaceInvitation.workspaceId', '=', workspaceId)
323
+ .where('workspaceInvitation.acceptedAt', 'is', null)
324
+ .where('workspaceInvitation.revokedAt', 'is', null)
325
+ .where('workspaceInvitation.expiresAt', '>', new Date())
326
+ .orderBy('workspaceInvitation.invitedAt')
327
+ .execute()
328
+ : []
295
329
  return {
296
330
  members: members.map((member) => ({
297
331
  userId: member.userId,
@@ -313,7 +347,7 @@ export function createWorkspaceMemberService(
313
347
  workspaceId: string,
314
348
  invitationId: string
315
349
  ): Promise<CreatedWorkspaceInvitation> {
316
- await requireAdmin(userId, workspaceId)
350
+ await requireAccess(userId, workspaceId, { workspace: ['invite'] })
317
351
  const invitation = await database
318
352
  .selectFrom('workspaceInvitation')
319
353
  .select(['emailNormalized', 'role'])
@@ -334,7 +368,7 @@ export function createWorkspaceMemberService(
334
368
  workspaceId: string,
335
369
  invitationId: string
336
370
  ): Promise<void> {
337
- await requireAdmin(userId, workspaceId)
371
+ await requireAccess(userId, workspaceId, { workspace: ['invite'] })
338
372
  const result = await database
339
373
  .updateTable('workspaceInvitation')
340
374
  .set({ revokedAt: new Date() })
@@ -352,7 +386,7 @@ export function createWorkspaceMemberService(
352
386
  memberId: string,
353
387
  role: WorkspaceRole
354
388
  ): Promise<void> {
355
- await requireAdmin(userId, workspaceId)
389
+ await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
356
390
  await database.transaction().execute(async (transaction) => {
357
391
  const member = await lockedMember(transaction, workspaceId, memberId)
358
392
  if (member.role === 'admin' && role !== 'admin') {
@@ -364,12 +398,13 @@ export function createWorkspaceMemberService(
364
398
  .where('workspaceId', '=', workspaceId)
365
399
  .where('userId', '=', memberId)
366
400
  .execute()
401
+ if (role !== 'admin') await handOverOwnership(transaction, workspaceId, memberId)
367
402
  })
368
403
  },
369
404
 
370
405
  /** Deletes an empty workspace, with its members and invitations. */
371
406
  async delete(userId: string, workspaceId: string): Promise<void> {
372
- await requireAdmin(userId, workspaceId)
407
+ await requireAccess(userId, workspaceId, { workspace: ['delete'] })
373
408
  await database.transaction().execute(async (transaction) => {
374
409
  // Locked first, so a document created meanwhile waits and then finds no workspace.
375
410
  await transaction
@@ -391,10 +426,13 @@ export function createWorkspaceMemberService(
391
426
  })
392
427
  },
393
428
 
394
- /** Removes a member, or lets someone leave; the last administrator cannot go. */
429
+ /**
430
+ * Removes a member, or lets someone leave; the last administrator cannot go, and an owner who
431
+ * goes leaves the workspace to the longest-standing other admin.
432
+ */
395
433
  async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {
396
434
  if (memberId === userId) await membership(userId, workspaceId)
397
- else await requireAdmin(userId, workspaceId)
435
+ else await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
398
436
  await database.transaction().execute(async (transaction) => {
399
437
  const member = await lockedMember(transaction, workspaceId, memberId)
400
438
  if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {
@@ -405,6 +443,7 @@ export function createWorkspaceMemberService(
405
443
  .where('workspaceId', '=', workspaceId)
406
444
  .where('userId', '=', memberId)
407
445
  .execute()
446
+ await handOverOwnership(transaction, workspaceId, memberId)
408
447
  })
409
448
  },
410
449
 
@@ -73,7 +73,8 @@ export async function insertWorkspace(
73
73
  id: input.id,
74
74
  name: input.name,
75
75
  slug: input.slug,
76
- createdBy: actorId
76
+ createdBy: actorId,
77
+ ownerId: actorId
77
78
  })
78
79
  .onConflict((conflict) => conflict.column('slug').doNothing())
79
80
  .returning('id')
@@ -6,6 +6,7 @@ import {
6
6
  } from '#cloud/contract'
7
7
  import type { CloudActor } from '#cloud/server/auth'
8
8
  import type { CloudDatabase } from '#cloud/server/db'
9
+ import { InvitationLimitError } from '#cloud/server/invitations'
9
10
  import {
10
11
  CLOUD_RATE_LIMITS,
11
12
  createRouteRateLimiter,
@@ -58,6 +59,9 @@ async function memberRoute<T>(context: Context, action: () => Promise<T>): Promi
58
59
  if (error instanceof WorkspaceAlreadyMemberError) {
59
60
  return context.json({ error: { code: 'already_member' as const } }, 409)
60
61
  }
62
+ if (error instanceof InvitationLimitError) {
63
+ return context.json({ error: { code: 'rate_limited' as const } }, 429)
64
+ }
61
65
  throw error
62
66
  }
63
67
  }
@@ -1,12 +1,12 @@
1
1
  import {
2
- AI_ERROR_STATUS,
3
- aiTokenClaimsSchema,
4
- CLOUD_AI_API_PATHS,
5
- CLOUD_AI_TOKEN_AUDIENCE,
6
- parseAIUsageQuery,
7
- type AIError,
8
- type AIErrorCode,
9
- type AITokenClaims
2
+ SERVICE_ERROR_STATUS,
3
+ servicesTokenClaimsSchema,
4
+ CLOUD_SERVICES_API_PATHS,
5
+ CLOUD_SERVICES_TOKEN_AUDIENCE,
6
+ parseUsageQuery,
7
+ type ServiceError,
8
+ type ServiceErrorCode,
9
+ type ServicesTokenClaims
10
10
  } from '#cloud/contract'
11
11
  import { validatedQuery } from '#cloud/server/validation'
12
12
  import { pick } from 'es-toolkit'
@@ -17,14 +17,14 @@ import { jwtVerify, type JWTVerifyGetKey } from 'jose'
17
17
  import type { Kysely } from 'kysely'
18
18
  import * as v from 'valibot'
19
19
 
20
- import type { AIRelayConfig } from './config'
21
- import type { AIRelayDatabase } from './db'
20
+ import type { ServicesConfig } from './config'
21
+ import type { ServicesDatabase } from './db'
22
22
  import { creditsFor, meteredUsage } from './metering'
23
- import { AIUsageCursorError, createAIUsageStore } from './usage'
23
+ import { ServicesUsageCursorError, createServicesUsageStore, spender } from './usage'
24
24
 
25
- export type AIRelayServices = {
26
- config: AIRelayConfig
27
- database: Kysely<AIRelayDatabase>
25
+ export type ServicesAppDependencies = {
26
+ config: ServicesConfig
27
+ database: Kysely<ServicesDatabase>
28
28
  /** Resolves Cloud's signing keys, normally `createRemoteJWKSet` on Cloud's JWKS. */
29
29
  keys: JWTVerifyGetKey
30
30
  /** Reaches the upstream model API. */
@@ -39,7 +39,7 @@ export type AIRelayServices = {
39
39
  upstreamTimeoutMs?: number
40
40
  }
41
41
 
42
- type AIRelayEnvironment = { Variables: { claims: AITokenClaims } }
42
+ type ServicesEnvironment = { Variables: { claims: ServicesTokenClaims } }
43
43
 
44
44
  const chatRequestSchema = v.looseObject({
45
45
  model: v.pipe(v.string(), v.minLength(1)),
@@ -77,27 +77,30 @@ const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * 60_000
77
77
 
78
78
  function aiError(
79
79
  context: Context,
80
- code: AIErrorCode,
81
- details: Omit<AIError['error'], 'code'> = {}
80
+ code: ServiceErrorCode,
81
+ details: Omit<ServiceError['error'], 'code'> = {}
82
82
  ) {
83
- return context.json({ error: { code, ...details } }, AI_ERROR_STATUS[code])
83
+ return context.json({ error: { code, ...details } }, SERVICE_ERROR_STATUS[code])
84
84
  }
85
85
 
86
- /** Counts each workspace's model requests in flight, within one process. */
86
+ /**
87
+ * Counts each account's model requests in flight, within one process: its workspaces spend the
88
+ * same credits, so they share one limit.
89
+ */
87
90
  function concurrencyLimiter(maximum: number) {
88
91
  const inFlight = new Map<string, number>()
89
92
  return {
90
- acquire(workspaceId: string): (() => void) | null {
91
- const count = inFlight.get(workspaceId) ?? 0
93
+ acquire(accountId: string): (() => void) | null {
94
+ const count = inFlight.get(accountId) ?? 0
92
95
  if (count >= maximum) return null
93
- inFlight.set(workspaceId, count + 1)
96
+ inFlight.set(accountId, count + 1)
94
97
  let released = false
95
98
  return () => {
96
99
  if (released) return
97
100
  released = true
98
- const remaining = (inFlight.get(workspaceId) ?? 1) - 1
99
- if (remaining > 0) inFlight.set(workspaceId, remaining)
100
- else inFlight.delete(workspaceId)
101
+ const remaining = (inFlight.get(accountId) ?? 1) - 1
102
+ if (remaining > 0) inFlight.set(accountId, remaining)
103
+ else inFlight.delete(accountId)
101
104
  }
102
105
  }
103
106
  }
@@ -109,36 +112,36 @@ function concurrencyLimiter(maximum: number) {
109
112
  * A request is admitted while the workspace has credits left and charged once its usage is known,
110
113
  * so concurrent requests can overdraw the allowance by what they cost.
111
114
  */
112
- export function createAIRelayApp(services: AIRelayServices) {
115
+ export function createServicesApp(services: ServicesAppDependencies) {
113
116
  const { config } = services
114
117
  const upstreamFetch = services.fetch ?? ((input, init) => fetch(input, init))
115
118
  const now = services.now ?? (() => new Date())
116
- const usage = createAIUsageStore(services.database)
119
+ const usage = createServicesUsageStore(services.database)
117
120
  const models = new Map(config.catalog.models.map((model) => [model.id, model]))
118
121
  const limiter = concurrencyLimiter(config.maximumConcurrentRequests)
119
122
  const allowedOrigins = new Set(config.allowedOrigins)
120
123
  const reportBackgroundError =
121
124
  services.onBackgroundError ??
122
- ((error: unknown) => console.error('[AI relay] Metering failed:', error))
125
+ ((error: unknown) => console.error('[Services] Metering failed:', error))
123
126
 
124
- const requireToken = async (context: Context<AIRelayEnvironment>, next: () => Promise<void>) => {
127
+ const requireToken = async (context: Context<ServicesEnvironment>, next: () => Promise<void>) => {
125
128
  const header = context.req.header('Authorization')
126
129
  const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined
127
130
  if (!token) return aiError(context, 'unauthorized')
128
131
  try {
129
132
  const { payload } = await jwtVerify(token, services.keys, {
130
133
  issuer: config.cloudURL,
131
- audience: CLOUD_AI_TOKEN_AUDIENCE,
134
+ audience: CLOUD_SERVICES_TOKEN_AUDIENCE,
132
135
  algorithms: ['ES256']
133
136
  })
134
- context.set('claims', v.parse(aiTokenClaimsSchema, payload))
137
+ context.set('claims', v.parse(servicesTokenClaimsSchema, payload))
135
138
  } catch {
136
139
  return aiError(context, 'unauthorized')
137
140
  }
138
141
  return next()
139
142
  }
140
143
 
141
- return new Hono<AIRelayEnvironment>()
144
+ return new Hono<ServicesEnvironment>()
142
145
  .use(
143
146
  '*',
144
147
  cors({
@@ -148,28 +151,26 @@ export function createAIRelayApp(services: AIRelayServices) {
148
151
  maxAge: 600
149
152
  })
150
153
  )
151
- .use(`${CLOUD_AI_API_PATHS.base}/*`, requireToken)
152
- .get(CLOUD_AI_API_PATHS.catalog, (context) => context.json(config.catalog))
153
- .get(CLOUD_AI_API_PATHS.wallet, async (context) => {
154
+ .use(`${CLOUD_SERVICES_API_PATHS.base}/*`, requireToken)
155
+ .get(CLOUD_SERVICES_API_PATHS.catalog, (context) => context.json(config.catalog))
156
+ .get(CLOUD_SERVICES_API_PATHS.wallet, async (context) => {
154
157
  const claims = context.get('claims')
155
- return context.json(
156
- await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())
157
- )
158
+ return context.json(await usage.wallet(spender(claims), claims.monthlyCreditAllowance, now()))
158
159
  })
159
- .get(CLOUD_AI_API_PATHS.usage, validatedQuery(parseAIUsageQuery), async (context) => {
160
+ .get(CLOUD_SERVICES_API_PATHS.usage, validatedQuery(parseUsageQuery), async (context) => {
160
161
  try {
161
162
  return context.json(
162
163
  await usage.page(context.get('claims').workspaceId, context.req.valid('query').cursor)
163
164
  )
164
165
  } catch (error) {
165
- if (error instanceof AIUsageCursorError) {
166
+ if (error instanceof ServicesUsageCursorError) {
166
167
  return context.json({ error: { code: 'invalid_request' as const } }, 400)
167
168
  }
168
169
  throw error
169
170
  }
170
171
  })
171
172
  .post(
172
- CLOUD_AI_API_PATHS.chatCompletions,
173
+ CLOUD_SERVICES_API_PATHS.chatCompletions,
173
174
  // Counted as it streams in, so a body without Content-Length is bounded too.
174
175
  bodyLimit({
175
176
  maxSize: config.maximumRequestBytes,
@@ -183,13 +184,13 @@ export function createAIRelayApp(services: AIRelayServices) {
183
184
  const request = pick(parsed.output, FORWARDED_FIELDS)
184
185
  const model = models.get(request.model)
185
186
  if (!model) return aiError(context, 'model_not_allowed')
186
- const wallet = await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())
187
+ const wallet = await usage.wallet(spender(claims), claims.monthlyCreditAllowance, now())
187
188
  if (wallet.balance === 0) {
188
189
  return aiError(context, 'insufficient_credits', {
189
190
  resetsAt: wallet.buckets[0]?.expiresAt ?? undefined
190
191
  })
191
192
  }
192
- const release = limiter.acquire(claims.workspaceId)
193
+ const release = limiter.acquire(spender(claims).accountId)
193
194
  if (!release) return aiError(context, 'rate_limited')
194
195
 
195
196
  const streamed = request.stream === true
@@ -231,6 +232,7 @@ export function createAIRelayApp(services: AIRelayServices) {
231
232
  await usage.record({
232
233
  id: crypto.randomUUID(),
233
234
  workspaceId: claims.workspaceId,
235
+ accountId: claims.accountId,
234
236
  userId: claims.sub,
235
237
  modelId: model.id,
236
238
  inputTokens: tokens.inputTokens,
@@ -248,4 +250,4 @@ export function createAIRelayApp(services: AIRelayServices) {
248
250
  )
249
251
  }
250
252
 
251
- export type AIRelayApp = ReturnType<typeof createAIRelayApp>
253
+ export type ServicesApp = ReturnType<typeof createServicesApp>