@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
@@ -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 { workspaceRoleCan, type AccessRequest } from '#cloud/server/auth/access-control'
12
13
  import 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
 
@@ -175,7 +221,7 @@ export function createWorkspaceMemberService(
175
221
  workspaceId: string,
176
222
  input: CreateWorkspaceInvitationInput
177
223
  ): Promise<CreatedWorkspaceInvitation> {
178
- const workspace = await requireAdmin(userId, workspaceId)
224
+ const workspace = await requireAccess(userId, workspaceId, { workspace: ['invite'] })
179
225
  const existing = await memberUsers(workspaceId)
180
226
  .select('workspaceMember.userId')
181
227
  .where((expression) =>
@@ -193,6 +239,7 @@ export function createWorkspaceMemberService(
193
239
  const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)
194
240
  const url = acceptanceURL(id, token)
195
241
  const row = await database.transaction().execute(async (transaction) => {
242
+ await spendInvitationBudget(transaction, { senderId: userId, email: input.email })
196
243
  await transaction
197
244
  .updateTable('workspaceInvitation')
198
245
  .set({ revokedAt: new Date() })
@@ -241,7 +288,7 @@ export function createWorkspaceMemberService(
241
288
 
242
289
  return {
243
290
  async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {
244
- await requireAdmin(userId, workspaceId)
291
+ await requireAccess(userId, workspaceId, { workspace: ['update'] })
245
292
  await database
246
293
  .updateTable('workspace')
247
294
  .set({ name, updatedAt: new Date() })
@@ -263,35 +310,34 @@ export function createWorkspaceMemberService(
263
310
  ])
264
311
  .orderBy('workspaceMember.createdAt')
265
312
  .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
- )
313
+ const invitations = workspaceRoleCan(workspace.role, { workspace: ['invite'] })
314
+ ? await database
315
+ .selectFrom('workspaceInvitation')
316
+ .leftJoin('user', (join) =>
317
+ join.on((expression) =>
318
+ expression(
319
+ expression.cast(expression.ref('user.id'), 'text'),
320
+ '=',
321
+ expression.ref('workspaceInvitation.invitedBy')
277
322
  )
278
323
  )
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
- : []
324
+ )
325
+ .select([
326
+ 'workspaceInvitation.id',
327
+ 'workspaceInvitation.emailNormalized',
328
+ 'workspaceInvitation.role',
329
+ 'workspaceInvitation.invitedAt',
330
+ 'workspaceInvitation.expiresAt',
331
+ 'workspaceInvitation.invitedBy',
332
+ 'user.name as inviterName'
333
+ ])
334
+ .where('workspaceInvitation.workspaceId', '=', workspaceId)
335
+ .where('workspaceInvitation.acceptedAt', 'is', null)
336
+ .where('workspaceInvitation.revokedAt', 'is', null)
337
+ .where('workspaceInvitation.expiresAt', '>', new Date())
338
+ .orderBy('workspaceInvitation.invitedAt')
339
+ .execute()
340
+ : []
295
341
  return {
296
342
  members: members.map((member) => ({
297
343
  userId: member.userId,
@@ -313,7 +359,7 @@ export function createWorkspaceMemberService(
313
359
  workspaceId: string,
314
360
  invitationId: string
315
361
  ): Promise<CreatedWorkspaceInvitation> {
316
- await requireAdmin(userId, workspaceId)
362
+ await requireAccess(userId, workspaceId, { workspace: ['invite'] })
317
363
  const invitation = await database
318
364
  .selectFrom('workspaceInvitation')
319
365
  .select(['emailNormalized', 'role'])
@@ -334,7 +380,7 @@ export function createWorkspaceMemberService(
334
380
  workspaceId: string,
335
381
  invitationId: string
336
382
  ): Promise<void> {
337
- await requireAdmin(userId, workspaceId)
383
+ await requireAccess(userId, workspaceId, { workspace: ['invite'] })
338
384
  const result = await database
339
385
  .updateTable('workspaceInvitation')
340
386
  .set({ revokedAt: new Date() })
@@ -352,7 +398,7 @@ export function createWorkspaceMemberService(
352
398
  memberId: string,
353
399
  role: WorkspaceRole
354
400
  ): Promise<void> {
355
- await requireAdmin(userId, workspaceId)
401
+ await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
356
402
  await database.transaction().execute(async (transaction) => {
357
403
  const member = await lockedMember(transaction, workspaceId, memberId)
358
404
  if (member.role === 'admin' && role !== 'admin') {
@@ -364,12 +410,13 @@ export function createWorkspaceMemberService(
364
410
  .where('workspaceId', '=', workspaceId)
365
411
  .where('userId', '=', memberId)
366
412
  .execute()
413
+ if (role !== 'admin') await handOverOwnership(transaction, workspaceId, memberId)
367
414
  })
368
415
  },
369
416
 
370
417
  /** Deletes an empty workspace, with its members and invitations. */
371
418
  async delete(userId: string, workspaceId: string): Promise<void> {
372
- await requireAdmin(userId, workspaceId)
419
+ await requireAccess(userId, workspaceId, { workspace: ['delete'] })
373
420
  await database.transaction().execute(async (transaction) => {
374
421
  // Locked first, so a document created meanwhile waits and then finds no workspace.
375
422
  await transaction
@@ -391,10 +438,13 @@ export function createWorkspaceMemberService(
391
438
  })
392
439
  },
393
440
 
394
- /** Removes a member, or lets someone leave; the last administrator cannot go. */
441
+ /**
442
+ * Removes a member, or lets someone leave; the last administrator cannot go, and an owner who
443
+ * goes leaves the workspace to the longest-standing other admin.
444
+ */
395
445
  async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {
396
446
  if (memberId === userId) await membership(userId, workspaceId)
397
- else await requireAdmin(userId, workspaceId)
447
+ else await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
398
448
  await database.transaction().execute(async (transaction) => {
399
449
  const member = await lockedMember(transaction, workspaceId, memberId)
400
450
  if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {
@@ -405,6 +455,7 @@ export function createWorkspaceMemberService(
405
455
  .where('workspaceId', '=', workspaceId)
406
456
  .where('userId', '=', memberId)
407
457
  .execute()
458
+ await handOverOwnership(transaction, workspaceId, memberId)
408
459
  })
409
460
  },
410
461
 
@@ -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,8 +6,19 @@ 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 { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
10
- import { validatedJSON } from '#cloud/server/validation'
9
+ import { InvitationLimitError } from '#cloud/server/invitations'
10
+ import {
11
+ CLOUD_RATE_LIMITS,
12
+ createRouteRateLimiter,
13
+ routeParamResource,
14
+ createResourceRateLimiter
15
+ } from '#cloud/server/rate-limit'
16
+ import {
17
+ validatedJSON,
18
+ workspaceInvitationParams,
19
+ workspaceMemberParams,
20
+ workspaceParams
21
+ } from '#cloud/server/validation'
11
22
  import {
12
23
  WorkspaceAlreadyMemberError,
13
24
  WorkspaceForbiddenError,
@@ -48,6 +59,9 @@ async function memberRoute<T>(context: Context, action: () => Promise<T>): Promi
48
59
  if (error instanceof WorkspaceAlreadyMemberError) {
49
60
  return context.json({ error: { code: 'already_member' as const } }, 409)
50
61
  }
62
+ if (error instanceof InvitationLimitError) {
63
+ return context.json({ error: { code: 'rate_limited' as const } }, 429)
64
+ }
51
65
  throw error
52
66
  }
53
67
  }
@@ -71,22 +85,22 @@ export function createWorkspaceRoutes(
71
85
  // Resending mails the invitation again, so it counts against the same budget as sending.
72
86
  router.use(
73
87
  '/:workspaceId/invitations/:invitationId/resend',
74
- createRouteRateLimiter(
88
+ createResourceRateLimiter(
75
89
  rateLimit.database,
76
90
  rateLimit.secret,
77
91
  CLOUD_RATE_LIMITS.invitationMutation,
78
- () => false,
79
- (context) => context.req.param('workspaceId') ?? 'unknown'
92
+ routeParamResource('workspaceId'),
93
+ () => false
80
94
  )
81
95
  )
82
96
  router.use(
83
97
  '/:workspaceId/invitations',
84
- createRouteRateLimiter(
98
+ createResourceRateLimiter(
85
99
  rateLimit.database,
86
100
  rateLimit.secret,
87
101
  CLOUD_RATE_LIMITS.invitationMutation,
88
- (context) => context.req.method !== 'POST',
89
- (context) => context.req.param('workspaceId') ?? 'unknown'
102
+ routeParamResource('workspaceId'),
103
+ (context) => context.req.method !== 'POST'
90
104
  )
91
105
  )
92
106
  }
@@ -109,88 +123,96 @@ export function createWorkspaceRoutes(
109
123
  throw error
110
124
  }
111
125
  })
112
- .get('/:workspaceId', async (context) => {
126
+ .get('/:workspaceId', workspaceParams, async (context) => {
113
127
  const workspace = await service.get(
114
128
  context.get('actor').userId,
115
- context.req.param('workspaceId')
129
+ context.req.valid('param').workspaceId
116
130
  )
117
131
  if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)
118
132
  return context.json({ workspace })
119
133
  })
120
- .patch('/:workspaceId', validatedJSON(parseUpdateWorkspace), (context) =>
134
+ .patch('/:workspaceId', workspaceParams, validatedJSON(parseUpdateWorkspace), (context) =>
121
135
  memberRoute(context, async () =>
122
136
  context.json({
123
137
  workspace: await members.rename(
124
138
  context.get('actor').userId,
125
- context.req.param('workspaceId'),
139
+ context.req.valid('param').workspaceId,
126
140
  context.req.valid('json').name
127
141
  )
128
142
  })
129
143
  )
130
144
  )
131
- .delete('/:workspaceId', (context) =>
145
+ .delete('/:workspaceId', workspaceParams, (context) =>
132
146
  memberRoute(context, async () => {
133
- await members.delete(context.get('actor').userId, context.req.param('workspaceId'))
147
+ await members.delete(context.get('actor').userId, context.req.valid('param').workspaceId)
134
148
  return context.body(null, 204)
135
149
  })
136
150
  )
137
- .get('/:workspaceId/members', (context) =>
151
+ .get('/:workspaceId/members', workspaceParams, (context) =>
138
152
  memberRoute(context, async () =>
139
153
  context.json(
140
- await members.list(context.get('actor').userId, context.req.param('workspaceId'))
154
+ await members.list(context.get('actor').userId, context.req.valid('param').workspaceId)
141
155
  )
142
156
  )
143
157
  )
144
- .post('/:workspaceId/invitations', validatedJSON(parseCreateWorkspaceInvitation), (context) =>
145
- memberRoute(context, async () =>
146
- context.json(
147
- await members.invite(
148
- context.get('actor').userId,
149
- context.req.param('workspaceId'),
150
- context.req.valid('json')
151
- ),
152
- 201
158
+ .post(
159
+ '/:workspaceId/invitations',
160
+ workspaceParams,
161
+ validatedJSON(parseCreateWorkspaceInvitation),
162
+ (context) =>
163
+ memberRoute(context, async () =>
164
+ context.json(
165
+ await members.invite(
166
+ context.get('actor').userId,
167
+ context.req.valid('param').workspaceId,
168
+ context.req.valid('json')
169
+ ),
170
+ 201
171
+ )
153
172
  )
154
- )
155
173
  )
156
- .post('/:workspaceId/invitations/:invitationId/resend', (context) =>
174
+ .post('/:workspaceId/invitations/:invitationId/resend', workspaceInvitationParams, (context) =>
157
175
  memberRoute(context, async () =>
158
176
  context.json(
159
177
  await members.resendInvitation(
160
178
  context.get('actor').userId,
161
- context.req.param('workspaceId'),
162
- context.req.param('invitationId')
179
+ context.req.valid('param').workspaceId,
180
+ context.req.valid('param').invitationId
163
181
  )
164
182
  )
165
183
  )
166
184
  )
167
- .delete('/:workspaceId/invitations/:invitationId', (context) =>
185
+ .delete('/:workspaceId/invitations/:invitationId', workspaceInvitationParams, (context) =>
168
186
  memberRoute(context, async () => {
169
187
  await members.revokeInvitation(
170
188
  context.get('actor').userId,
171
- context.req.param('workspaceId'),
172
- context.req.param('invitationId')
189
+ context.req.valid('param').workspaceId,
190
+ context.req.valid('param').invitationId
173
191
  )
174
192
  return context.body(null, 204)
175
193
  })
176
194
  )
177
- .patch('/:workspaceId/members/:userId', validatedJSON(parseUpdateWorkspaceMember), (context) =>
178
- memberRoute(context, async () => {
179
- await members.updateRole(
180
- context.get('actor').userId,
181
- context.req.param('workspaceId'),
182
- context.req.param('userId'),
183
- context.req.valid('json').role
184
- )
185
- return context.body(null, 204)
186
- })
195
+ .patch(
196
+ '/:workspaceId/members/:userId',
197
+ workspaceMemberParams,
198
+ validatedJSON(parseUpdateWorkspaceMember),
199
+ (context) =>
200
+ memberRoute(context, async () => {
201
+ await members.updateRole(
202
+ context.get('actor').userId,
203
+ context.req.valid('param').workspaceId,
204
+ context.req.valid('param').userId,
205
+ context.req.valid('json').role
206
+ )
207
+ return context.body(null, 204)
208
+ })
187
209
  )
188
- .delete('/:workspaceId/members/:userId', (context) =>
210
+ .delete('/:workspaceId/members/:userId', workspaceMemberParams, (context) =>
189
211
  memberRoute(context, async () => {
190
212
  await members.remove(
191
213
  context.get('actor').userId,
192
- context.req.param('workspaceId'),
193
- context.req.param('userId')
214
+ context.req.valid('param').workspaceId,
215
+ context.req.valid('param').userId
194
216
  )
195
217
  return context.body(null, 204)
196
218
  })
@@ -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,9 @@ export function createAIRelayApp(services: AIRelayServices) {
231
232
  await usage.record({
232
233
  id: crypto.randomUUID(),
233
234
  workspaceId: claims.workspaceId,
235
+ // A token from a Cloud without accounts names none; the row then counts for its
236
+ // workspace, and once Cloud upgrades, for that workspace's owner as well.
237
+ accountId: claims.accountId ?? null,
234
238
  userId: claims.sub,
235
239
  modelId: model.id,
236
240
  inputTokens: tokens.inputTokens,
@@ -248,4 +252,4 @@ export function createAIRelayApp(services: AIRelayServices) {
248
252
  )
249
253
  }
250
254
 
251
- export type AIRelayApp = ReturnType<typeof createAIRelayApp>
255
+ export type ServicesApp = ReturnType<typeof createServicesApp>