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

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 (187) hide show
  1. package/dist/client.d.ts +560 -93
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +1101 -186
  4. package/dist/client.js.map +1 -1
  5. package/dist/contract.d.ts +2 -2
  6. package/dist/contract.js +2 -2
  7. package/dist/contract2.js +390 -44
  8. package/dist/contract2.js.map +1 -1
  9. package/dist/email.d.ts +366 -3
  10. package/dist/email.d.ts.map +1 -1
  11. package/dist/email.js +1403 -556
  12. package/dist/email.js.map +1 -1
  13. package/dist/errors.js +16 -3
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +878 -37
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index2.d.ts +12 -2
  18. package/dist/index2.d.ts.map +1 -1
  19. package/dist/listen.mjs +589 -128
  20. package/dist/listen.mjs.map +1 -1
  21. package/dist/runtime-cloudflare.d.ts +4 -0
  22. package/dist/runtime-cloudflare.d.ts.map +1 -1
  23. package/dist/runtime-cloudflare.js +8689 -6324
  24. package/dist/runtime-cloudflare.js.map +1 -1
  25. package/dist/runtime-node.d.mts +10098 -5401
  26. package/dist/runtime-node.d.mts.map +1 -1
  27. package/dist/server.d.ts +14078 -7909
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +11723 -9412
  30. package/dist/server.js.map +1 -1
  31. package/dist/server.mjs +10658 -8649
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/server2.mjs +79 -57
  34. package/dist/server2.mjs.map +1 -1
  35. package/package.json +13 -4
  36. package/src/admin/api/routes.ts +263 -190
  37. package/src/admin/audit/service.ts +9 -1
  38. package/src/admin/bootstrap.ts +86 -0
  39. package/src/admin/documents/service.ts +119 -4
  40. package/src/admin/email/service.ts +2 -1
  41. package/src/admin/enrollment/email.ts +17 -3
  42. package/src/admin/enrollment/service.ts +71 -10
  43. package/src/admin/errors.ts +5 -0
  44. package/src/admin/index.ts +1 -0
  45. package/src/admin/reports/service.ts +9 -3
  46. package/src/admin/schema.ts +6 -5
  47. package/src/admin/users/service.ts +173 -16
  48. package/src/client/api.ts +29 -2
  49. package/src/client/comments.ts +205 -0
  50. package/src/client/device-authorization.ts +4 -20
  51. package/src/client/discovery.ts +4 -2
  52. package/src/client/files/archive.ts +60 -0
  53. package/src/client/files/checksum.ts +7 -0
  54. package/src/client/files/download.ts +122 -0
  55. package/src/client/files/images.ts +89 -0
  56. package/src/client/files/index.ts +15 -0
  57. package/src/client/files/objects.ts +173 -0
  58. package/src/client/files/save.ts +79 -0
  59. package/src/client/index.ts +3 -6
  60. package/src/client/portal/account.ts +20 -2
  61. package/src/client/portal/administration.ts +52 -5
  62. package/src/client/portal/request.ts +4 -2
  63. package/src/client/tour.ts +44 -0
  64. package/src/client/versions.ts +7 -1
  65. package/src/contract/account.ts +61 -11
  66. package/src/contract/admin/index.ts +48 -3
  67. package/src/contract/billing.ts +73 -4
  68. package/src/contract/comments.ts +223 -0
  69. package/src/contract/discovery.ts +47 -19
  70. package/src/contract/index.ts +10 -0
  71. package/src/contract/links.ts +5 -0
  72. package/src/contract/relay.ts +3 -1
  73. package/src/contract/services.ts +44 -4
  74. package/src/contract/workspaces.ts +5 -0
  75. package/src/email/locales/ar.json +28 -0
  76. package/src/email/locales/de.json +28 -0
  77. package/src/email/locales/es.json +28 -0
  78. package/src/email/locales/fr.json +28 -0
  79. package/src/email/locales/it.json +28 -0
  80. package/src/email/locales/ja.json +28 -0
  81. package/src/email/locales/pl.json +28 -0
  82. package/src/email/locales/pt-br.json +28 -0
  83. package/src/email/locales/ru.json +28 -0
  84. package/src/email/locales/zh-cn.json +28 -0
  85. package/src/email/messages.ts +35 -0
  86. package/src/email/render.ts +18 -0
  87. package/src/email/samples.ts +28 -1
  88. package/src/email/schema.ts +29 -3
  89. package/src/email/templates/BrandEmail.vue +3 -1
  90. package/src/email/templates/CommentNotification.vue +39 -0
  91. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  92. package/src/email/templates/TwoStepChanged.vue +17 -2
  93. package/src/email/templates/brand.ts +6 -0
  94. package/src/errors/posthog.ts +28 -4
  95. package/src/runtime/cloudflare/email.ts +2 -0
  96. package/src/runtime/cloudflare/relay/index.ts +21 -6
  97. package/src/runtime/cloudflare/worker.ts +6 -0
  98. package/src/runtime/cloudflare/xml.ts +12 -0
  99. package/src/runtime/node/admin.ts +51 -47
  100. package/src/runtime/node/email/runtime.ts +1 -0
  101. package/src/runtime/node/email/transport.ts +1 -0
  102. package/src/runtime/node/server.ts +8 -2
  103. package/src/runtime/posthog/errors.ts +3 -1
  104. package/src/server/account/actions.ts +3 -1
  105. package/src/server/account/deletion.ts +38 -4
  106. package/src/server/account/routes.ts +67 -46
  107. package/src/server/account/tokens.ts +3 -3
  108. package/src/server/api/router.ts +22 -7
  109. package/src/server/app/checks.ts +6 -1
  110. package/src/server/app/cors.ts +44 -0
  111. package/src/server/app/index.ts +76 -76
  112. package/src/server/app/routes.ts +14 -5
  113. package/src/server/app/services.ts +49 -15
  114. package/src/server/auth/access-control.ts +13 -8
  115. package/src/server/auth/account.ts +13 -12
  116. package/src/server/auth/activity.ts +7 -2
  117. package/src/server/auth/adapter.ts +16 -3
  118. package/src/server/auth/email.ts +29 -17
  119. package/src/server/auth/endpoints.ts +4 -0
  120. package/src/server/auth/factory.ts +83 -64
  121. package/src/server/auth/index.ts +1 -1
  122. package/src/server/auth/methods.ts +162 -0
  123. package/src/server/auth/mfa-assurance.ts +147 -10
  124. package/src/server/auth/rate-limit.ts +31 -0
  125. package/src/server/auth/runtime.ts +19 -5
  126. package/src/server/auth/social-providers.ts +70 -24
  127. package/src/server/billing/index.ts +2 -0
  128. package/src/server/billing/notify.ts +55 -0
  129. package/src/server/billing/seats.ts +17 -0
  130. package/src/server/billing/tokens.ts +1 -1
  131. package/src/server/cleanup/documents.ts +5 -2
  132. package/src/server/cleanup/revisions.ts +6 -3
  133. package/src/server/cleanup/uploads.ts +2 -1
  134. package/src/server/collaboration/relay/connection.ts +7 -2
  135. package/src/server/collaboration/relay/hub.ts +55 -24
  136. package/src/server/collaboration/routes.ts +8 -5
  137. package/src/server/comments/index.ts +9 -0
  138. package/src/server/comments/notify.ts +277 -0
  139. package/src/server/comments/routes.ts +352 -0
  140. package/src/server/comments/rows.ts +249 -0
  141. package/src/server/comments/service.ts +570 -0
  142. package/src/server/community/routes.ts +6 -6
  143. package/src/server/config/deployment.ts +19 -6
  144. package/src/server/config/index.ts +1 -1
  145. package/src/server/config/public.ts +19 -6
  146. package/src/server/config/schema.ts +14 -2
  147. package/src/server/config/toml/schema.ts +27 -4
  148. package/src/server/db/index.ts +2 -1
  149. package/src/server/db/migrate.ts +21 -1
  150. package/src/server/db/migrations/015_comments.ts +57 -0
  151. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  152. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  153. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  154. package/src/server/db/tables.ts +92 -2
  155. package/src/server/documents/access.ts +17 -0
  156. package/src/server/documents/images.ts +6 -1
  157. package/src/server/documents/routes.ts +12 -12
  158. package/src/server/documents/service.ts +19 -5
  159. package/src/server/documents/summary.ts +15 -0
  160. package/src/server/documents/versions/routes.ts +7 -8
  161. package/src/server/documents/versions/service.ts +5 -2
  162. package/src/server/email/service.ts +8 -2
  163. package/src/server/email/types.ts +1 -0
  164. package/src/server/errors/index.ts +48 -3
  165. package/src/server/index.ts +15 -1
  166. package/src/server/internal/routes.ts +8 -2
  167. package/src/server/internal/service.ts +10 -0
  168. package/src/server/invitations/budget.ts +3 -1
  169. package/src/server/invitations/index.ts +1 -0
  170. package/src/server/invitations/links.ts +6 -0
  171. package/src/server/pictures/service.ts +3 -1
  172. package/src/server/policy/workspace.ts +5 -2
  173. package/src/server/reports/routes.ts +2 -2
  174. package/src/server/reports/service.ts +3 -1
  175. package/src/server/services/routes.ts +2 -2
  176. package/src/server/sharing/capabilities/service.ts +1 -1
  177. package/src/server/sharing/document-routes.ts +3 -3
  178. package/src/server/sharing/invitations/service.ts +3 -4
  179. package/src/server/sharing/routes.ts +15 -15
  180. package/src/server/validation.ts +33 -25
  181. package/src/server/workspaces/members.ts +50 -12
  182. package/src/server/workspaces/repository.ts +23 -12
  183. package/src/server/workspaces/routes.ts +8 -8
  184. package/src/services/app.ts +30 -19
  185. package/src/services/config.ts +47 -8
  186. package/src/services/metering.ts +15 -27
  187. package/src/client/billing.ts +0 -80
@@ -1,11 +1,11 @@
1
1
  import {
2
- parseAcceptDocumentInvitation,
3
- parseCreateInvitationContinuation,
4
- parseCreateDocumentInvitation,
5
- parseCreateDocumentShare,
6
- parsePutDocumentGrant,
7
- parseResolveDocumentShare,
8
- parseUpdateDocumentShare
2
+ acceptDocumentInvitationSchema,
3
+ createInvitationContinuationSchema,
4
+ createDocumentInvitationSchema,
5
+ createDocumentShareSchema,
6
+ putDocumentGrantSchema,
7
+ resolveDocumentShareSchema,
8
+ updateDocumentShareSchema
9
9
  } from '#cloud/contract'
10
10
  import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'
11
11
  import type { CloudDatabase } from '#cloud/server/db'
@@ -77,7 +77,7 @@ export function createDocumentSharingRoutes(
77
77
  .post(
78
78
  '/documents/:documentId/shares',
79
79
  documentParams,
80
- validatedJSON(parseCreateDocumentShare),
80
+ validatedJSON(createDocumentShareSchema),
81
81
  (context) =>
82
82
  sharingRoute(context, async () =>
83
83
  context.json(
@@ -93,7 +93,7 @@ export function createDocumentSharingRoutes(
93
93
  .patch(
94
94
  '/documents/:documentId/shares/:shareId',
95
95
  documentShareParams,
96
- validatedJSON(parseUpdateDocumentShare),
96
+ validatedJSON(updateDocumentShareSchema),
97
97
  (context) =>
98
98
  sharingRoute(context, async () =>
99
99
  context.json({
@@ -140,7 +140,7 @@ export function createDocumentSharingRoutes(
140
140
  .put(
141
141
  '/documents/:documentId/grants/:userId',
142
142
  documentUserParams,
143
- validatedJSON(parsePutDocumentGrant),
143
+ validatedJSON(putDocumentGrantSchema),
144
144
  (context) =>
145
145
  sharingRoute(context, async () =>
146
146
  context.json({
@@ -176,7 +176,7 @@ export function createDocumentSharingRoutes(
176
176
  .post(
177
177
  '/documents/:documentId/invitations',
178
178
  documentParams,
179
- validatedJSON(parseCreateDocumentInvitation),
179
+ validatedJSON(createDocumentInvitationSchema),
180
180
  (context) =>
181
181
  sharingRoute(context, async () =>
182
182
  context.json(
@@ -192,7 +192,7 @@ export function createDocumentSharingRoutes(
192
192
  .post(
193
193
  '/invitations/:invitationId/accept',
194
194
  invitationParams,
195
- validatedJSON(parseAcceptDocumentInvitation),
195
+ validatedJSON(acceptDocumentInvitationSchema),
196
196
  (context) =>
197
197
  sharingRoute(context, async () =>
198
198
  context.json({
@@ -226,7 +226,7 @@ export function createPublicSharingRoutes(
226
226
  return new Hono()
227
227
  .post(
228
228
  '/invitations/continuations',
229
- validatedJSON(parseCreateInvitationContinuation),
229
+ validatedJSON(createInvitationContinuationSchema),
230
230
  (context) =>
231
231
  sharingRoute(context, async () =>
232
232
  context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)
@@ -245,7 +245,7 @@ export function createPublicSharingRoutes(
245
245
  .post(
246
246
  '/invitations/:invitationId/preview',
247
247
  invitationParams,
248
- validatedJSON(parseAcceptDocumentInvitation),
248
+ validatedJSON(acceptDocumentInvitationSchema),
249
249
  (context) =>
250
250
  sharingRoute(context, async () =>
251
251
  context.json({
@@ -259,7 +259,7 @@ export function createPublicSharingRoutes(
259
259
  .post(
260
260
  '/shares/:shareId/resolve',
261
261
  shareParams,
262
- validatedJSON(parseResolveDocumentShare),
262
+ validatedJSON(resolveDocumentShareSchema),
263
263
  (context) =>
264
264
  sharingRoute(context, async () =>
265
265
  context.json({
@@ -1,26 +1,24 @@
1
- import type { Context } from 'hono'
2
- import { validator } from 'hono/validator'
1
+ import { sValidator } from '@hono/standard-validator'
3
2
  import * as v from 'valibot'
4
3
 
5
- /** A request part that fails its schema is a 400, never a server error. */
6
- function parseOrReject<T>(parse: (input: unknown) => T, value: unknown, context: Context) {
7
- try {
8
- return parse(value)
9
- } catch (error) {
10
- if (error instanceof v.ValiError) {
11
- return context.json({ error: { code: 'invalid_request' as const } }, 400)
12
- }
13
- throw error
14
- }
15
- }
4
+ const invalidRequest = { error: { code: 'invalid_request' as const } }
16
5
 
17
- export function validatedJSON<T>(parse: (input: unknown) => T) {
18
- return validator('json', (value, context: Context) => parseOrReject(parse, value, context))
6
+ /**
7
+ * A JSON body through `schema`; handlers read it from `context.req.valid('json')`. A body that
8
+ * fails it is a 400, never a server error. The route's type takes what the schema accepts and
9
+ * hands handlers what it outputs, so a typed client may leave out a field with a default.
10
+ */
11
+ export function validatedJSON<Schema extends v.GenericSchema>(schema: Schema) {
12
+ return sValidator('json', schema, (result, context) =>
13
+ result.success ? undefined : context.json(invalidRequest, 400)
14
+ )
19
15
  }
20
16
 
21
17
  /** Query string counterpart of `validatedJSON`. */
22
- export function validatedQuery<T>(parse: (input: unknown) => T) {
23
- return validator('query', (value, context: Context) => parseOrReject(parse, value, context))
18
+ export function validatedQuery<Schema extends v.GenericSchema>(schema: Schema) {
19
+ return sValidator('query', schema, (result, context) =>
20
+ result.success ? undefined : context.json(invalidRequest, 400)
21
+ )
24
22
  }
25
23
 
26
24
  /**
@@ -34,13 +32,10 @@ const uuidParamSchema = v.pipe(v.string(), v.uuid(), v.toLowerCase())
34
32
  * parameter that fails it names nothing, so the route answers 404 as for a missing row, and the
35
33
  * value never reaches the database.
36
34
  */
37
- export function validatedParams<TOutput>(schema: v.GenericSchema<unknown, TOutput>) {
38
- return validator('param', (value, context: Context) => {
39
- const parsed = v.safeParse(schema, value)
40
- return parsed.success
41
- ? parsed.output
42
- : context.json({ error: { code: 'not_found' as const } }, 404)
43
- })
35
+ export function validatedParams<Schema extends v.GenericSchema>(schema: Schema) {
36
+ return sValidator('param', schema, (result, context) =>
37
+ result.success ? undefined : context.json({ error: { code: 'not_found' as const } }, 404)
38
+ )
44
39
  }
45
40
 
46
41
  /** A route parameter the server takes as text, such as a user ID, which is not a UUID column. */
@@ -50,6 +45,12 @@ export const documentParams = validatedParams(v.object({ documentId: uuidParamSc
50
45
  export const documentVersionParams = validatedParams(
51
46
  v.object({ documentId: uuidParamSchema, versionId: uuidParamSchema })
52
47
  )
48
+ export const documentThreadParams = validatedParams(
49
+ v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema })
50
+ )
51
+ export const documentCommentParams = validatedParams(
52
+ v.object({ documentId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })
53
+ )
53
54
  export const documentShareParams = validatedParams(
54
55
  v.object({ documentId: uuidParamSchema, shareId: uuidParamSchema })
55
56
  )
@@ -68,7 +69,14 @@ export const workspaceMemberParams = validatedParams(
68
69
  )
69
70
  export const accountParams = validatedParams(v.object({ userId: uuidParamSchema }))
70
71
  export const shareParams = validatedParams(v.object({ shareId: uuidParamSchema }))
71
- export const communityThumbnailParams = validatedParams(
72
+ export const shareThreadParams = validatedParams(
73
+ v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema })
74
+ )
75
+ export const shareCommentParams = validatedParams(
76
+ v.object({ shareId: uuidParamSchema, threadId: uuidParamSchema, commentId: uuidParamSchema })
77
+ )
78
+ /** A document and one of its revisions, as a thumbnail's address names them. */
79
+ export const documentRevisionParams = validatedParams(
72
80
  v.object({ documentId: uuidParamSchema, revisionId: uuidParamSchema })
73
81
  )
74
82
  export const invitationParams = validatedParams(v.object({ invitationId: uuidParamSchema }))
@@ -12,7 +12,11 @@ import type { CloudActor } from '#cloud/server/auth'
12
12
  import { workspaceRoleCan, type AccessRequest } from '#cloud/server/auth/access-control'
13
13
  import { userIdText, type CloudDatabase } from '#cloud/server/db'
14
14
  import type { TransactionalEmailService } from '#cloud/server/email/types'
15
- import { spendInvitationBudget } from '#cloud/server/invitations'
15
+ import {
16
+ INVITATION_LIFETIME_MS,
17
+ INVITATION_SECRET_BYTES,
18
+ spendInvitationBudget
19
+ } from '#cloud/server/invitations'
16
20
  import { lockStorageAllowance } from '#cloud/server/quota/storage'
17
21
  import {
18
22
  invitationMatchesActor,
@@ -22,12 +26,10 @@ import {
22
26
  import { dateString } from '#cloud/server/sharing/contracts'
23
27
  import { hashCapability } from '#cloud/server/sharing/crypto'
24
28
  import { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'
29
+ import { compact, uniq } from 'es-toolkit'
25
30
  import type { Kysely, Transaction } from 'kysely'
26
31
 
27
- import { randomHex } from '@open-pencil/scene-graph/random'
28
-
29
- const INVITATION_SECRET_BYTES = 24
30
- const INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000
32
+ import { randomHex } from '@open-pencil/std/random'
31
33
 
32
34
  /** The workspace does not exist, or the person is not a member of it. */
33
35
  export class WorkspaceNotFoundError extends Error {
@@ -83,6 +85,12 @@ export class WorkspaceInvitationInvalidError extends Error {
83
85
  export type WorkspaceMemberServiceOptions = {
84
86
  email?: TransactionalEmailService
85
87
  publicURL: string
88
+ /**
89
+ * Told, after a change commits, the accounts whose seats it may have changed: the owner of the
90
+ * workspace, and the one before when ownership passed on. Seats are the people who can edit
91
+ * across the workspaces an account owns, which billing may charge for.
92
+ */
93
+ onSeatsChanged?: (accountIds: readonly string[]) => void
86
94
  }
87
95
 
88
96
  function invitationContract(row: {
@@ -179,6 +187,25 @@ export function createWorkspaceMemberService(
179
187
  database: Kysely<CloudDatabase>,
180
188
  options: WorkspaceMemberServiceOptions
181
189
  ) {
190
+ /** The workspace's owner as `database` sees it, inside the change's transaction. */
191
+ async function ownerIn(database: WorkspaceDatabase, workspaceId: string): Promise<string | null> {
192
+ const workspace = await database
193
+ .selectFrom('workspace')
194
+ .select('ownerId')
195
+ .where('id', '=', workspaceId)
196
+ .executeTakeFirst()
197
+ return workspace?.ownerId ?? null
198
+ }
199
+
200
+ /**
201
+ * Reports the owners whose seats a committed change touched, read inside its transaction, so
202
+ * nothing after the commit can fail or see a later change.
203
+ */
204
+ function seatsChanged(owners: readonly (string | null)[]): void {
205
+ const accountIds = uniq(compact(owners))
206
+ if (accountIds.length > 0) options.onSeatsChanged?.(accountIds)
207
+ }
208
+
182
209
  async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {
183
210
  const workspace = await findWorkspace(database, userId, workspaceId)
184
211
  if (!workspace) throw new WorkspaceNotFoundError()
@@ -387,8 +414,9 @@ export function createWorkspaceMemberService(
387
414
  role: WorkspaceRole
388
415
  ): Promise<void> {
389
416
  await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
390
- await database.transaction().execute(async (transaction) => {
417
+ const owners = await database.transaction().execute(async (transaction) => {
391
418
  const member = await lockedMember(transaction, workspaceId, memberId)
419
+ const before = await ownerIn(transaction, workspaceId)
392
420
  if (member.role === 'admin' && role !== 'admin') {
393
421
  if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()
394
422
  }
@@ -399,17 +427,19 @@ export function createWorkspaceMemberService(
399
427
  .where('userId', '=', memberId)
400
428
  .execute()
401
429
  if (role !== 'admin') await handOverOwnership(transaction, workspaceId, memberId)
430
+ return [before, await ownerIn(transaction, workspaceId)]
402
431
  })
432
+ seatsChanged(owners)
403
433
  },
404
434
 
405
435
  /** Deletes an empty workspace, with its members and invitations. */
406
436
  async delete(userId: string, workspaceId: string): Promise<void> {
407
437
  await requireAccess(userId, workspaceId, { workspace: ['delete'] })
408
- await database.transaction().execute(async (transaction) => {
438
+ const owner = await database.transaction().execute(async (transaction) => {
409
439
  // Locked first, so a document created meanwhile waits and then finds no workspace.
410
- await transaction
440
+ const workspace = await transaction
411
441
  .selectFrom('workspace')
412
- .select('id')
442
+ .select('ownerId')
413
443
  .where('id', '=', workspaceId)
414
444
  .forUpdate()
415
445
  .executeTakeFirstOrThrow()
@@ -423,7 +453,9 @@ export function createWorkspaceMemberService(
423
453
  }
424
454
  if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')
425
455
  await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()
456
+ return workspace.ownerId
426
457
  })
458
+ seatsChanged([owner])
427
459
  },
428
460
 
429
461
  /**
@@ -433,8 +465,9 @@ export function createWorkspaceMemberService(
433
465
  async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {
434
466
  if (memberId === userId) await membership(userId, workspaceId)
435
467
  else await requireAccess(userId, workspaceId, { workspace: ['manage-members'] })
436
- await database.transaction().execute(async (transaction) => {
468
+ const owners = await database.transaction().execute(async (transaction) => {
437
469
  const member = await lockedMember(transaction, workspaceId, memberId)
470
+ const before = await ownerIn(transaction, workspaceId)
438
471
  if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {
439
472
  throw new WorkspaceLastAdminError()
440
473
  }
@@ -444,7 +477,9 @@ export function createWorkspaceMemberService(
444
477
  .where('userId', '=', memberId)
445
478
  .execute()
446
479
  await handOverOwnership(transaction, workspaceId, memberId)
480
+ return [before, await ownerIn(transaction, workspaceId)]
447
481
  })
482
+ seatsChanged(owners)
448
483
  },
449
484
 
450
485
  /** What a workspace invitation link offers, or null when the id is not one. */
@@ -510,7 +545,7 @@ export function createWorkspaceMemberService(
510
545
  ) {
511
546
  throw new WorkspaceInvitationInvalidError()
512
547
  }
513
- return database.transaction().execute(async (transaction) => {
548
+ const joined = await database.transaction().execute(async (transaction) => {
514
549
  await transaction
515
550
  .insertInto('workspaceMember')
516
551
  .values({
@@ -532,8 +567,11 @@ export function createWorkspaceMemberService(
532
567
  .where('workspaceId', '=', invitation.workspaceId)
533
568
  .where('userId', '=', actor.userId)
534
569
  .executeTakeFirstOrThrow()
535
- return { workspaceId: invitation.workspaceId, role: member.role }
570
+ const owner = await ownerIn(transaction, invitation.workspaceId)
571
+ return { joined: { workspaceId: invitation.workspaceId, role: member.role }, owner }
536
572
  })
573
+ seatsChanged([joined.owner])
574
+ return joined.joined
537
575
  }
538
576
  }
539
577
  }
@@ -8,6 +8,25 @@ function toISOString(value: Date | string): string {
8
8
  return value instanceof Date ? value.toISOString() : value
9
9
  }
10
10
 
11
+ function summary(
12
+ {
13
+ ownerId,
14
+ ...row
15
+ }: Omit<WorkspaceSummary, 'owner' | 'createdAt' | 'updatedAt'> & {
16
+ ownerId: string
17
+ createdAt: Date | string
18
+ updatedAt: Date | string
19
+ },
20
+ userId: string
21
+ ): WorkspaceSummary {
22
+ return {
23
+ ...row,
24
+ owner: ownerId === userId,
25
+ createdAt: toISOString(row.createdAt),
26
+ updatedAt: toISOString(row.updatedAt)
27
+ }
28
+ }
29
+
11
30
  export async function listWorkspaces(
12
31
  database: WorkspaceDatabase,
13
32
  userId: string
@@ -21,17 +40,14 @@ export async function listWorkspaces(
21
40
  'workspace.slug',
22
41
  'workspace.createdAt',
23
42
  'workspace.updatedAt',
43
+ 'workspace.ownerId',
24
44
  'workspaceMember.role'
25
45
  ])
26
46
  .where('workspaceMember.userId', '=', userId)
27
47
  .orderBy('workspace.updatedAt', 'desc')
28
48
  .execute()
29
49
 
30
- return rows.map((row) => ({
31
- ...row,
32
- createdAt: toISOString(row.createdAt),
33
- updatedAt: toISOString(row.updatedAt)
34
- }))
50
+ return rows.map((row) => summary(row, userId))
35
51
  }
36
52
 
37
53
  export async function findWorkspace(
@@ -48,18 +64,13 @@ export async function findWorkspace(
48
64
  'workspace.slug',
49
65
  'workspace.createdAt',
50
66
  'workspace.updatedAt',
67
+ 'workspace.ownerId',
51
68
  'workspaceMember.role'
52
69
  ])
53
70
  .where('workspace.id', '=', workspaceId)
54
71
  .where('workspaceMember.userId', '=', userId)
55
72
  .executeTakeFirst()
56
- return row
57
- ? {
58
- ...row,
59
- createdAt: toISOString(row.createdAt),
60
- updatedAt: toISOString(row.updatedAt)
61
- }
62
- : undefined
73
+ return row ? summary(row, userId) : undefined
63
74
  }
64
75
 
65
76
  export async function insertWorkspace(
@@ -1,8 +1,8 @@
1
1
  import {
2
- parseCreateWorkspace,
3
- parseCreateWorkspaceInvitation,
4
- parseUpdateWorkspace,
5
- parseUpdateWorkspaceMember
2
+ createWorkspaceSchema,
3
+ createWorkspaceInvitationSchema,
4
+ updateWorkspaceSchema,
5
+ updateWorkspaceMemberSchema
6
6
  } from '#cloud/contract'
7
7
  import type { CloudActor } from '#cloud/server/auth'
8
8
  import type { CloudDatabase } from '#cloud/server/db'
@@ -109,7 +109,7 @@ export function createWorkspaceRoutes(
109
109
  const workspaces = await service.list(context.get('actor').userId)
110
110
  return context.json({ workspaces })
111
111
  })
112
- .post('/', validatedJSON(parseCreateWorkspace), async (context) => {
112
+ .post('/', validatedJSON(createWorkspaceSchema), async (context) => {
113
113
  try {
114
114
  const workspace = await service.create(
115
115
  context.get('actor').userId,
@@ -131,7 +131,7 @@ export function createWorkspaceRoutes(
131
131
  if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)
132
132
  return context.json({ workspace })
133
133
  })
134
- .patch('/:workspaceId', workspaceParams, validatedJSON(parseUpdateWorkspace), (context) =>
134
+ .patch('/:workspaceId', workspaceParams, validatedJSON(updateWorkspaceSchema), (context) =>
135
135
  memberRoute(context, async () =>
136
136
  context.json({
137
137
  workspace: await members.rename(
@@ -158,7 +158,7 @@ export function createWorkspaceRoutes(
158
158
  .post(
159
159
  '/:workspaceId/invitations',
160
160
  workspaceParams,
161
- validatedJSON(parseCreateWorkspaceInvitation),
161
+ validatedJSON(createWorkspaceInvitationSchema),
162
162
  (context) =>
163
163
  memberRoute(context, async () =>
164
164
  context.json(
@@ -195,7 +195,7 @@ export function createWorkspaceRoutes(
195
195
  .patch(
196
196
  '/:workspaceId/members/:userId',
197
197
  workspaceMemberParams,
198
- validatedJSON(parseUpdateWorkspaceMember),
198
+ validatedJSON(updateWorkspaceMemberSchema),
199
199
  (context) =>
200
200
  memberRoute(context, async () => {
201
201
  await members.updateRole(
@@ -3,7 +3,7 @@ import {
3
3
  servicesTokenClaimsSchema,
4
4
  CLOUD_SERVICES_API_PATHS,
5
5
  CLOUD_SERVICES_TOKEN_AUDIENCE,
6
- parseUsageQuery,
6
+ usageQuerySchema,
7
7
  type ServiceError,
8
8
  type ServiceErrorCode,
9
9
  type ServicesTokenClaims
@@ -11,12 +11,15 @@ import {
11
11
  import { validatedQuery } from '#cloud/server/validation'
12
12
  import { pick } from 'es-toolkit'
13
13
  import { Hono, type Context } from 'hono'
14
+ import { bearerAuth } from 'hono/bearer-auth'
14
15
  import { bodyLimit } from 'hono/body-limit'
15
16
  import { cors } from 'hono/cors'
16
17
  import { jwtVerify, type JWTVerifyGetKey } from 'jose'
17
18
  import type { Kysely } from 'kysely'
18
19
  import * as v from 'valibot'
19
20
 
21
+ import { MINUTE_MS } from '@open-pencil/std/timing'
22
+
20
23
  import type { ServicesConfig } from './config'
21
24
  import type { ServicesDatabase } from './db'
22
25
  import { creditsFor, meteredUsage } from './metering'
@@ -73,7 +76,7 @@ const FORWARDED_FIELDS = [
73
76
  ] as const
74
77
 
75
78
  /** How long an upstream answer may take in all, streamed or not, so a stalled one cannot hold a request slot forever. */
76
- const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * 60_000
79
+ const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * MINUTE_MS
77
80
 
78
81
  function aiError(
79
82
  context: Context,
@@ -111,6 +114,7 @@ function concurrencyLimiter(maximum: number) {
111
114
  * OpenAI-compatible upstream with one key, and holds each workspace to its monthly allowance.
112
115
  * A request is admitted while the workspace has credits left and charged once its usage is known,
113
116
  * so concurrent requests can overdraw the allowance by what they cost.
117
+ * `/health` answers without a token, for uptime checks; it says nothing about the upstream.
114
118
  */
115
119
  export function createServicesApp(services: ServicesAppDependencies) {
116
120
  const { config } = services
@@ -124,22 +128,28 @@ export function createServicesApp(services: ServicesAppDependencies) {
124
128
  services.onBackgroundError ??
125
129
  ((error: unknown) => console.error('[Services] Metering failed:', error))
126
130
 
127
- const requireToken = async (context: Context<ServicesEnvironment>, next: () => Promise<void>) => {
128
- const header = context.req.header('Authorization')
129
- const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined
130
- if (!token) return aiError(context, 'unauthorized')
131
- try {
132
- const { payload } = await jwtVerify(token, services.keys, {
133
- issuer: config.cloudURL,
134
- audience: CLOUD_SERVICES_TOKEN_AUDIENCE,
135
- algorithms: ['ES256']
136
- })
137
- context.set('claims', v.parse(servicesTokenClaimsSchema, payload))
138
- } catch {
139
- return aiError(context, 'unauthorized')
140
- }
141
- return next()
142
- }
131
+ const unauthorized = { error: { code: 'unauthorized' as const } }
132
+ const requireToken = bearerAuth<ServicesEnvironment>({
133
+ async verifyToken(token, context) {
134
+ try {
135
+ const { payload } = await jwtVerify(token, services.keys, {
136
+ issuer: config.cloudURL,
137
+ audience: CLOUD_SERVICES_TOKEN_AUDIENCE,
138
+ algorithms: ['ES256']
139
+ })
140
+ const claims = v.safeParse(servicesTokenClaimsSchema, payload)
141
+ if (!claims.success) return false
142
+ context.set('claims', claims.output)
143
+ return true
144
+ } catch {
145
+ return false
146
+ }
147
+ },
148
+ noAuthenticationHeader: { message: unauthorized },
149
+ // A header that is not a bearer token is malformed, not a wrong token.
150
+ invalidAuthenticationHeader: { message: { error: { code: 'invalid_request' as const } } },
151
+ invalidToken: { message: unauthorized }
152
+ })
143
153
 
144
154
  return new Hono<ServicesEnvironment>()
145
155
  .use(
@@ -151,13 +161,14 @@ export function createServicesApp(services: ServicesAppDependencies) {
151
161
  maxAge: 600
152
162
  })
153
163
  )
164
+ .get('/health', (context) => context.json({ status: 'ok' as const }))
154
165
  .use(`${CLOUD_SERVICES_API_PATHS.base}/*`, requireToken)
155
166
  .get(CLOUD_SERVICES_API_PATHS.catalog, (context) => context.json(config.catalog))
156
167
  .get(CLOUD_SERVICES_API_PATHS.wallet, async (context) => {
157
168
  const claims = context.get('claims')
158
169
  return context.json(await usage.wallet(spender(claims), claims.monthlyCreditAllowance, now()))
159
170
  })
160
- .get(CLOUD_SERVICES_API_PATHS.usage, validatedQuery(parseUsageQuery), async (context) => {
171
+ .get(CLOUD_SERVICES_API_PATHS.usage, validatedQuery(usageQuerySchema), async (context) => {
161
172
  try {
162
173
  return context.json(
163
174
  await usage.page(context.get('claims').workspaceId, context.req.valid('query').cursor)
@@ -67,6 +67,20 @@ const servicesConfigSchema = v.object({
67
67
  }),
68
68
  catalog: v.object({
69
69
  default_model: textSchema,
70
+ /**
71
+ * The model for each of the editor's roles. Design left out is the default model; Review and
72
+ * Fast left out follow Design, and Vision left out does too when Design reads images.
73
+ */
74
+ // Strict, so a misspelled role fails at start instead of quietly following Design.
75
+ roles: v.optional(
76
+ v.strictObject({
77
+ design: v.optional(textSchema),
78
+ review: v.optional(textSchema),
79
+ fast: v.optional(textSchema),
80
+ vision: v.optional(textSchema)
81
+ }),
82
+ {}
83
+ ),
70
84
  models: v.pipe(v.array(modelSchema), v.minLength(1))
71
85
  })
72
86
  })
@@ -88,16 +102,41 @@ function catalogFrom(input: v.InferOutput<typeof servicesConfigSchema>['catalog'
88
102
  if (!ids.has(input.default_model)) {
89
103
  throw new ServicesConfigError(`Default model ${input.default_model} is not in the catalog`)
90
104
  }
105
+ const models = input.models.map((model) => ({
106
+ id: model.id,
107
+ label: model.label,
108
+ creditsPerMillionInputTokens: model.credits_per_million_input_tokens,
109
+ creditsPerMillionOutputTokens: model.credits_per_million_output_tokens,
110
+ contextTokens: model.context_tokens,
111
+ capabilities: { reasoning: model.reasoning, vision: model.vision, tools: model.tools }
112
+ }))
113
+ const byID = new Map(input.models.map((model) => [model.id, model]))
114
+ const role = (name: string, id: string, needs: 'tools' | 'vision' | null) => {
115
+ const model = byID.get(id)
116
+ if (!model) throw new ServicesConfigError(`The ${name} model ${id} is not in the catalog`)
117
+ if (needs && !model[needs]) {
118
+ throw new ServicesConfigError(`The ${name} model ${id} has no ${needs}`)
119
+ }
120
+ return id
121
+ }
122
+ // A catalog from before roles, whose default model can't run the chat, recommends nothing
123
+ // rather than refusing to start; roles named explicitly are always checked.
124
+ const namesRoles = Object.keys(input.roles).length > 0
125
+ if (!namesRoles && !byID.get(input.default_model)?.tools) {
126
+ return v.parse(serviceCatalogSchema, { defaultModelID: input.default_model, models })
127
+ }
128
+ const design = role('design', input.roles.design ?? input.default_model, 'tools')
129
+ // Vision falls back to the design model when it reads images, and is left out when none can.
130
+ const visionID = input.roles.vision ?? (byID.get(design)?.vision ? design : undefined) ?? null
91
131
  return v.parse(serviceCatalogSchema, {
92
132
  defaultModelID: input.default_model,
93
- models: input.models.map((model) => ({
94
- id: model.id,
95
- label: model.label,
96
- creditsPerMillionInputTokens: model.credits_per_million_input_tokens,
97
- creditsPerMillionOutputTokens: model.credits_per_million_output_tokens,
98
- contextTokens: model.context_tokens,
99
- capabilities: { reasoning: model.reasoning, vision: model.vision, tools: model.tools }
100
- }))
133
+ roleModels: {
134
+ design,
135
+ review: role('review', input.roles.review ?? design, null),
136
+ fast: role('fast', input.roles.fast ?? design, 'tools'),
137
+ vision: visionID === null ? null : role('vision', visionID, 'vision')
138
+ },
139
+ models
101
140
  })
102
141
  }
103
142