@open-pencil/cloud 0.16.0 → 0.17.0-beta.2

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 (54) hide show
  1. package/dist/listen.mjs +236 -117
  2. package/dist/listen.mjs.map +1 -1
  3. package/dist/runtime-node.d.mts +2937 -703
  4. package/dist/runtime-node.d.mts.map +1 -1
  5. package/dist/server.d.ts +3985 -941
  6. package/dist/server.d.ts.map +1 -1
  7. package/dist/server.js +833 -376
  8. package/dist/server.js.map +1 -1
  9. package/dist/server.mjs +665 -271
  10. package/dist/server.mjs.map +1 -1
  11. package/package.json +4 -2
  12. package/src/admin/api/routes.ts +44 -33
  13. package/src/runtime/cloudflare/environment.ts +16 -2
  14. package/src/runtime/cloudflare/relay/index.ts +128 -0
  15. package/src/runtime/cloudflare/relay/sockets.ts +112 -0
  16. package/src/runtime/cloudflare/worker.ts +56 -19
  17. package/src/runtime/node/bootstrap.ts +9 -4
  18. package/src/runtime/node/server.ts +40 -8
  19. package/src/runtime/posthog/errors.ts +48 -0
  20. package/src/runtime/s3/objects.ts +26 -0
  21. package/src/runtime/site/server.ts +5 -3
  22. package/src/server/api/router.ts +3 -2
  23. package/src/server/api/types.ts +7 -0
  24. package/src/server/app.ts +4 -0
  25. package/src/server/cleanup/objects.ts +10 -2
  26. package/src/server/cleanup/revisions.ts +8 -2
  27. package/src/server/collaboration/index.ts +3 -0
  28. package/src/server/collaboration/relay/connection.ts +195 -0
  29. package/src/server/collaboration/relay/hub.ts +199 -187
  30. package/src/server/collaboration/relay/index.ts +3 -1
  31. package/src/server/collaboration/relay/log.ts +76 -0
  32. package/src/server/collaboration/relay/persistence.ts +147 -22
  33. package/src/server/collaboration/relay/resume.ts +28 -0
  34. package/src/server/collaboration/routes.ts +27 -16
  35. package/src/server/config/deployment.ts +11 -0
  36. package/src/server/config/schema.ts +24 -2
  37. package/src/server/db/migrate.ts +3 -1
  38. package/src/server/db/migrations/028_collaboration_updates.ts +84 -0
  39. package/src/server/db/tables.ts +18 -4
  40. package/src/server/documents/routes.ts +106 -80
  41. package/src/server/documents/versions/routes.ts +36 -25
  42. package/src/server/documents/versions/service.ts +9 -0
  43. package/src/server/errors/index.ts +56 -0
  44. package/src/server/index.ts +11 -0
  45. package/src/server/internal/routes.ts +3 -8
  46. package/src/server/objects/types.ts +12 -0
  47. package/src/server/pictures/routes.ts +4 -2
  48. package/src/server/rate-limit/index.ts +4 -1
  49. package/src/server/rate-limit/middleware.ts +99 -11
  50. package/src/server/sharing/document-routes.ts +30 -22
  51. package/src/server/sharing/routes.ts +122 -83
  52. package/src/server/validation.ts +58 -2
  53. package/src/server/workspaces/routes.ts +63 -45
  54. package/src/runtime/cloudflare/relay.ts +0 -136
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":["isBase64","countSchema","enrollmentStatusSchema","uuidSchema","FILTERS","searchCondition","FILTERS","FILTERS","dateString","enrollmentStatusSchema","parseTOML","invitationContract","providerPicture","toISOString","uuidSchema","DOWNLOAD_LIFETIME_MS","WRITABLE_ROLES","INVITATION_SECRET_BYTES","INVITATION_LIFETIME_MS","invitationContract","HTML","getSignedURL"],"sources":["../src/contract/account.ts","../src/contract/workspaces.ts","../src/contract/admin/index.ts","../src/contract/collaboration.ts","../src/contract/sharing.ts","../src/contract/links.ts","../src/contract/portal.ts","../src/contract/versions.ts","../src/admin/errors.ts","../src/admin/api/security.ts","../src/admin/schema.ts","../src/server/rate-limit/cleanup.ts","../src/server/rate-limit/keys.ts","../src/server/rate-limit/postgres.ts","../src/server/rate-limit/middleware.ts","../src/admin/api/routes.ts","../src/admin/list.ts","../src/admin/audit/service.ts","../src/admin/email/service.ts","../src/admin/enrollment/email.ts","../src/admin/enrollment/service.ts","../src/admin/operations/service.ts","../src/server/policy/keys.ts","../src/server/policy/static.ts","../src/server/config/deployment.ts","../src/server/config/public.ts","../src/server/auth/account.ts","../src/server/sharing/contracts.ts","../src/server/auth/endpoints.ts","../src/server/auth/user-agent.ts","../src/server/auth/activity.ts","../src/server/auth/email.ts","../src/server/auth/mfa-assurance.ts","../src/server/pictures/provider.ts","../src/server/pictures/service.ts","../src/server/pictures/routes.ts","../src/server/auth/social-providers.ts","../src/server/auth/factory.ts","../src/server/auth/runtime.ts","../src/server/auth/session.ts","../src/admin/users/service.ts","../src/server/ai/errors.ts","../src/server/ai/keys.ts","../src/server/documents/access.ts","../src/server/documents/errors.ts","../src/server/quota/storage.ts","../src/server/documents/routes.ts","../src/server/cleanup/objects.ts","../src/server/cleanup/documents.ts","../src/server/documents/images.ts","../src/server/documents/versions/history.ts","../src/server/cleanup/revisions.ts","../src/server/cleanup/uploads.ts","../src/server/cleanup/configured.ts","../src/server/worker/interval.ts","../src/server/worker/periodic.ts","../src/server/cleanup/worker.ts","../src/server/documents/summary.ts","../src/server/documents/limits.ts","../src/server/documents/repository.ts","../src/server/documents/versions/checkpoint.ts","../src/server/documents/service.ts","../src/server/ai/routes.ts","../src/server/ai/service.ts","../src/server/sharing/access.ts","../src/server/sharing/crypto.ts","../src/server/sharing/errors.ts","../src/server/policy/database.ts","../src/server/policy/entitlements.ts","../src/server/policy/provider.ts","../src/server/policy/policy.ts","../src/server/policy/configured.ts","../src/server/policy/service.ts","../src/server/sharing/policy.ts","../src/server/sharing/capabilities/service.ts","../src/server/sharing/grants/service.ts","../src/server/sharing/continuation.ts","../src/server/workspaces/repository.ts","../src/server/workspaces/members.ts","../src/server/sharing/http.ts","../src/server/sharing/actor.ts","../src/server/sharing/document-routes.ts","../src/server/sharing/invitations/service.ts","../src/server/sharing/routes.ts","../src/server/sharing/service.ts","../src/server/collaboration/routes.ts","../src/server/collaboration/service.ts","../src/server/collaboration/relay/authorize.ts","../src/server/collaboration/relay/awareness.ts","../src/server/collaboration/relay/documents.ts","../src/server/collaboration/relay/hub.ts","../src/server/collaboration/relay/persistence.ts","../src/server/documents/versions/routes.ts","../src/server/documents/versions/service.ts","../src/server/workspaces/service.ts","../src/server/workspaces/routes.ts","../src/server/api/router.ts","../src/server/account/actions.ts","../src/server/account/routes.ts","../src/server/internal/schema.ts","../src/server/internal/service.ts","../src/server/internal/routes.ts","../src/server/app.ts","../src/server/db/database.ts","../src/email/templates/brand.ts","../src/email/templates/layout.ts","../src/email/templates/document-invitation.ts","../src/email/templates/enrollment.ts","../src/email/render.ts","../src/email/schema.ts","../src/server/email/crypto.ts","../src/server/email/service.ts","../src/server/email/invitations.ts","../src/server/email/worker.ts","../src/runtime/postgres/database.ts","../src/runtime/node/config.ts","../src/runtime/node/bootstrap.ts","../src/runtime/s3/objects.ts","../src/runtime/node/email/transport.ts","../src/runtime/node/email/runtime.ts","../src/runtime/node/relay.ts","../src/runtime/site/server.ts","../src/runtime/node/site.ts","../src/runtime/node/server.ts"],"sourcesContent":["import { isValid as isBase64 } from 'js-base64'\nimport * as v from 'valibot'\n\nexport const cloudAccountStateSchema = v.picklist(['active', 'pending', 'rejected', 'revoked'])\nexport const cloudIdentitySchema = v.object({\n userId: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.string(),\n /** The account's picture, such as one a social provider gave it. */\n image: v.optional(v.nullable(v.string())),\n deploymentRole: v.optional(v.picklist(['user', 'admin']))\n})\n\nexport const cloudAccountStatusResponseSchema = v.object({\n user: cloudIdentitySchema,\n state: cloudAccountStateSchema\n})\n\nexport const cloudAuthenticationProviderSchema = v.picklist(['credential', 'google', 'apple'])\nexport const cloudAuthenticationMethodSchema = v.object({\n id: v.string(),\n provider: cloudAuthenticationProviderSchema,\n createdAt: v.string(),\n canUnlink: v.boolean()\n})\nexport const cloudAuthenticationMethodsResponseSchema = v.object({\n methods: v.array(cloudAuthenticationMethodSchema),\n availableSocialProviders: v.array(v.picklist(['google', 'apple']))\n})\nexport const cloudPasswordChangeSchema = v.object({\n currentPassword: v.string(),\n newPassword: v.string()\n})\nexport const cloudSocialLinkSchema = v.object({\n provider: v.picklist(['google', 'apple']),\n callbackURL: v.pipe(v.string(), v.url())\n})\nexport const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) })\nexport const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() })\nexport const accountSecurityErrorCodeSchema = v.picklist([\n 'current_password_invalid',\n 'password_too_short',\n 'password_too_long',\n 'last_authentication_method',\n 'session_not_fresh',\n 'authentication_method_failed',\n 'email_unchanged',\n 'email_change_unavailable',\n 'current_session',\n 'picture_invalid'\n])\nexport const accountSecurityErrorResponseSchema = v.object({\n error: v.object({ code: accountSecurityErrorCodeSchema })\n})\n\nexport const cloudMFAStatusSchema = v.object({\n required: v.boolean(),\n enabled: v.boolean(),\n totpEnabled: v.boolean(),\n assured: v.boolean(),\n totpAvailable: v.boolean(),\n passkeysAvailable: v.boolean(),\n recoveryCodesAvailable: v.boolean()\n})\nexport const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema })\nexport const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) })\nexport const cloudMFAEnableResponseSchema = v.object({\n totpURI: v.string(),\n backupCodes: v.array(v.string())\n})\nexport const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) })\nexport const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) })\nexport const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) })\nexport const cloudPasskeySchema = v.object({\n id: v.string(),\n name: v.nullish(v.string()),\n createdAt: v.string()\n})\nexport const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) })\nexport const cloudPasskeyDeleteSchema = v.object({ id: v.string() })\n\nexport function parseCloudMFAEnable(input: unknown) {\n return v.parse(cloudMFAEnableSchema, input)\n}\nexport function parseCloudMFAVerify(input: unknown) {\n return v.parse(cloudMFAVerifySchema, input)\n}\nexport function parseCloudPasskeyDelete(input: unknown) {\n return v.parse(cloudPasskeyDeleteSchema, input)\n}\nexport function parseCloudPasswordChange(input: unknown) {\n return v.parse(cloudPasswordChangeSchema, input)\n}\nexport function parseCloudSocialLink(input: unknown) {\n return v.parse(cloudSocialLinkSchema, input)\n}\nexport function parseCloudUnlinkAuthenticationMethod(input: unknown) {\n return v.parse(cloudUnlinkAuthenticationMethodSchema, input)\n}\n\nexport const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) })\n\n/** Who an account belongs to, as the portal shows it. */\nexport const cloudPersonSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n /** The address of the account's picture, which the server serves; null shows initials. */\n image: v.nullable(v.string())\n})\n/** What a person can see and change about themselves. */\nexport const cloudProfileSchema = v.object({\n ...cloudPersonSchema.entries,\n createdAt: v.string(),\n /** Whether the server can send the verification a new email address needs. */\n emailChangeAvailable: v.boolean()\n})\nexport const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema })\nexport const cloudProfileUpdateSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\n/** The largest picture an account may upload, once the page has cropped and shrunk it. */\nexport const CLOUD_PICTURE_MAX_BYTES = 256 * 1024\n/** The width and height a page shrinks a picture to before it uploads it. */\nexport const CLOUD_PICTURE_SIZE = 256\nexport const cloudPictureUploadSchema = v.object({\n /** The picture's PNG or JPEG bytes, in Base64. */\n data: v.pipe(\n v.string(),\n v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4),\n v.check((value) => isBase64(value))\n )\n})\n/** The address the account's picture is now served from. */\nexport const cloudPictureResponseSchema = v.object({ image: v.string() })\nexport const cloudEmailChangeSchema = v.object({\n newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n callbackURL: v.pipe(v.string(), v.url())\n})\n\n/** How a sign-in was made: the method it used, or the desktop app's approved code. */\nexport const cloudSignInMethodSchema = v.picklist([\n 'password',\n 'google',\n 'apple',\n 'passkey',\n 'two-step',\n 'email-link',\n 'desktop',\n 'other'\n])\nexport const cloudAccountSessionSchema = v.object({\n id: v.string(),\n /** The session this request was made with. */\n current: v.boolean(),\n method: v.nullable(cloudSignInMethodSchema),\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string(),\n lastActiveAt: v.string(),\n expiresAt: v.string()\n})\nexport const cloudAccountSessionsResponseSchema = v.object({\n sessions: v.array(cloudAccountSessionSchema)\n})\nexport const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) })\nexport const cloudSignInSchema = v.object({\n id: v.string(),\n method: cloudSignInMethodSchema,\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string()\n})\nexport const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) })\n\nexport function parseCloudProfileUpdate(input: unknown) {\n return v.parse(cloudProfileUpdateSchema, input)\n}\nexport function parseCloudPictureUpload(input: unknown) {\n return v.parse(cloudPictureUploadSchema, input)\n}\nexport function parseCloudEmailChange(input: unknown) {\n return v.parse(cloudEmailChangeSchema, input)\n}\nexport function parseCloudSessionRevoke(input: unknown) {\n return v.parse(cloudSessionRevokeSchema, input)\n}\n\nexport type AccountSecurityErrorCode = v.InferOutput<typeof accountSecurityErrorCodeSchema>\nexport type CloudAuthenticationProvider = v.InferOutput<typeof cloudAuthenticationProviderSchema>\nexport type CloudAuthenticationMethod = v.InferOutput<typeof cloudAuthenticationMethodSchema>\nexport type CloudAuthenticationMethods = v.InferOutput<\n typeof cloudAuthenticationMethodsResponseSchema\n>\n\nexport type CloudAccountStatus = v.InferOutput<typeof cloudAccountStatusResponseSchema>\nexport type CloudProfile = v.InferOutput<typeof cloudProfileSchema>\nexport type CloudSignInMethod = v.InferOutput<typeof cloudSignInMethodSchema>\nexport type CloudAccountSession = v.InferOutput<typeof cloudAccountSessionSchema>\nexport type CloudSignIn = v.InferOutput<typeof cloudSignInSchema>\n","import * as v from 'valibot'\n\nexport const workspaceRoleSchema = v.picklist(['viewer', 'editor', 'admin'])\nexport type WorkspaceRole = v.InferOutput<typeof workspaceRoleSchema>\n\nexport const workspaceSummarySchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n slug: v.string(),\n role: workspaceRoleSchema,\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type WorkspaceSummary = v.InferOutput<typeof workspaceSummarySchema>\n\nexport const createWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),\n slug: v.optional(\n v.pipe(\n v.string(),\n v.trim(),\n v.minLength(3),\n v.maxLength(63),\n v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)\n )\n )\n})\nexport type CreateWorkspaceInput = v.InferOutput<typeof createWorkspaceSchema>\n\nexport const workspaceListSchema = v.object({\n workspaces: v.array(workspaceSummarySchema)\n})\nexport type WorkspaceList = v.InferOutput<typeof workspaceListSchema>\n\nexport const updateWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\nexport type UpdateWorkspaceInput = v.InferOutput<typeof updateWorkspaceSchema>\n\n/** Someone who belongs to a workspace, and what they may do in it. */\nexport const workspaceMemberSchema = v.object({\n userId: v.string(),\n name: v.string(),\n email: v.string(),\n image: v.nullable(v.string()),\n role: workspaceRoleSchema,\n joinedAt: v.string()\n})\nexport type WorkspaceMember = v.InferOutput<typeof workspaceMemberSchema>\n\n/** An invitation to join a workspace that has not been accepted yet. */\nexport const workspaceInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n email: v.string(),\n role: workspaceRoleSchema,\n /** Who sent it; the name is null once their account is gone. */\n invitedBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n invitedAt: v.string(),\n expiresAt: v.string()\n})\nexport type WorkspaceInvitation = v.InferOutput<typeof workspaceInvitationSchema>\n\nexport const workspaceMembersSchema = v.object({\n members: v.array(workspaceMemberSchema),\n /** Only administrators see pending invitations. */\n invitations: v.array(workspaceInvitationSchema)\n})\nexport type WorkspaceMembers = v.InferOutput<typeof workspaceMembersSchema>\n\nexport const createWorkspaceInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n role: workspaceRoleSchema\n})\nexport type CreateWorkspaceInvitationInput = v.InferOutput<typeof createWorkspaceInvitationSchema>\n\n/** A new invitation and its link, for an administrator to pass on when email is off. */\nexport const createdWorkspaceInvitationSchema = v.object({\n invitation: workspaceInvitationSchema,\n acceptanceURL: v.string()\n})\nexport type CreatedWorkspaceInvitation = v.InferOutput<typeof createdWorkspaceInvitationSchema>\n\nexport const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema })\nexport type UpdateWorkspaceMemberInput = v.InferOutput<typeof updateWorkspaceMemberSchema>\n\nexport function parseCreateWorkspace(input: unknown): CreateWorkspaceInput {\n return v.parse(createWorkspaceSchema, input)\n}\n\nexport function parseUpdateWorkspace(input: unknown): UpdateWorkspaceInput {\n return v.parse(updateWorkspaceSchema, input)\n}\n\nexport function parseCreateWorkspaceInvitation(input: unknown): CreateWorkspaceInvitationInput {\n return v.parse(createWorkspaceInvitationSchema, input)\n}\n\nexport function parseUpdateWorkspaceMember(input: unknown): UpdateWorkspaceMemberInput {\n return v.parse(updateWorkspaceMemberSchema, input)\n}\n","import { zipObject } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport {\n cloudIdentitySchema,\n cloudAccountSessionSchema,\n cloudPersonSchema,\n cloudSignInSchema\n} from '../account'\nimport { workspaceRoleSchema } from '../workspaces'\n\nconst timestampSchema = v.pipe(v.string(), v.isoTimestamp())\nconst nullableTimestampSchema = v.nullable(timestampSchema)\nconst countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\n/**\n * What every admin list answers besides its rows: how many rows match the search and filter\n * across every page, and how many match the search under each filter.\n */\nfunction listTotals<const Filter extends string>(filters: readonly Filter[]) {\n return {\n total: countSchema,\n counts: v.object(\n zipObject(\n filters,\n filters.map(() => countSchema)\n )\n )\n }\n}\n\nexport const adminErrorCodeSchema = v.picklist([\n 'bad_request',\n 'unauthorized',\n 'forbidden',\n 'not_found',\n 'rate_limited',\n 'invalid_enrollment_transition',\n 'last_admin_required',\n 'self_admin_action_forbidden',\n 'email_regeneration_unavailable',\n 'mfa_required'\n])\n\nexport const adminErrorResponseSchema = v.object({\n error: v.object({ code: adminErrorCodeSchema })\n})\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentSchema = v.object({\n id: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.nullable(v.string()),\n reason: v.nullable(v.string()),\n status: enrollmentStatusSchema,\n requestedAt: timestampSchema,\n reviewedAt: nullableTimestampSchema,\n reviewedBy: v.nullable(v.string()),\n /** The reviewer's name, in lists, while the server still knows them. */\n reviewerName: v.optional(v.nullable(v.string())),\n reviewNote: v.nullable(v.string()),\n approvedUserId: v.nullable(v.string()),\n requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))\n})\n\nexport const enrollmentsResponseSchema = v.object({\n enrollments: v.array(enrollmentSchema),\n ...listTotals(enrollmentStatusSchema.options)\n})\nexport const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema })\n\nexport const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })\n\nexport const cloudAdminUserSchema = v.object({\n ...cloudPersonSchema.entries,\n role: v.optional(v.string()),\n banned: v.nullable(v.boolean()),\n banReason: v.optional(v.nullable(v.string())),\n createdAt: timestampSchema,\n /** An authenticator app or a passkey confirms this account's sign-ins. */\n twoStep: v.boolean(),\n /** When one of the account's sessions was last used, or null when none is left. */\n lastActiveAt: nullableTimestampSchema,\n workspaceCount: countSchema\n})\n\n/** Which accounts a list of people shows. */\nexport const cloudAdminUserFilterSchema = v.picklist([\n 'all',\n 'administrators',\n 'suspended',\n 'without-two-step'\n])\nexport const cloudAdminUsersResponseSchema = v.object({\n users: v.array(cloudAdminUserSchema),\n ...listTotals(cloudAdminUserFilterSchema.options)\n})\n\nexport const cloudAdminUserDetailSchema = v.object({\n user: v.object({\n ...cloudAdminUserSchema.entries,\n emailVerified: v.boolean()\n }),\n methods: v.array(v.object({ provider: v.string(), createdAt: timestampSchema })),\n authenticator: v.boolean(),\n passkeyCount: countSchema,\n sessions: v.array(cloudAccountSessionSchema),\n signIns: v.array(cloudSignInSchema),\n workspaces: v.array(\n v.object({\n id: v.string(),\n name: v.string(),\n role: workspaceRoleSchema,\n memberCount: countSchema,\n joinedAt: timestampSchema\n })\n )\n})\n\nexport const adminMutationResponseSchema = v.object({ ok: v.literal(true) })\n\nexport const transactionalEmailAdminSchema = v.object({\n id: v.string(),\n kind: v.string(),\n recipientEmailNormalized: v.pipe(v.string(), v.email()),\n status: v.string(),\n attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),\n nextAttemptAt: timestampSchema,\n transport: v.nullable(v.string()),\n transportMessageId: v.nullable(v.string()),\n lastErrorCode: v.nullable(v.string()),\n createdAt: timestampSchema,\n acceptedAt: nullableTimestampSchema,\n regeneratable: v.boolean()\n})\n/** Which messages a list of email shows, by how their delivery went. */\nexport const cloudAdminEmailFilterSchema = v.picklist(['all', 'sent', 'waiting', 'failed'])\nexport const adminEmailResponseSchema = v.object({\n messages: v.array(transactionalEmailAdminSchema),\n ...listTotals(cloudAdminEmailFilterSchema.options)\n})\n\n/** Who or what an event names; `name` is null once the server no longer knows it. */\nconst auditPartySchema = v.object({ id: v.string(), name: v.nullable(v.string()) })\n\nexport const adminAuditEventSchema = v.object({\n id: v.string(),\n actor: auditPartySchema,\n action: v.string(),\n /** What the event is about: an account, an access request, or an email. */\n subject: v.object({ ...auditPartySchema.entries, type: v.string() }),\n metadata: v.unknown(),\n createdAt: timestampSchema\n})\n/** Which events a list of activity shows, by what they are about. */\nexport const cloudAdminAuditFilterSchema = v.picklist(['all', 'accounts', 'requests', 'email'])\nexport const adminAuditResponseSchema = v.object({\n events: v.array(adminAuditEventSchema),\n ...listTotals(cloudAdminAuditFilterSchema.options)\n})\n\nexport const adminOperationsResponseSchema = v.object({\n deployment: v.picklist(['official', 'self-hosted']),\n enrollmentMode: v.picklist(['open', 'approval', 'closed']),\n emailTransport: v.picklist(['none', 'smtp', 'cloudflare']),\n pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),\n pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n accounts: countSchema,\n workspaces: countSchema,\n documents: countSchema,\n storedBytes: countSchema\n})\n\nexport type AdminErrorCode = v.InferOutput<typeof adminErrorCodeSchema>\nexport type Enrollment = v.InferOutput<typeof enrollmentSchema>\nexport type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>\nexport type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>\nexport type CloudAdminUserFilter = v.InferOutput<typeof cloudAdminUserFilterSchema>\nexport type CloudAdminEmailFilter = v.InferOutput<typeof cloudAdminEmailFilterSchema>\nexport type CloudAdminAuditFilter = v.InferOutput<typeof cloudAdminAuditFilterSchema>\nexport type EnrollmentStatus = v.InferOutput<typeof enrollmentStatusSchema>\nexport type CloudAdminUsers = v.InferOutput<typeof cloudAdminUsersResponseSchema>\nexport type CloudAdminUserDetail = v.InferOutput<typeof cloudAdminUserDetailSchema>\nexport type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>\nexport type AdminAuditEvent = v.InferOutput<typeof adminAuditEventSchema>\nexport type AdminOperations = v.InferOutput<typeof adminOperationsResponseSchema>\n","import * as v from 'valibot'\n\nimport { documentPermissionSchema } from './documents'\n\nexport const collaborationPrincipalSchema = v.variant('kind', [\n v.object({\n kind: v.literal('user'),\n userId: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email())\n }),\n v.object({\n kind: v.literal('guest'),\n guestId: v.string(),\n name: v.string()\n })\n])\nexport type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalSchema>\n\n/**\n * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so\n * other peers can trust it over what the peer says of itself.\n */\nexport const cloudPresenceSchema = v.object({\n kind: v.picklist(['user', 'guest']),\n id: v.string(),\n name: v.string(),\n permission: documentPermissionSchema\n})\nexport type CloudPresence = v.InferOutput<typeof cloudPresenceSchema>\n\nexport const collaborationTicketSchema = v.object({\n token: v.string(),\n provider: v.optional(v.picklist(['trystero', 'relay'])),\n serverURL: v.optional(v.pipe(v.string(), v.url())),\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),\n principal: collaborationPrincipalSchema,\n permission: documentPermissionSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n expiresAt: v.string(),\n serverEnforcedWrites: v.boolean()\n})\nexport type CollaborationTicket = v.InferOutput<typeof collaborationTicketSchema>\n","import * as v from 'valibot'\n\nimport { collaborationPrincipalSchema } from './collaboration'\nimport { documentPermissionSchema, requestImageLinksSchema } from './documents'\nimport { workspaceRoleSchema } from './workspaces'\n\nexport const documentShareSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n permission: documentPermissionSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string(),\n expiresAt: v.nullable(v.string()),\n revokedAt: v.nullable(v.string()),\n lastUsedAt: v.nullable(v.string())\n})\nexport type DocumentShare = v.InferOutput<typeof documentShareSchema>\n\n/** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */\nconst shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())))\n\nexport const createDocumentShareSchema = v.object({\n permission: documentPermissionSchema,\n expiresAt: shareExpirySchema\n})\nexport type CreateDocumentShareInput = v.InferOutput<typeof createDocumentShareSchema>\n\nexport const updateDocumentShareSchema = v.object({\n permission: v.optional(documentPermissionSchema),\n expiresAt: shareExpirySchema\n})\nexport type UpdateDocumentShareInput = v.InferOutput<typeof updateDocumentShareSchema>\n\nexport const resolveDocumentShareSchema = v.object({\n secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),\n guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))\n})\nexport type ResolveDocumentShareInput = v.InferOutput<typeof resolveDocumentShareSchema>\n\n/** A guest's request for the links of images a shared document's live room names. */\nexport const requestSharedImageLinksSchema = v.object({\n ...resolveDocumentShareSchema.entries,\n ...requestImageLinksSchema.entries\n})\nexport type RequestSharedImageLinksInput = v.InferOutput<typeof requestSharedImageLinksSchema>\n\nexport function parseRequestSharedImageLinks(input: unknown): RequestSharedImageLinksInput {\n return v.parse(requestSharedImageLinksSchema, input)\n}\n\nexport const resolvedDocumentShareSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n permission: documentPermissionSchema,\n principal: collaborationPrincipalSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))\n})\nexport type ResolvedDocumentShare = v.InferOutput<typeof resolvedDocumentShareSchema>\n\nexport const cloudUserProfileSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n image: v.nullable(v.pipe(v.string(), v.url()))\n})\nexport type CloudUserProfile = v.InferOutput<typeof cloudUserProfileSchema>\n\nexport const documentGrantSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n userId: v.string(),\n permission: documentPermissionSchema,\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type DocumentGrant = v.InferOutput<typeof documentGrantSchema>\n\n/** What accepting an invitation gave: access to a document, or a place in a workspace. */\nexport const acceptedInvitationSchema = v.variant('kind', [\n v.object({ kind: v.literal('document'), grant: documentGrantSchema }),\n v.object({\n kind: v.literal('workspace'),\n workspaceId: v.pipe(v.string(), v.uuid()),\n role: workspaceRoleSchema\n })\n])\nexport type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>\n\nexport const lookupCloudUserSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email())\n})\nexport type LookupCloudUserInput = v.InferOutput<typeof lookupCloudUserSchema>\n\nexport const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })\nexport type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>\n\nexport const createDocumentInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n permission: documentPermissionSchema\n})\nexport type CreateDocumentInvitationInput = v.InferOutput<typeof createDocumentInvitationSchema>\n\nexport const acceptDocumentInvitationSchema = v.object({\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type AcceptDocumentInvitationInput = v.InferOutput<typeof acceptDocumentInvitationSchema>\n\nexport const createInvitationContinuationSchema = v.object({\n invitationId: v.pipe(v.string(), v.uuid()),\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type CreateInvitationContinuationInput = v.InferOutput<\n typeof createInvitationContinuationSchema\n>\n\nexport const invitationContinuationSchema = v.object({\n id: v.pipe(v.string(), v.minLength(16), v.maxLength(128))\n})\nexport type InvitationContinuation = v.InferOutput<typeof invitationContinuationSchema>\n\nconst invitationPreviewFields = {\n inviterName: v.string(),\n expiresAt: v.string(),\n recipientHint: v.string()\n}\n\n/** What an invitation link opens: one document, or a whole workspace. */\nexport const invitationPreviewSchema = v.variant('kind', [\n v.object({\n kind: v.literal('document'),\n documentName: v.string(),\n permission: documentPermissionSchema,\n ...invitationPreviewFields\n }),\n v.object({\n kind: v.literal('workspace'),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n ...invitationPreviewFields\n })\n])\nexport type InvitationPreview = v.InferOutput<typeof invitationPreviewSchema>\n\nexport const documentInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n email: v.pipe(v.string(), v.email()),\n permission: documentPermissionSchema,\n invitedBy: v.string(),\n invitedAt: v.string(),\n expiresAt: v.string(),\n acceptedAt: v.nullable(v.string())\n})\nexport type DocumentInvitation = v.InferOutput<typeof documentInvitationSchema>\n\nexport function parseCreateInvitationContinuation(\n input: unknown\n): CreateInvitationContinuationInput {\n return v.parse(createInvitationContinuationSchema, input)\n}\n\nexport function parseLookupCloudUser(input: unknown): LookupCloudUserInput {\n return v.parse(lookupCloudUserSchema, input)\n}\n\nexport function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {\n return v.parse(createDocumentShareSchema, input)\n}\n\nexport function parseUpdateDocumentShare(input: unknown): UpdateDocumentShareInput {\n return v.parse(updateDocumentShareSchema, input)\n}\n\nexport function parseResolveDocumentShare(input: unknown): ResolveDocumentShareInput {\n return v.parse(resolveDocumentShareSchema, input)\n}\n\nexport function parsePutDocumentGrant(input: unknown): PutDocumentGrantInput {\n return v.parse(putDocumentGrantSchema, input)\n}\n\nexport function parseCreateDocumentInvitation(input: unknown): CreateDocumentInvitationInput {\n return v.parse(createDocumentInvitationSchema, input)\n}\n\nexport function parseAcceptDocumentInvitation(input: unknown): AcceptDocumentInvitationInput {\n return v.parse(acceptDocumentInvitationSchema, input)\n}\n","import { encodeParam, parseURL, withFragment, withQuery } from 'ufo'\n\n/** The two kinds of Cloud link that carry a secret: invitations and documents shared by link. */\nexport type CloudLinkKind = 'invitations' | 'share'\n\n/** Every kind of Cloud link: those that carry a secret, and a document's address for members. */\nexport type CloudLinkPathKind = CloudLinkKind | 'documents'\n\nconst CLOUD_LINK_PATH = /^\\/(invitations|share|documents)\\/([^/]+)$/\n\n/**\n * A link on the server's own editor. The server is the link's own address, so the link needs\n * nothing else to name it; a secret travels in the fragment, so it never reaches access logs or\n * `Referer` headers.\n */\nfunction serverLink(\n serverURL: string,\n path: string,\n query: Record<string, string | undefined> = {},\n secret?: string\n): string {\n const { protocol, host } = parseURL(serverURL)\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new Error('A Cloud server address must use HTTP or HTTPS')\n }\n const link = withQuery(`${protocol}//${host}${path}`, query)\n return secret ? withFragment(link, secret) : link\n}\n\n/** An invitation to a document or a workspace, `/invitations/:id#token`. */\nexport function cloudInvitationURL(serverURL: string, invitationId: string, token: string): string {\n return serverLink(serverURL, `/invitations/${encodeParam(invitationId)}`, {}, token)\n}\n\n/** A document shared by link, `/share/:id#secret`. */\nexport function cloudShareURL(serverURL: string, shareId: string, secret: string): string {\n return serverLink(serverURL, `/share/${encodeParam(shareId)}`, {}, secret)\n}\n\n/**\n * A document's address for its members, `/documents/:id`, or one of its versions with\n * `?version=…`. It carries no secret: whoever opens it signs in, and the server decides.\n */\nexport function cloudDocumentURL(\n serverURL: string,\n documentId: string,\n versionId: string | null = null\n): string {\n return serverLink(serverURL, cloudDocumentPath(documentId), {\n version: versionId ?? undefined\n })\n}\n\nexport function cloudDocumentPath(documentId: string): string {\n return `/documents/${encodeParam(documentId)}`\n}\n\n/**\n * The kind and ID of a Cloud link's path, or null for any other path. The ID is decoded; a broken\n * escape such as `%E0` is no link.\n */\nexport function parseCloudLinkPath(\n pathname: string\n): { kind: CloudLinkPathKind; id: string } | null {\n const [, kind, id] = pathname.match(CLOUD_LINK_PATH) ?? []\n if ((kind !== 'invitations' && kind !== 'share' && kind !== 'documents') || !id) return null\n try {\n return { kind, id: decodeURIComponent(id) }\n } catch {\n return null\n }\n}\n\n/**\n * The desktop app's form of a Cloud link, `openpencil://cloud?url=<link>#secret`: the web link,\n * whose address names the server, with its secret kept in the fragment.\n * `desktop/src/launch/links.rs` validates it before the editor sees it.\n */\nexport function cloudDesktopLinkURL(\n kind: CloudLinkKind,\n id: string,\n serverURL: string,\n secret: string\n): string {\n const link = serverLink(serverURL, `/${kind}/${encodeParam(id)}`)\n return withFragment(withQuery('openpencil://cloud', { url: link }), secret)\n}\n","/**\n * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for\n * visitors who are not signed in, sign-in and desktop sign-in approval, account settings, and the\n * administration console. Every runtime serves the portal's `cloud.html` at and below these\n * paths, and the editor's `index.html` at the root and at any other page the API does not answer.\n */\nexport const CLOUD_PORTAL_PAGE_ROOTS = ['/welcome', '/auth', '/account', '/admin'] as const\n\nexport function isCloudPortalPage(path: string): boolean {\n return CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`))\n}\n","import * as v from 'valibot'\n\nimport { documentDownloadSchema, documentSummarySchema } from './documents'\n\n/** How long a version's name may be; the history list shows the start of longer ones. */\nexport const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100\nexport const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1000\n\n/** A checkpoint the server kept on its own, or a version someone named. */\nexport const documentVersionKindSchema = v.picklist(['checkpoint', 'named'])\nexport type DocumentVersionKind = v.InferOutput<typeof documentVersionKindSchema>\n\nexport const documentVersionSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n revisionId: v.pipe(v.string(), v.uuid()),\n kind: documentVersionKindSchema,\n name: v.nullable(v.string()),\n description: v.nullable(v.string()),\n createdAt: v.string(),\n /** Who made the version: the author of a checkpoint's save, or who named or restored it. */\n createdBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n /** The version this one restored, while that version is still in the history. */\n restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),\n /** Whether the document holds this version now. */\n current: v.boolean()\n})\nexport type DocumentVersion = v.InferOutput<typeof documentVersionSchema>\n\nexport const documentVersionsSchema = v.object({\n versions: v.array(documentVersionSchema),\n /** Pass as `before` for the next, older page; null on the last one. */\n nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))\n})\nexport type DocumentVersions = v.InferOutput<typeof documentVersionsSchema>\n\nconst versionNameSchema = v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(DOCUMENT_VERSION_NAME_MAX_LENGTH)\n)\nconst versionDescriptionSchema = v.pipe(\n v.string(),\n v.trim(),\n v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH)\n)\n\n/** Names the document as it is now, like Save to version history. */\nexport const saveDocumentVersionSchema = v.object({\n name: versionNameSchema,\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type SaveDocumentVersionInput = v.InferOutput<typeof saveDocumentVersionSchema>\n\n/** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */\nexport const updateDocumentVersionSchema = v.object({\n name: v.nullable(versionNameSchema),\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type UpdateDocumentVersionInput = v.InferOutput<typeof updateDocumentVersionSchema>\n\nexport const duplicateDocumentVersionSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))\n})\nexport type DuplicateDocumentVersionInput = v.InferOutput<typeof duplicateDocumentVersionSchema>\n\nexport const documentVersionResponseSchema = v.object({ version: documentVersionSchema })\n/** A version with where to download it, so a link to it can show it without the history. */\nexport const documentVersionDownloadSchema = v.object({\n document: documentDownloadSchema,\n version: documentVersionSchema\n})\nexport type DocumentVersionDownload = v.InferOutput<typeof documentVersionDownloadSchema>\nexport const restoredDocumentSchema = v.object({\n document: documentSummarySchema,\n version: documentVersionSchema\n})\n\nexport function parseSaveDocumentVersion(input: unknown): SaveDocumentVersionInput {\n return v.parse(saveDocumentVersionSchema, input)\n}\nexport function parseUpdateDocumentVersion(input: unknown): UpdateDocumentVersionInput {\n return v.parse(updateDocumentVersionSchema, input)\n}\nexport function parseDuplicateDocumentVersion(input: unknown): DuplicateDocumentVersionInput {\n return v.parse(duplicateDocumentVersionSchema, input)\n}\n","export type AdminErrorCode =\n | 'invalid_enrollment_transition'\n | 'last_admin_required'\n | 'self_admin_action_forbidden'\n | 'email_regeneration_unavailable'\n | 'mfa_required'\n\nexport class AdminDomainError extends Error {\n override readonly name = 'AdminDomainError'\n constructor(\n readonly code: AdminErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n\nexport function adminErrorStatus(error: AdminDomainError): 400 | 409 {\n return error.code === 'invalid_enrollment_transition' ? 409 : 400\n}\n","import type { Context, Next } from 'hono'\n\nexport function requireTrustedMutationOrigin(trustedOrigins: ReadonlySet<string>) {\n return async (context: Context, next: Next) => {\n if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(context.req.method)) return next()\n const origin = context.req.header('origin')\n if (!origin || !trustedOrigins.has(origin)) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return next()\n }\n}\n","import * as v from 'valibot'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n/** Accounts and access requests are named by UUID; anything else names no row. */\nexport const isUUID = (value: string) => v.is(uuidSchema, value)\n\n/** The most rows one admin list request returns. */\nexport const ADMIN_LIST_MAXIMUM = 500\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentReviewSchema = v.object({\n note: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(1000)))\n})\nexport const userRoleMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n enabled: v.boolean()\n})\n\nexport const userMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))\n})\n\nexport type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>\n\nexport const parseEnrollmentReview = (input: unknown) => v.parse(enrollmentReviewSchema, input)\nexport const parseUserMutation = (input: unknown) => v.parse(userMutationSchema, input)\nexport const parseUserRoleMutation = (input: unknown) => v.parse(userRoleMutationSchema, input)\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {\n return {\n async cleanupExpired(before: Date): Promise<number> {\n const result = await database\n .deleteFrom('apiRateLimit')\n .where('windowStartedAt', '<', before)\n .executeTakeFirst()\n return Number(result.numDeletedRows)\n }\n }\n}\n\nexport type RateLimitCleanupService = ReturnType<typeof createRateLimitCleanupService>\n","import type { CloudActor } from '#cloud/server/auth'\nimport type { Context } from 'hono'\n\nexport type ClientIdentityOptions = {\n trustedHeaders: string[]\n}\n\n/**\n * The client address a trusted proxy reported. List-valued headers such as `X-Forwarded-For` carry\n * whatever the client sent followed by what each proxy appended, so only the right-most entry,\n * the one the trusted proxy wrote, identifies the client.\n */\nexport function trustedClientIP(context: Context, options: ClientIdentityOptions): string | null {\n for (const header of options.trustedHeaders) {\n const value = context.req\n .header(header)\n ?.split(',')\n .map((entry) => entry.trim())\n .findLast((entry) => entry.length > 0)\n if (value) return value\n }\n return null\n}\n\nexport const rateLimitKey = {\n email(email: string): string {\n return `email:${email.trim().toLowerCase()}`\n },\n ip(ip: string): string {\n return `ip:${ip}`\n },\n actor(actor: CloudActor): string {\n return `actor:${actor.userId}`\n },\n resource(resourceId: string, identity: string): string {\n return `resource:${resourceId}:${identity}`\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport type { ClientRateLimitInfo, Store } from 'hono-rate-limiter'\nimport type { Kysely } from 'kysely'\n\nexport class PostgresRateLimitStore implements Store {\n readonly localKeys = false\n readonly prefix: string\n private windowMs = 60_000\n\n constructor(\n private readonly database: Kysely<CloudDatabase>,\n private readonly secret: string,\n namespace: string,\n options: { windowMs?: number } = {}\n ) {\n this.prefix = `${namespace}:`\n this.windowMs = options.windowMs ?? this.windowMs\n }\n\n init(options: { windowMs: number }): void {\n this.windowMs = options.windowMs\n }\n\n private hash(key: string): string {\n return bytesToHex(sha256(utf8ToBytes(`${this.secret}:${this.prefix}:${key}`)))\n }\n\n async increment(key: string): Promise<ClientRateLimitInfo> {\n const now = new Date()\n const resetTime = new Date(\n Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs\n )\n const row = await this.database\n .insertInto('apiRateLimit')\n .values({\n keyHash: this.hash(key),\n windowStartedAt: new Date(resetTime.getTime() - this.windowMs),\n requestCount: 1,\n updatedAt: now\n })\n .onConflict((conflict) =>\n conflict.column('keyHash').doUpdateSet((expression) => ({\n requestCount: expression\n .case()\n .whenRef('apiRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')\n .then(expression('apiRateLimit.requestCount', '+', 1))\n .else(1)\n .end(),\n windowStartedAt: expression.ref('excluded.windowStartedAt'),\n updatedAt: expression.ref('excluded.updatedAt')\n }))\n )\n .returning(['requestCount', 'windowStartedAt'])\n .executeTakeFirstOrThrow()\n return {\n totalHits: Number(row.requestCount),\n resetTime: new Date(new Date(row.windowStartedAt).getTime() + this.windowMs)\n }\n }\n\n async decrement(key: string): Promise<void> {\n await this.database\n .updateTable('apiRateLimit')\n .set((expression) => ({\n requestCount: expression.fn('greatest', [\n expression('requestCount', '-', 1),\n expression.val(0)\n ])\n }))\n .where('keyHash', '=', this.hash(key))\n .execute()\n }\n\n async resetKey(key: string): Promise<void> {\n await this.database.deleteFrom('apiRateLimit').where('keyHash', '=', this.hash(key)).execute()\n }\n}\n","import type { CloudAPIEnvironment } from '#cloud/server/api/types'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Context, Env, Input } from 'hono'\nimport { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'\nimport { matchedRoutes } from 'hono/route'\nimport type { Kysely } from 'kysely'\n\nimport { trustedClientIP, type ClientIdentityOptions } from './keys'\nimport { PostgresRateLimitStore } from './postgres'\n\nexport type RateLimitPolicy = {\n namespace: string\n windowMs: number\n limit: number\n}\n\nexport const CLOUD_RATE_LIMITS = {\n publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },\n collaborationTicket: { namespace: 'collaboration-ticket', windowMs: 60_000, limit: 60 },\n invitationMutation: { namespace: 'invitation-mutation', windowMs: 60_000, limit: 30 },\n workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },\n documentCreation: { namespace: 'document-creation', windowMs: 60_000, limit: 60 },\n uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120 },\n authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },\n aiToken: { namespace: 'ai-token', windowMs: 60_000, limit: 30 },\n adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },\n adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }\n} as const satisfies Record<string, RateLimitPolicy>\n\n/**\n * The limiters routes mount for their own budget, each with which requests it counts. A general\n * limiter leaves those requests to it rather than counting them twice; the routes themselves say\n * which have one, so the general limiter never matches paths.\n */\nconst routeBudgets = new WeakMap<object, (context: Context) => boolean>()\n\n/** Whether a limiter the request's route mounts for its own budget counts this request. */\nexport function routeHasOwnBudget(context: Context): boolean {\n return matchedRoutes(context).some((route) => routeBudgets.get(route.handler)?.(context))\n}\n\nfunction ownBudget<Limiter extends object>(\n limiter: Limiter,\n skip?: (context: Context) => boolean\n): Limiter {\n routeBudgets.set(limiter, (context) => !skip?.(context))\n return limiter\n}\n\ntype RateLimitOptions<E extends Env, P extends string, I extends Input> = {\n database: Kysely<CloudDatabase>\n secret: string\n policy: RateLimitPolicy\n keyGenerator(context: Context<E, P, I>): string\n handler?: RateLimitExceededEventHandler<E, P, I>\n skip?: (context: Context<E, P, I>) => boolean\n standardHeaders?: boolean | 'draft-6' | 'draft-7'\n}\n\nexport function createCloudRateLimiter<\n E extends Env = Env,\n P extends string = string,\n I extends Input = Input\n>(options: RateLimitOptions<E, P, I>) {\n return rateLimiter<E, P, I>({\n windowMs: options.policy.windowMs,\n limit: options.policy.limit,\n standardHeaders: options.standardHeaders ?? 'draft-7',\n store: new PostgresRateLimitStore(options.database, options.secret, options.policy.namespace),\n keyGenerator: (context) => options.keyGenerator(context),\n handler: options.handler\n ? (context, next, used) => options.handler?.(context, next, used)\n : undefined,\n skip: options.skip\n })\n}\n\nexport function createTrustedIPRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n client: ClientIdentityOptions,\n handler?: RateLimitExceededEventHandler,\n options?: {\n resource?: (context: Context) => string\n skip?: (context: Context) => boolean\n /** The limiter is a route's own budget, which general limiters leave to it. */\n route?: boolean\n }\n) {\n const limiter = createCloudRateLimiter({\n database,\n secret,\n policy,\n keyGenerator: (context) => {\n const ip = trustedClientIP(context, client) ?? 'unavailable'\n return options?.resource ? `resource:${options.resource(context)}:ip:${ip}` : `ip:${ip}`\n },\n skip: (context) =>\n trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),\n handler\n })\n return options?.route ? ownBudget(limiter, options.skip) : limiter\n}\n\nexport function createActorRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean,\n resource?: (context: Context<CloudAPIEnvironment, '*'>) => string\n) {\n return createCloudRateLimiter<CloudAPIEnvironment, '*'>({\n database,\n secret,\n policy,\n keyGenerator: (context) =>\n resource\n ? `resource:${resource(context)}:actor:${context.get('actor').userId}`\n : `actor:${context.get('actor').userId}`,\n skip\n })\n}\n\n/**\n * A limiter a route mounts for its own budget, such as document creation; general limiters leave\n * the requests it counts to it.\n */\nexport function createRouteRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean,\n resource?: (context: Context<CloudAPIEnvironment, '*'>) => string\n) {\n return ownBudget(createActorRateLimiter(database, secret, policy, skip, resource), skip)\n}\n","import { requireTrustedMutationOrigin } from '#cloud/admin/api/security'\nimport type { AdminAuditService } from '#cloud/admin/audit/service'\nimport type { AdminEmailService } from '#cloud/admin/email/service'\nimport type { EnrollmentService } from '#cloud/admin/enrollment/service'\nimport { adminErrorStatus, AdminDomainError } from '#cloud/admin/errors'\nimport type { AdminOperationsService } from '#cloud/admin/operations/service'\nimport {\n enrollmentStatusSchema,\n parseEnrollmentReview,\n parseUserMutation,\n parseUserRoleMutation\n} from '#cloud/admin/schema'\nimport type { AdminUserService } from '#cloud/admin/users/service'\nimport {\n cloudAdminAuditFilterSchema,\n cloudAdminEmailFilterSchema,\n cloudAdminUserFilterSchema\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport type { CloudAuthAdapter } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON, validatedQuery } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport { NoResultError, type Kysely } from 'kysely'\nimport * as v from 'valibot'\n\n/**\n * A count from the query string; anything but digits, or a number too large to be exact, is a bad\n * request rather than a NaN or out-of-range query.\n */\nconst countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber(), v.safeInteger()))\n/** What an admin list reads from its query string: a search, one of `filters`, and a page. */\nfunction listQuery<const Filter extends string>(filters: v.PicklistSchema<Filter[], undefined>) {\n const schema = v.object({\n search: v.optional(v.string()),\n filter: v.optional(filters),\n limit: countSchema,\n offset: countSchema\n })\n return (input: unknown) => v.parse(schema, input)\n}\nconst parseEnrollmentQuery = listQuery(enrollmentStatusSchema)\nconst parseUserQuery = listQuery(cloudAdminUserFilterSchema)\nconst parseEmailQuery = listQuery(cloudAdminEmailFilterSchema)\nconst parseAuditQuery = listQuery(cloudAdminAuditFilterSchema)\n/** Accounts are named by UUID; anything else names no one, rather than failing the query. */\nconst accountIdSchema = v.pipe(v.string(), v.uuid())\n\n/** Does what an administrator asked to another account; one that is not an account is not found. */\nasync function accountMutation(\n context: Context<CloudAPIEnvironment>,\n userId: string,\n mutate: (actorId: string, userId: string) => Promise<void>\n) {\n if (!v.is(accountIdSchema, userId)) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n await mutate(context.get('actor').userId, userId)\n return context.json({ ok: true as const })\n}\n\nexport type CloudAdminServices = {\n email: AdminEmailService\n enrollment: EnrollmentService\n users: AdminUserService\n audit: AdminAuditService\n operations: AdminOperationsService\n}\n\nexport function createCloudAdminRoutes(\n services: CloudAdminServices,\n trustedOrigins: ReadonlySet<string>,\n security: {\n auth: CloudAuthAdapter\n database: Kysely<CloudDatabase>\n requireMFA: boolean\n secret: string\n }\n) {\n const adminRead = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminRead,\n (context) => context.req.method !== 'GET'\n )\n const adminMutation = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminMutation,\n (context) => context.req.method === 'GET'\n )\n return new Hono<CloudAPIEnvironment>()\n .use('*', requireTrustedMutationOrigin(trustedOrigins))\n .use('*', async (context, next) => {\n const actor = context.get('actor')\n if (actor.deploymentRole !== 'admin') {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (security.requireMFA) {\n const status = await security.auth.mfaStatus(context.req.raw.headers)\n if (!status?.assured) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n return next()\n })\n .use('*', adminRead)\n .use('*', adminMutation)\n .onError((error, context) => {\n if (error instanceof AdminDomainError) {\n return context.json({ error: { code: error.code } }, adminErrorStatus(error))\n }\n if (error instanceof v.ValiError) {\n return context.json({ error: { code: 'invalid_request' as const } }, 400)\n }\n // An enrollment or message ID that names nothing.\n if (error instanceof NoResultError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n throw error\n })\n .get('/enrollments', validatedQuery(parseEnrollmentQuery), async (context) =>\n context.json(await services.enrollment.list(context.req.valid('query')))\n )\n .post('/enrollments/:id/approve', validatedJSON(parseEnrollmentReview), async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.param('id'),\n 'approved',\n context.req.valid('json')\n )\n })\n )\n .post('/enrollments/:id/reject', validatedJSON(parseEnrollmentReview), async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.param('id'),\n 'rejected',\n context.req.valid('json')\n )\n })\n )\n .post('/enrollments/:id/revoke', validatedJSON(parseEnrollmentReview), async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.param('id'),\n 'revoked',\n context.req.valid('json')\n )\n })\n )\n .get('/users', validatedQuery(parseUserQuery), async (context) =>\n context.json(await services.users.list(context.req.valid('query')))\n )\n .get('/users/:id', async (context) => {\n const id = context.req.param('id')\n const detail = v.is(accountIdSchema, id) ? await services.users.detail(id) : null\n if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json(detail)\n })\n .post('/users/reset-two-step', validatedJSON(parseUserMutation), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.resetTwoStep(actorId, userId)\n )\n )\n .post('/users/remove-picture', validatedJSON(parseUserMutation), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.removePicture(actorId, userId)\n )\n )\n .post('/users/ban', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.ban(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.reason\n )\n return context.json({ ok: true as const })\n })\n .post('/users/unban', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.unban(context.req.raw.headers, context.get('actor').userId, input.userId)\n return context.json({ ok: true as const })\n })\n .post('/users/revoke-sessions', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.revokeSessions(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId\n )\n return context.json({ ok: true as const })\n })\n .post('/users/set-admin', validatedJSON(parseUserRoleMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.setAdmin(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.enabled\n )\n return context.json({ ok: true as const })\n })\n .get('/email', validatedQuery(parseEmailQuery), async (context) =>\n context.json(await services.email.list(context.req.valid('query')))\n )\n .post('/email/:id/regenerate', async (context) => {\n await services.email.regenerate(context.get('actor').userId, context.req.param('id'))\n return context.json({ ok: true as const })\n })\n .get('/audit', validatedQuery(parseAuditQuery), async (context) =>\n context.json(await services.audit.list(context.req.valid('query')))\n )\n .get('/operations', async (context) => context.json(await services.operations.summary()))\n}\n\n/** The administration routes' types, for the portal's typed client. */\nexport type CloudAdminRoutes = ReturnType<typeof createCloudAdminRoutes>\n","import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { clamp, zipObject } from 'es-toolkit'\nimport type { Expression, ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'\n\n/** The rows an admin list returns when the request does not say. */\nexport const ADMIN_PAGE_SIZE = 50\n\n/** What every admin list takes: words to search for, one of its filters, and a page. */\nexport type AdminListQuery<Filter extends string> = {\n search?: string\n filter?: Filter\n limit?: number\n offset?: number\n}\n\n/** A `like` pattern that finds `search` anywhere, matching `%`, `_`, and `\\` literally. */\nexport function containsPattern(search: string): string {\n return `%${search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n}\n\n/** The search words, or undefined when there are none. */\nexport function listSearch(query: AdminListQuery<string>): string | undefined {\n return query.search?.trim() || undefined\n}\n\n/** The page a query asks for, kept within what one request may return. */\nexport function listWindow(query: AdminListQuery<string>) {\n return {\n limit: clamp(query.limit ?? ADMIN_PAGE_SIZE, 1, ADMIN_LIST_MAXIMUM),\n offset: Math.max(0, query.offset ?? 0)\n }\n}\n\n/** A list's filters, each the condition its rows meet; the same one counts them and pages them. */\nexport type ListFilters<Filter extends string, Table extends keyof CloudDatabase> = Record<\n Filter,\n (expression: ExpressionBuilder<CloudDatabase, Table>) => Expression<SqlBool>\n>\n\n/**\n * How many of `searched`'s rows meet each filter, in one query: each count is an aggregate with a\n * `filter (where …)` clause rather than a query of its own.\n */\nexport async function countEachFilter<Filter extends string, Table extends keyof CloudDatabase>(\n searched: SelectQueryBuilder<CloudDatabase, Table, object>,\n names: readonly Filter[],\n filters: ListFilters<Filter, Table>\n): Promise<Record<Filter, number>> {\n // Kysely names each column after its filter but cannot type a generic name, so the row is read\n // as counts by name.\n const row: Record<string, unknown> = await searched\n .select((expression) =>\n names.map((name) => expression.fn.countAll<number>().filterWhere(filters[name]).as(name))\n )\n .executeTakeFirstOrThrow()\n return zipObject(\n names,\n names.map((name) => Number(row[name]))\n )\n}\n","import {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { cloudAdminAuditFilterSchema, type CloudAdminAuditFilter } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { uniq } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\n/** Events by what they are about; every event is under `all`. */\nconst FILTERS: ListFilters<CloudAdminAuditFilter, 'adminAuditEvent'> = {\n all: (expression) => expression.lit(true),\n accounts: (expression) => expression('adminAuditEvent.subjectType', '=', 'user'),\n requests: (expression) => expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n email: (expression) => expression('adminAuditEvent.subjectType', '=', 'transactional-email')\n}\n\ntype AuditExpression = ExpressionBuilder<CloudDatabase, 'adminAuditEvent'>\n\n/** Events whose actor, or the account or request they are about, has `pattern` in a name or email. */\nfunction searchCondition(pattern: string) {\n return (expression: AuditExpression) => {\n const account = (column: 'adminAuditEvent.actorUserId' | 'adminAuditEvent.subjectId') =>\n expression.exists(\n expression\n .selectFrom('user')\n .select('user.id')\n .where((inner) => inner(inner.cast('user.id', 'text'), '=', inner.ref(column)))\n .where((inner) =>\n inner.or([inner('user.name', 'ilike', pattern), inner('user.email', 'ilike', pattern)])\n )\n )\n return expression.or([\n account('adminAuditEvent.actorUserId'),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'user'),\n account('adminAuditEvent.subjectId')\n ]),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n expression.exists(\n expression\n .selectFrom('enrollment')\n .select('enrollment.id')\n .where((inner) =>\n inner(\n inner.cast('enrollment.id', 'text'),\n '=',\n inner.ref('adminAuditEvent.subjectId')\n )\n )\n .where((inner) =>\n inner.or([\n inner('enrollment.name', 'ilike', pattern),\n inner('enrollment.emailNormalized', 'ilike', pattern)\n ])\n )\n )\n ])\n ])\n }\n}\n\nexport function createAdminAuditService(database: Kysely<CloudDatabase>) {\n return {\n /**\n * A page of events, newest first, each with its actor's and subject's names while the server\n * knows them, and how many match the search under each filter.\n */\n async list(query: AdminListQuery<CloudAdminAuditFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('adminAuditEvent')\n if (search) searched = searched.where(searchCondition(containsPattern(search)))\n const counts = await countEachFilter(searched, cloudAdminAuditFilterSchema.options, FILTERS)\n const events = await searched\n .where(FILTERS[filter])\n .selectAll()\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Accounts and requests are named by UUID; anything else is not looked up.\n const userIds = uniq(\n events.flatMap((event) =>\n event.subjectType === 'user' ? [event.actorUserId, event.subjectId] : [event.actorUserId]\n )\n ).filter(isUUID)\n const enrollmentIds = uniq(\n events.flatMap((event) => (event.subjectType === 'enrollment' ? [event.subjectId] : []))\n ).filter(isUUID)\n const [users, enrollments] = await Promise.all([\n userIds.length\n ? database.selectFrom('user').select(['id', 'name']).where('id', 'in', userIds).execute()\n : [],\n enrollmentIds.length\n ? database\n .selectFrom('enrollment')\n .select(['id', 'name', 'emailNormalized'])\n .where('id', 'in', enrollmentIds)\n .execute()\n : []\n ])\n const names = new Map(users.map((user) => [user.id, user.name]))\n const requesters = new Map(\n enrollments.map((enrollment) => [\n enrollment.id,\n enrollment.name ?? enrollment.emailNormalized\n ])\n )\n const rows = events.map((event) => ({\n id: event.id,\n actor: { id: event.actorUserId, name: names.get(event.actorUserId) ?? null },\n action: event.action,\n subject: {\n type: event.subjectType,\n id: event.subjectId,\n name:\n (event.subjectType === 'enrollment'\n ? requesters.get(event.subjectId)\n : names.get(event.subjectId)) ?? null\n },\n metadata: event.metadata,\n createdAt: event.createdAt\n }))\n return { events: rows, total: counts[filter], counts }\n }\n }\n}\n\nexport type AdminAuditService = ReturnType<typeof createAdminAuditService>\n","import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'\nimport { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { cloudAdminEmailFilterSchema, type CloudAdminEmailFilter } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\n/** The enrollment status each message describes; a message is resent only while it still holds. */\nconst ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {\n 'enrollment-requested': 'pending',\n 'enrollment-approved': 'approved',\n 'enrollment-rejected': 'rejected',\n 'enrollment-revoked': 'revoked'\n}\n\n/** Messages by how their delivery went; every message is under `all`. */\nconst FILTERS: ListFilters<CloudAdminEmailFilter, 'transactionalEmail'> = {\n all: (expression) => expression.lit(true),\n sent: (expression) => expression('status', '=', 'accepted'),\n waiting: (expression) => expression('status', 'in', ['pending', 'sending']),\n failed: (expression) => expression('status', '=', 'failed')\n}\n\nexport function createAdminEmailService(\n database: Kysely<CloudDatabase>,\n email?: TransactionalEmailService,\n links: { publicURL: string } = { publicURL: '' }\n) {\n return {\n /** A page of messages, newest first, with how many match the search under each filter. */\n async list(query: AdminListQuery<CloudAdminEmailFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('transactionalEmail')\n if (search) {\n searched = searched.where('recipientEmailNormalized', 'ilike', containsPattern(search))\n }\n const counts = await countEachFilter(searched, cloudAdminEmailFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select([\n 'id',\n 'kind',\n 'recipientEmailNormalized',\n 'status',\n 'attemptCount',\n 'nextAttemptAt',\n 'transport',\n 'transportMessageId',\n 'lastErrorCode',\n 'createdAt',\n 'acceptedAt'\n ])\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n return {\n messages: rows.map((row) => ({\n ...row,\n regeneratable: row.kind.startsWith('enrollment-')\n })),\n total: counts[filter],\n counts\n }\n },\n async regenerate(actorId: string, messageId: string): Promise<void> {\n if (!email)\n throw new AdminDomainError('email_regeneration_unavailable', 'Email delivery is disabled')\n await database.transaction().execute(async (transaction) => {\n const original = await transaction\n .selectFrom('transactionalEmail')\n .select(['id', 'kind', 'recipientEmailNormalized'])\n .where('id', '=', messageId)\n .executeTakeFirstOrThrow()\n if (\n !original.kind.startsWith('enrollment-') ||\n original.kind === 'admin-enrollment-notification'\n ) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'This message cannot be regenerated'\n )\n }\n const kind = original.kind\n const enrollment = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', original.recipientEmailNormalized)\n .executeTakeFirst()\n if (!enrollment)\n throw new AdminDomainError('email_regeneration_unavailable', 'Enrollment is unavailable')\n if (ENROLLMENT_MESSAGE_STATUS[kind] !== enrollment.status) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'The enrollment no longer matches this message'\n )\n }\n await email.enqueue(\n {\n idempotencyKey: `admin-regeneration/${messageId}/${crypto.randomUUID()}`,\n kind,\n recipientEmail: enrollment.emailNormalized,\n payload: {\n name: enrollment.name ?? 'there',\n actionURL:\n kind === 'enrollment-approved'\n ? links.publicURL\n : new URL('/auth/sign-in', links.publicURL).href\n }\n },\n transaction\n )\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'email.regenerated',\n subjectType: 'transactional-email',\n subjectId: messageId,\n metadata: { replacementKind: kind }\n })\n .execute()\n })\n }\n }\n}\n\nexport type AdminEmailService = ReturnType<typeof createAdminEmailService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Transaction } from 'kysely'\n\nimport type { EnrollmentStatus } from './service'\n\nexport type EnrollmentEmailOptions = {\n /**\n * The server's address: its editor, where an approved account goes next, and its own pages,\n * where people sign in and administrators review requests.\n */\n publicURL: string\n adminRecipients: string[]\n email?: TransactionalEmailService\n}\n\nexport async function enqueueEnrollmentRequested(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: { enrollmentId: string; email: string; name: string; reason: string; revision: number }\n): Promise<void> {\n if (!options.email) return\n await options.email.enqueue(\n {\n idempotencyKey: `enrollment-requested/${input.enrollmentId}/${input.revision}`,\n kind: 'enrollment-requested',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', options.publicURL).href }\n },\n transaction\n )\n for (const recipientEmail of options.adminRecipients) {\n await options.email.enqueue(\n {\n idempotencyKey: `admin-enrollment-notification/${input.enrollmentId}/${input.revision}/${recipientEmail}`,\n kind: 'admin-enrollment-notification',\n recipientEmail,\n payload: {\n requesterEmail: input.email,\n requesterName: input.name,\n reason: input.reason,\n actionURL: new URL('/admin/requests', options.publicURL).href\n }\n },\n transaction\n )\n }\n}\n\nexport async function enqueueEnrollmentReview(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: {\n enrollmentId: string\n recipientEmail: string\n name: string\n status: Exclude<EnrollmentStatus, 'pending'>\n reviewedAt: Date\n }\n): Promise<void> {\n if (!options.email) return\n await options.email.enqueue(\n {\n idempotencyKey: `enrollment-${input.status}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,\n kind: `enrollment-${input.status}`,\n recipientEmail: input.recipientEmail,\n payload: {\n name: input.name,\n actionURL:\n input.status === 'approved'\n ? options.publicURL\n : new URL('/auth/sign-in', options.publicURL).href\n }\n },\n transaction\n )\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { enrollmentStatusSchema } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { compact, uniq } from 'es-toolkit'\nimport type { Kysely } from 'kysely'\n\nimport {\n enqueueEnrollmentRequested,\n enqueueEnrollmentReview,\n type EnrollmentEmailOptions\n} from './email'\n\nexport type EnrollmentStatus = 'pending' | 'approved' | 'rejected' | 'revoked'\nexport type EnrollmentMode = 'open' | 'approval' | 'closed'\n\nexport type EnrollmentRequestInput = { email: string; name?: string; reason?: string }\nexport type EnrollmentReviewInput = { note?: string }\nexport type EnrollmentRecord = {\n id: string\n email: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: string\n reviewedAt: string | null\n reviewedBy: string | null\n reviewerName?: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\ntype EnrollmentRow = {\n id: string\n emailNormalized: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: Date | string\n reviewedAt: Date | string | null\n reviewedBy: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\nconst ALLOWED_TRANSITIONS: Record<EnrollmentStatus, ReadonlySet<EnrollmentStatus>> = {\n pending: new Set(['approved', 'rejected']),\n approved: new Set(['revoked']),\n rejected: new Set(['pending', 'approved']),\n revoked: new Set(['pending', 'approved'])\n}\n\n/** Requests by their status; each is in exactly one. */\nconst FILTERS: ListFilters<EnrollmentStatus, 'enrollment'> = {\n pending: (expression) => expression('status', '=', 'pending'),\n approved: (expression) => expression('status', '=', 'approved'),\n rejected: (expression) => expression('status', '=', 'rejected'),\n revoked: (expression) => expression('status', '=', 'revoked')\n}\n\nfunction dateString(value: Date | string | null): string | null {\n return value ? new Date(value).toISOString() : null\n}\nfunction enrollmentRecord(row: EnrollmentRow): EnrollmentRecord {\n return {\n id: row.id,\n email: row.emailNormalized,\n name: row.name,\n reason: row.reason,\n status: row.status,\n requestedAt: dateString(row.requestedAt) ?? '',\n reviewedAt: dateString(row.reviewedAt),\n reviewedBy: row.reviewedBy,\n reviewNote: row.reviewNote,\n approvedUserId: row.approvedUserId,\n requestRevision: row.requestRevision\n }\n}\nexport function normalizeEnrollmentEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nexport function createEnrollmentService(\n database: Kysely<CloudDatabase>,\n emailOptions: EnrollmentEmailOptions = { publicURL: '', adminRecipients: [] }\n) {\n const statusForEmail = async (email: string): Promise<EnrollmentStatus | null> => {\n const row = await database\n .selectFrom('enrollment')\n .select('status')\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .executeTakeFirst()\n return row?.status ?? null\n }\n return {\n async request(input: EnrollmentRequestInput): Promise<void> {\n const emailNormalized = normalizeEnrollmentEmail(input.email)\n await database.transaction().execute(async (transaction) => {\n const existing = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', emailNormalized)\n .forUpdate()\n .executeTakeFirst()\n if (existing?.status === 'approved' || existing?.status === 'pending') return\n const revision = (existing?.requestRevision ?? 0) + 1\n const values = {\n name: input.name?.trim() || existing?.name || null,\n reason: input.reason?.trim() || null,\n status: 'pending' as const,\n reviewedAt: null,\n reviewedBy: null,\n reviewNote: null,\n requestRevision: revision\n }\n let row: EnrollmentRow\n if (existing) {\n row = await transaction\n .updateTable('enrollment')\n .set(values)\n .where('id', '=', existing.id)\n .returningAll()\n .executeTakeFirstOrThrow()\n } else {\n row = await transaction\n .insertInto('enrollment')\n .values({\n id: crypto.randomUUID(),\n emailNormalized,\n ...values,\n approvedUserId: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n }\n await enqueueEnrollmentRequested(transaction, emailOptions, {\n enrollmentId: row.id,\n email: row.emailNormalized,\n name: row.name ?? 'there',\n reason: row.reason ?? 'No reason provided.',\n revision\n })\n })\n },\n statusForEmail,\n async isApproved(email: string): Promise<boolean> {\n return (await statusForEmail(email)) === 'approved'\n },\n /** A page of requests in one status, newest first, with how many match the search in each. */\n async list(query: AdminListQuery<EnrollmentStatus> = {}) {\n const search = listSearch(query)\n const status = query.filter ?? 'pending'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('enrollment')\n if (search) {\n const pattern = containsPattern(search)\n searched = searched.where((expression) =>\n expression.or([\n expression('name', 'ilike', pattern),\n expression('emailNormalized', 'ilike', pattern)\n ])\n )\n }\n const counts = await countEachFilter(searched, enrollmentStatusSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[status])\n .selectAll()\n .orderBy('requestedAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Reviewers are named by account ID; anything else names no one.\n const reviewerIds = uniq(compact(rows.map((row) => row.reviewedBy))).filter(isUUID)\n const reviewers = reviewerIds.length\n ? await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', reviewerIds)\n .execute()\n : []\n const names = new Map(reviewers.map((reviewer) => [reviewer.id, reviewer.name]))\n const enrollments = rows.map((row) => ({\n ...enrollmentRecord(row),\n reviewerName: row.reviewedBy ? (names.get(row.reviewedBy) ?? null) : null\n }))\n return { enrollments, total: counts[status], counts }\n },\n async review(\n actorId: string,\n enrollmentId: string,\n status: Exclude<EnrollmentStatus, 'pending'>,\n input: EnrollmentReviewInput\n ): Promise<EnrollmentRecord> {\n return database.transaction().execute(async (transaction) => {\n const current = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('id', '=', enrollmentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (!ALLOWED_TRANSITIONS[current.status].has(status)) {\n throw new AdminDomainError(\n 'invalid_enrollment_transition',\n `Enrollment cannot transition from ${current.status} to ${status}`\n )\n }\n const now = new Date()\n const approvedUser =\n status === 'approved'\n ? await transaction\n .selectFrom('user')\n .select('id')\n .where('email', '=', current.emailNormalized)\n .executeTakeFirst()\n : undefined\n const row = await transaction\n .updateTable('enrollment')\n .set({\n status,\n reviewedAt: now,\n reviewedBy: actorId,\n reviewNote: input.note?.trim() || null,\n approvedUserId: approvedUser?.id ?? current.approvedUserId\n })\n .where('id', '=', enrollmentId)\n .where('status', '=', current.status)\n .returningAll()\n .executeTakeFirstOrThrow()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: `enrollment.${status}`,\n subjectType: 'enrollment',\n subjectId: enrollmentId,\n metadata: { email: row.emailNormalized },\n createdAt: now\n })\n .execute()\n await enqueueEnrollmentReview(transaction, emailOptions, {\n enrollmentId,\n recipientEmail: row.emailNormalized,\n name: row.name ?? 'there',\n status,\n reviewedAt: now\n })\n return enrollmentRecord(row)\n })\n },\n async bindApprovedUser(email: string, userId: string): Promise<void> {\n await database\n .updateTable('enrollment')\n .set({ approvedUserId: userId })\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .where('status', '=', 'approved')\n .execute()\n },\n /**\n * Moves an approved account's enrollment to the address it changed to, so the approval stays\n * with the account rather than with an address it no longer uses. Any other request from the\n * new address gives way to it.\n */\n async followEmailChange(userId: string, email: string): Promise<void> {\n const emailNormalized = normalizeEnrollmentEmail(email)\n await database.transaction().execute(async (transaction) => {\n const approved = await transaction\n .selectFrom('enrollment')\n .select(['id', 'emailNormalized'])\n .where('approvedUserId', '=', userId)\n .where('status', '=', 'approved')\n .forUpdate()\n .executeTakeFirst()\n if (!approved || approved.emailNormalized === emailNormalized) return\n await transaction\n .deleteFrom('enrollment')\n .where('emailNormalized', '=', emailNormalized)\n .where('id', '!=', approved.id)\n .execute()\n await transaction\n .updateTable('enrollment')\n .set({ emailNormalized })\n .where('id', '=', approved.id)\n .execute()\n })\n },\n async pendingCount(): Promise<number> {\n const row = await database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n }\n}\nexport type EnrollmentService = ReturnType<typeof createEnrollmentService>\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport function createAdminOperationsService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n async function emailCount(status: 'pending' | 'failed'): Promise<number> {\n const row = await database\n .selectFrom('transactionalEmail')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', status)\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n\n return {\n async summary() {\n const [\n pendingEnrollment,\n pendingEmail,\n failedEmail,\n accounts,\n workspaces,\n documents,\n stored\n ] = await Promise.all([\n database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow(),\n emailCount('pending'),\n emailCount('failed'),\n database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspace')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('document')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('deletedAt', 'is', null)\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspaceStorageUsage')\n .select(({ fn }) => fn.sum<number | null>('committedBytes').as('bytes'))\n .executeTakeFirstOrThrow()\n ])\n return {\n deployment: config.deployment,\n enrollmentMode: config.enrollmentMode,\n emailTransport: config.emailTransport,\n pendingEnrollment: Number(pendingEnrollment.count),\n pendingEmail,\n failedEmail,\n accounts: Number(accounts.count),\n workspaces: Number(workspaces.count),\n documents: Number(documents.count),\n storedBytes: Number(stored.bytes ?? 0)\n }\n }\n }\n}\n\nexport type AdminOperationsService = ReturnType<typeof createAdminOperationsService>\n","export const CLOUD_FEATURE_KEYS = {\n links: 'cloud.sharing.links',\n guestView: 'cloud.sharing.guest-view',\n guestEdit: 'cloud.sharing.guest-edit',\n guestPresence: 'cloud.sharing.guest-presence',\n collaboration: 'cloud.collaboration.enabled',\n serverEnforcedWrites: 'cloud.collaboration.server-enforced-writes',\n revisionHistory: 'cloud.documents.revision-history',\n maximumFileBytes: 'cloud.documents.maximum-file-bytes',\n maximumStorageBytes: 'cloud.storage.maximum-bytes',\n maximumParticipants: 'cloud.collaboration.maximum-participants',\n cloudAI: 'cloud.ai.enabled',\n monthlyCreditAllowance: 'cloud.ai.monthly-credit-allowance'\n} as const\n\nexport type CloudPolicyContext = {\n targetingKey: string\n actorId?: string\n workspaceId?: string\n organizationId?: string\n documentId?: string\n deploymentMode: 'official' | 'self-hosted'\n}\n","import { pickBy } from 'es-toolkit/object'\nimport { isNotNil } from 'es-toolkit/predicate'\nimport * as v from 'valibot'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport {\n staticEntitlementsSchema,\n staticEntitlementsTOMLSchema,\n type StaticEntitlements\n} from './schema'\n\n/** Entitlements as a writer sends them, with any group left out. */\nexport type StaticEntitlementsInput = v.InferInput<typeof staticEntitlementsSchema>\n\n/** Entitlements as the deployment TOML spells them, renamed to their structured form. */\nexport function staticEntitlementsFromTOML(\n value: v.InferOutput<typeof staticEntitlementsTOMLSchema>\n): StaticEntitlements {\n return v.parse(staticEntitlementsSchema, {\n documents: {\n maximumFileBytes: value.documents?.maximum_file_bytes,\n revisionHistory: value.documents?.revision_history\n },\n storage: { maximumBytes: value.storage?.maximum_bytes },\n sharing: {\n links: value.sharing?.links,\n guestView: value.sharing?.guest_view,\n guestEdit: value.sharing?.guest_edit,\n guestPresence: value.sharing?.guest_presence\n },\n collaboration: {\n enabled: value.collaboration?.enabled,\n maximumParticipants: value.collaboration?.maximum_participants\n },\n ai: {\n enabled: value.ai?.enabled,\n monthlyCreditAllowance: value.ai?.monthly_credit_allowance\n }\n })\n}\n\nexport function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {\n return staticEntitlementsFromTOML(v.parse(staticEntitlementsTOMLSchema, input))\n}\n\nexport function staticEntitlementValues(input: unknown): Record<string, boolean | number> {\n const entitlements = v.parse(staticEntitlementsSchema, input)\n const values: Record<string, boolean | number | undefined> = {\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: entitlements.documents.maximumFileBytes,\n [CLOUD_FEATURE_KEYS.revisionHistory]: entitlements.documents.revisionHistory,\n [CLOUD_FEATURE_KEYS.maximumStorageBytes]: entitlements.storage.maximumBytes,\n [CLOUD_FEATURE_KEYS.links]: entitlements.sharing.links,\n [CLOUD_FEATURE_KEYS.guestView]: entitlements.sharing.guestView,\n [CLOUD_FEATURE_KEYS.guestEdit]: entitlements.sharing.guestEdit,\n [CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,\n [CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,\n [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,\n [CLOUD_FEATURE_KEYS.cloudAI]: entitlements.ai.enabled,\n [CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.ai.monthlyCreditAllowance\n }\n return pickBy(values, isNotNil) as Record<string, boolean | number>\n}\n","import { staticEntitlementsFromTOML } from '#cloud/server/policy/static'\nimport { parse as parseTOML } from 'smol-toml'\nimport * as v from 'valibot'\n\nimport {\n cloudDeploymentConfigSchema,\n parseCloudServerConfig,\n type CloudDeploymentConfig,\n type CloudSecretReference,\n type CloudServerConfig\n} from './schema'\n\nexport type CloudEnvironment = Readonly<Record<string, string | undefined>>\n\nexport function parseCloudDeploymentSource(source: string): CloudDeploymentConfig {\n return v.parse(cloudDeploymentConfigSchema, parseTOML(source))\n}\n\nfunction requiredSecret(environment: CloudEnvironment, reference: CloudSecretReference): string {\n const value = environment[reference.from_env]\n if (!value) throw new Error(`Required secret binding is unavailable: ${reference.from_env}`)\n return value\n}\n\nfunction configuredText(\n environment: CloudEnvironment,\n value: string | CloudSecretReference\n): string {\n return typeof value === 'string' ? value : requiredSecret(environment, value)\n}\n\nfunction optionalSecret(\n environment: CloudEnvironment,\n reference?: CloudSecretReference\n): string | undefined {\n return reference ? environment[reference.from_env] : undefined\n}\n\nfunction staticEntitlements(config: CloudDeploymentConfig) {\n if (config.entitlements?.source !== 'static') return undefined\n return staticEntitlementsFromTOML(config.entitlements)\n}\n\nfunction emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n if (config.email.transport === 'none') return { emailTransport: 'none' as const }\n if (config.email.transport === 'cloudflare') {\n return { emailTransport: 'cloudflare' as const, emailFrom: config.email.from }\n }\n return {\n emailTransport: 'smtp' as const,\n emailFrom: config.email.from,\n smtpHost: config.email.smtp.host,\n smtpPort: config.email.smtp.port,\n smtpSecure: config.email.smtp.secure,\n smtpUser: optionalSecret(environment, config.email.smtp.user),\n smtpPassword: optionalSecret(environment, config.email.smtp.password)\n }\n}\n\nfunction authenticationConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n const google = config.authentication.providers.google\n const apple = config.authentication.providers.apple\n return {\n googleClientId: google ? configuredText(environment, google.client_id) : undefined,\n googleClientSecret: google ? requiredSecret(environment, google.client_secret) : undefined,\n appleClientId: apple?.client_id,\n appleTeamId: apple?.team_id,\n appleKeyId: apple?.key_id,\n applePrivateKey: apple ? requiredSecret(environment, apple.private_key) : undefined,\n appleAppBundleIdentifier: apple?.app_bundle_identifier\n }\n}\n\nfunction workerConfig(config: CloudDeploymentConfig) {\n const email = config.workers?.email\n const cleanup = config.workers?.cleanup\n return {\n emailBatchSize: email?.batch_size,\n emailIntervalMs: email?.interval_ms,\n emailLeaseDurationMs: email?.lease_ms,\n emailMaximumAttempts: email?.maximum_attempts,\n cleanupEnabled: cleanup?.enabled,\n cleanupBatchSize: cleanup?.batch_size,\n cleanupIntervalMs: cleanup?.interval_ms,\n cleanupLeaseDurationMs: cleanup?.lease_ms,\n documentRetentionMs: config.documents.retention_days * 86_400_000\n }\n}\n\nfunction serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n return {\n aiEndpoint: config.ai?.endpoint,\n aiSigningKey: config.ai ? requiredSecret(environment, config.ai.signing_key) : undefined,\n aiTokenLifetimeSeconds: config.ai ? config.ai.token_lifetime_minutes * 60 : undefined,\n billingPortalURL: config.billing?.portal_url,\n internalServiceToken: config.internal_api\n ? requiredSecret(environment, config.internal_api.service_token)\n : undefined\n }\n}\n\n/** Hard limits, whatever a plan allows; each lives in the section it limits. */\nfunction technicalLimits(config: CloudDeploymentConfig) {\n return {\n maximumUploadBytes: config.object_storage.maximum_upload_bytes,\n maximumCollaborationMessageBytes: config.collaboration.maximum_message_bytes,\n maximumConnectionsPerRoom: config.collaboration.maximum_connections_per_room\n }\n}\n\nexport function parseCloudDeploymentConfig(\n input: unknown,\n environment: CloudEnvironment\n): CloudServerConfig {\n const config = v.parse(cloudDeploymentConfigSchema, input)\n return parseCloudServerConfig({\n deployment: config.deployment.mode,\n publicURL: config.deployment.public_url,\n indexingPolicy: config.deployment.indexing,\n trustedOrigins: config.deployment.trusted_origins,\n localEditor: config.deployment.local_editor,\n listingMinimumEditorVersion: config.deployment.listing?.minimum_editor_version,\n databaseURL: requiredSecret(environment, config.database.url),\n authSecret: requiredSecret(environment, config.authentication.secret),\n enrollmentMode: config.authentication.enrollment.mode,\n enrollmentAdminNotificationEmails: config.authentication.enrollment.notification_emails,\n emailPasswordEnabled: config.authentication.email_password.enabled,\n emailPasswordSignUpEnabled: config.authentication.email_password.sign_up,\n emailPasswordMinimumLength: config.authentication.email_password.minimum_password_length,\n emailPasswordMaximumLength: config.authentication.email_password.maximum_password_length,\n emailVerificationExpiresIn:\n config.authentication.email_password.verification_link_lifetime_minutes * 60,\n passwordResetExpiresIn:\n config.authentication.email_password.password_reset_link_lifetime_minutes * 60,\n compromisedPasswordCheck: config.authentication.email_password.compromised_password_check,\n deploymentAdminMFARequired: config.authentication.mfa.required_for_admins,\n totpEnabled: config.authentication.mfa.totp,\n recoveryCodesEnabled: config.authentication.mfa.recovery_codes,\n mfaTrustedDeviceDays: config.authentication.mfa.trusted_device_lifetime_days,\n passkeysEnabled: config.authentication.passkeys.enabled,\n passkeyRPName: config.authentication.passkeys.rp_name,\n captchaProvider: config.authentication.captcha?.provider,\n captchaSiteKey: config.authentication.captcha?.site_key,\n captchaSecretKey: config.authentication.captcha\n ? requiredSecret(environment, config.authentication.captcha.secret_key)\n : undefined,\n captchaAllowedHostnames: config.authentication.captcha?.allowed_hostnames,\n authTrustedIPHeaders: config.authentication.trusted_proxies.headers,\n authTrustedProxies: config.authentication.trusted_proxies.addresses,\n ...authenticationConfig(config, environment),\n s3Endpoint: config.object_storage.endpoint,\n s3Region: config.object_storage.region,\n s3Bucket: config.object_storage.bucket,\n s3AccessKeyId: requiredSecret(environment, config.object_storage.credentials.access_key_id),\n s3SecretAccessKey: requiredSecret(\n environment,\n config.object_storage.credentials.secret_access_key\n ),\n s3SessionToken: environment[config.object_storage.credentials.session_token.from_env],\n s3ForcePathStyle: config.object_storage.force_path_style,\n s3ChecksumVerification: config.object_storage.checksum_verification,\n s3ServerSideEncryption: config.object_storage.server_side_encryption,\n s3KmsKeyId: config.object_storage.kms_key_id,\n relayURL: config.collaboration.relay_url,\n staticEntitlements: staticEntitlements(config),\n ...emailConfig(config, environment),\n ...workerConfig(config),\n ...serviceConfig(config, environment),\n technicalLimits: technicalLimits(config)\n })\n}\n\nexport function parseCloudDeploymentTOML(\n source: string,\n environment: CloudEnvironment\n): CloudServerConfig {\n return parseCloudDeploymentConfig(parseCloudDeploymentSource(source), environment)\n}\n","import {\n CLOUD_AI_CONTRACT_VERSION,\n CLOUD_PROTOCOL_VERSION,\n parseCloudDiscovery,\n type CloudDiscovery\n} from '#cloud/contract'\nimport { withoutTrailingSlash } from 'ufo'\n\nimport type { CloudServerConfig } from './schema'\n\nexport function configuredSocialProviders(config: CloudServerConfig): Array<'apple' | 'google'> {\n return [\n ...(config.appleClientId ? (['apple'] as const) : []),\n ...(config.googleClientId ? (['google'] as const) : [])\n ]\n}\n\nexport function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscovery {\n const authentication: CloudDiscovery['authentication'] = {\n socialProviders: configuredSocialProviders(config),\n enterpriseSSO: false,\n enrollmentMode: config.enrollmentMode\n }\n if (config.emailPasswordEnabled) {\n authentication.emailPassword = {\n signIn: true,\n signUp: config.emailPasswordSignUpEnabled,\n minimumPasswordLength: config.emailPasswordMinimumLength\n }\n if (config.captchaProvider && config.captchaSiteKey) {\n authentication.emailPassword.captcha = {\n provider: config.captchaProvider,\n siteKey: config.captchaSiteKey\n }\n }\n }\n if (config.totpEnabled || config.passkeysEnabled) {\n authentication.mfa = {\n deploymentAdminRequired: config.deploymentAdminMFARequired,\n totp: config.totpEnabled,\n passkeys: config.passkeysEnabled,\n recoveryCodes: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n\n return parseCloudDiscovery({\n protocolVersion: CLOUD_PROTOCOL_VERSION,\n deployment: config.deployment,\n apiURL: withoutTrailingSlash(new URL('/api', config.publicURL).href),\n authURL: withoutTrailingSlash(new URL('/api/auth', config.publicURL).href),\n localEditor: config.localEditor,\n authentication,\n capabilities: {\n documents: true,\n workspaces: true,\n collaboration: true\n },\n listing: config.listingMinimumEditorVersion\n ? { minimumEditorVersion: config.listingMinimumEditorVersion }\n : undefined,\n ai: config.aiEndpoint\n ? { endpoint: config.aiEndpoint, contractVersion: CLOUD_AI_CONTRACT_VERSION }\n : undefined,\n billing: config.billingPortalURL ? { portalURL: config.billingPortalURL } : undefined\n })\n}\n","import type {\n CloudAuthenticationMethod,\n CloudAuthenticationProvider\n} from '#cloud/contract/account'\nimport { configuredSocialProviders, type CloudServerConfig } from '#cloud/server/config'\n\nimport type { CloudAuthAdapter } from './adapter'\n\nconst supportedProvider = (provider: string): provider is CloudAuthenticationProvider =>\n provider === 'credential' || provider === 'google' || provider === 'apple'\n\nexport function createAccountAuthenticationService(\n auth: CloudAuthAdapter,\n config: CloudServerConfig\n) {\n return {\n async methods(headers: Headers) {\n const accounts = await auth.listAuthenticationMethods(headers)\n const methods = accounts.flatMap((account): CloudAuthenticationMethod[] => {\n if (!supportedProvider(account.providerId)) return []\n return [\n {\n id: account.id,\n provider: account.providerId,\n createdAt: account.createdAt.toISOString(),\n canUnlink: accounts.length > 1\n }\n ]\n })\n return {\n methods,\n availableSocialProviders: configuredSocialProviders(config).filter(\n (provider) => !methods.some((method) => method.provider === provider)\n )\n }\n },\n async changePassword(\n headers: Headers,\n input: { currentPassword: string; newPassword: string }\n ): Promise<void> {\n await auth.changePassword(headers, input)\n },\n async startSocialLink(\n headers: Headers,\n input: { provider: 'google' | 'apple'; callbackURL: string }\n ): Promise<string> {\n if (!configuredSocialProviders(config).includes(input.provider)) {\n throw new Error('Authentication provider is unavailable')\n }\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Authentication callback origin is unavailable')\n }\n return auth.startSocialLink(headers, { ...input, callbackURL: callback.href })\n },\n async unlink(headers: Headers, methodId: string): Promise<void> {\n await auth.unlinkAuthenticationMethod(headers, methodId)\n },\n /** Asks for a new address; the link that confirms it comes back to this server's pages. */\n async changeEmail(\n headers: Headers,\n input: { newEmail: string; callbackURL: string }\n ): Promise<void> {\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Email change callback origin is unavailable')\n }\n await auth.changeEmail(headers, { ...input, callbackURL: callback.href })\n }\n }\n}\n\nexport type AccountAuthenticationService = ReturnType<typeof createAccountAuthenticationService>\n","import type {\n DocumentGrant,\n DocumentInvitation,\n DocumentPermission,\n DocumentShare\n} from '#cloud/contract'\n\nexport function dateString(value: Date | string | null): string | null {\n if (value === null) return null\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function shareContract(row: {\n id: string\n documentId: string\n permission: DocumentPermission\n roomEpoch: number\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n expiresAt: Date | string | null\n revokedAt: Date | string | null\n lastUsedAt: Date | string | null\n}): DocumentShare {\n // Rows carry the secret's hash; responses name each field so it never goes out.\n return {\n id: row.id,\n documentId: row.documentId,\n permission: row.permission,\n roomEpoch: row.roomEpoch,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt),\n revokedAt: dateString(row.revokedAt),\n lastUsedAt: dateString(row.lastUsedAt)\n }\n}\n\nexport function grantContract(row: {\n id: string\n documentId: string\n userId: string\n permission: DocumentPermission\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n}): DocumentGrant {\n return {\n id: row.id,\n documentId: row.documentId,\n userId: row.userId,\n permission: row.permission,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? ''\n }\n}\n\nexport function invitationContract(row: {\n id: string\n documentId: string\n emailNormalized: string\n permission: DocumentPermission\n invitedBy: string\n invitedAt: Date | string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n}): DocumentInvitation {\n return {\n id: row.id,\n documentId: row.documentId,\n email: row.emailNormalized,\n permission: row.permission,\n invitedBy: row.invitedBy,\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? '',\n acceptedAt: dateString(row.acceptedAt)\n }\n}\n","import type * as BetterAuthEndpoints from 'better-auth/api'\n\n/** Where Better Auth answers under the Cloud server. */\nexport const AUTH_BASE_PATH = '/api/auth'\n\n/** The path an endpoint declares, whether the library exports it built or as a factory. */\ntype PathOf<Endpoint> = Endpoint extends { path: infer Path extends string }\n ? Path\n : Endpoint extends (...args: never) => { path: infer Path extends string }\n ? Path\n : never\ntype CorePaths<Names extends keyof typeof BetterAuthEndpoints> = {\n readonly [Name in Names]: PathOf<(typeof BetterAuthEndpoints)[Name]>\n}\n\n/**\n * The core endpoints whose paths Better Auth's own options need before it is built: rate limits,\n * captcha, and the hooks that record sign-ins. Plugin endpoints come from the plugin objects and\n * the rest from `auth.api`; these few are written out, and the type check holds each to the path\n * the library declares, so a renamed endpoint fails to compile.\n */\nexport const CORE_AUTH_PATHS: CorePaths<\n | 'callbackOAuth'\n | 'requestPasswordReset'\n | 'sendVerificationEmail'\n | 'signInEmail'\n | 'signUpEmail'\n | 'verifyEmail'\n> = {\n callbackOAuth: '/callback/:id',\n requestPasswordReset: '/request-password-reset',\n sendVerificationEmail: '/send-verification-email',\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n verifyEmail: '/verify-email'\n}\n\n/**\n * Whether `path`, as a hook context or request has it, is the endpoint at `endpoint`. Hooks see the\n * declared pattern or the concrete path, so a `:param` segment matches any one segment.\n */\nexport function isAuthEndpoint(path: string | undefined, endpoint: string): boolean {\n if (!path) return false\n const actual = path.split('/')\n const expected = endpoint.split('/')\n return (\n actual.length === expected.length &&\n expected.every((segment, index) =>\n segment.startsWith(':') ? Boolean(actual[index]) : segment === actual[index]\n )\n )\n}\n\n/** The path a request for the endpoint at `endpoint` arrives at on the Cloud server. */\nexport function authRequestPath(endpoint: string): string {\n return `${AUTH_BASE_PATH}${endpoint}`\n}\n","import Bowser from 'bowser'\nimport { compact } from 'es-toolkit'\n\n/** The browser and system a user agent names, as words for a person: `Chrome 141`, `macOS`. */\nexport function describeUserAgent(userAgent: string | null | undefined): {\n browser: string | null\n system: string | null\n} {\n if (!userAgent) return { browser: null, system: null }\n const { browser, os } = Bowser.parse(userAgent)\n const version = browser.version?.split('.', 1)[0]\n return {\n browser: browser.name ? compact([browser.name, version]).join(' ') : null,\n system: os.name || null\n }\n}\n","import type { CloudAccountSession, CloudSignIn, CloudSignInMethod } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport type { BetterAuthPlugin } from 'better-auth'\nimport { createAuthMiddleware, isAPIError } from 'better-auth/api'\nimport type { Kysely } from 'kysely'\n\nimport type { AuthenticationEmailService } from './email'\nimport { CORE_AUTH_PATHS, isAuthEndpoint } from './endpoints'\nimport { describeUserAgent } from './user-agent'\n\n/** The newest sign-ins an account's history shows. */\nconst SIGN_IN_HISTORY_LIMIT = 50\n\ntype Endpoint = { path: string }\n\n/** The plugin endpoints that sign someone in, as the server's plugins declare them. */\nexport type SignInPluginEndpoints = {\n twoStep: { verifyTOTP: Endpoint; verifyBackupCode: Endpoint }\n passkeys: { verifyPasskeyAuthentication: Endpoint; verifyPasskeyRegistration: Endpoint }\n devices: { deviceToken: Endpoint }\n}\n\n/** The Better Auth endpoints that sign someone in, and the method each one is. */\nexport type SignInEndpoints = readonly (readonly [path: string, method: CloudSignInMethod])[]\n\n/** The sign-in endpoints of the core and of the server's plugins, from their own paths. */\nexport function signInEndpoints(plugins: SignInPluginEndpoints): SignInEndpoints {\n return [\n [CORE_AUTH_PATHS.signInEmail, 'password'],\n [plugins.passkeys.verifyPasskeyAuthentication.path, 'passkey'],\n [plugins.twoStep.verifyTOTP.path, 'two-step'],\n [plugins.twoStep.verifyBackupCode.path, 'two-step'],\n [CORE_AUTH_PATHS.verifyEmail, 'email-link'],\n [plugins.devices.deviceToken.path, 'desktop']\n ]\n}\n\n/**\n * How an endpoint signed someone in, or null when it signs nobody in, such as one that refreshes\n * a session. A provider's callback names the provider, as Better Auth's own `lastLoginMethod`\n * reads it.\n */\nexport function signInMethod(\n endpoint: { path?: string; params?: Record<string, string | undefined> },\n methods: SignInEndpoints\n): CloudSignInMethod | null {\n if (isAuthEndpoint(endpoint.path, CORE_AUTH_PATHS.callbackOAuth)) {\n const provider = endpoint.params?.id\n return provider === 'google' || provider === 'apple' ? provider : 'other'\n }\n return methods.find(([path]) => isAuthEndpoint(endpoint.path, path))?.[1] ?? null\n}\n\n/**\n * Where an account signs in from. Each new session is written down with how it was made, so the\n * account's owner can read its sign-ins and sessions, and a sign-in from an address the account\n * never used before is told to its email; the first sign-in an account makes is not.\n */\nexport function createSignInActivity(\n database: Kysely<CloudDatabase>,\n email?: AuthenticationEmailService\n) {\n return {\n /** Writes down a session an endpoint just issued, and mails a sign-in from a new address. */\n async record(\n issued: {\n session: {\n id: string\n userId: string\n ipAddress?: string | null\n userAgent?: string | null\n }\n user: { email: string; name: string }\n },\n method: CloudSignInMethod\n ): Promise<void> {\n const { session, user } = issued\n // Confirming a new email address issues the session it was confirmed in again.\n const recorded = await database\n .selectFrom('signIn')\n .select('id')\n .where('sessionId', '=', session.id)\n .executeTakeFirst()\n if (recorded) return\n const ipAddress = session.ipAddress || null\n const [known, earlier] = await Promise.all([\n ipAddress\n ? database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .where('ipAddress', '=', ipAddress)\n .executeTakeFirst()\n : undefined,\n database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .executeTakeFirst()\n ])\n const id = crypto.randomUUID()\n const signedInAt = new Date()\n await database\n .insertInto('signIn')\n .values({\n id,\n userId: session.userId,\n sessionId: session.id,\n method,\n ipAddress,\n userAgent: session.userAgent || null,\n createdAt: signedInAt\n })\n .execute()\n if (!email || !earlier || known || !ipAddress) return\n await email.sendNewSignIn({\n email: user.email,\n name: user.name,\n signInId: id,\n signedInAt,\n ipAddress,\n ...describeUserAgent(session.userAgent),\n desktop: method === 'desktop'\n })\n },\n\n /** The account's sessions that have not expired, newest activity first. */\n async sessions(userId: string, currentSessionId: string): Promise<CloudAccountSession[]> {\n const rows = await database\n .selectFrom('session')\n .leftJoin('signIn', 'signIn.sessionId', 'session.id')\n .select([\n 'session.id',\n 'session.ipAddress',\n 'session.userAgent',\n 'session.createdAt',\n 'session.updatedAt',\n 'session.expiresAt',\n 'signIn.method'\n ])\n .where('session.userId', '=', userId)\n .where('session.expiresAt', '>', new Date())\n .orderBy('session.updatedAt', 'desc')\n .execute()\n return rows.map((row) => ({\n id: row.id,\n current: row.id === currentSessionId,\n method: row.method ?? null,\n ipAddress: row.ipAddress || null,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? '',\n lastActiveAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }))\n },\n\n async signIns(userId: string, limit = SIGN_IN_HISTORY_LIMIT): Promise<CloudSignIn[]> {\n const rows = await database\n .selectFrom('signIn')\n .select(['id', 'method', 'ipAddress', 'userAgent', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt', 'desc')\n .limit(limit)\n .execute()\n return rows.map((row) => ({\n id: row.id,\n method: row.method,\n ipAddress: row.ipAddress,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? ''\n }))\n }\n }\n}\n\nexport type SignInActivity = ReturnType<typeof createSignInActivity>\n\n/**\n * Better Auth's side of account activity. After an endpoint issues a session, Better Auth hands\n * it to hooks as `newSession`; two-step sign-in clears it until the second step, so only\n * sessions someone can use are written down. Adding a passkey is told to its owner.\n */\nexport function accountActivity(\n activity: SignInActivity,\n plugins: SignInPluginEndpoints,\n onPasskeyAdded: (user: { id: string; email: string; name: string }) => Promise<void>\n): BetterAuthPlugin {\n const methods = signInEndpoints(plugins)\n return {\n id: 'openpencil-account-activity',\n hooks: {\n after: [\n {\n matcher: (context) => signInMethod(context, methods) !== null,\n handler: createAuthMiddleware(async (context) => {\n const issued = context.context.newSession\n const method = signInMethod(context, methods)\n if (issued && method) await activity.record(issued, method)\n })\n },\n {\n matcher: (context) =>\n isAuthEndpoint(context.path, plugins.passkeys.verifyPasskeyRegistration.path),\n handler: createAuthMiddleware(async (context) => {\n const user = context.context.session?.user\n if (user && !isAPIError(context.context.returned)) await onPasskeyAdded(user)\n })\n }\n ]\n }\n }\n}\n","import type { TwoStepChange } from '#cloud/email'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\n\nexport type AuthenticationEmailService = {\n sendVerification(input: {\n email: string\n name: string\n url: string\n token: string\n purpose?: 'account' | 'change'\n }): Promise<void>\n sendPasswordReset(input: {\n email: string\n name: string\n url: string\n token: string\n }): Promise<void>\n sendPasswordChanged(input: {\n email: string\n name: string\n userId: string\n url: string\n }): Promise<void>\n /** Tells the address being replaced which address is taking over, before it confirms. */\n sendEmailChangeRequested(input: {\n email: string\n name: string\n userId: string\n newEmail: string\n }): Promise<void>\n sendNewSignIn(input: {\n email: string\n name: string\n signInId: string\n signedInAt: Date\n ipAddress: string | null\n browser: string | null\n system: string | null\n desktop: boolean\n }): Promise<void>\n sendTwoStepChanged(input: {\n email: string\n name: string\n userId: string\n change: TwoStepChange\n }): Promise<void>\n}\n\nfunction tokenHash(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function createAuthenticationEmailService(\n email: TransactionalEmailService,\n publicURL: string\n): AuthenticationEmailService {\n return {\n async sendVerification(input) {\n await email.enqueue({\n idempotencyKey: `email-verification/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'email-verification',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: input.url, purpose: input.purpose }\n })\n },\n async sendPasswordReset(input) {\n await email.enqueue({\n idempotencyKey: `password-reset/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'password-reset',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: input.url }\n })\n },\n async sendPasswordChanged(input) {\n await email.enqueue({\n idempotencyKey: `password-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'password-changed',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', publicURL).href }\n })\n },\n async sendEmailChangeRequested(input) {\n await email.enqueue({\n idempotencyKey: `email-change-requested/${input.userId}/${crypto.randomUUID()}`,\n kind: 'email-change-requested',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n newEmail: input.newEmail,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n async sendNewSignIn(input) {\n await email.enqueue({\n idempotencyKey: `new-sign-in/${input.signInId}`,\n kind: 'new-sign-in',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n signedInAt: input.signedInAt.toISOString(),\n ipAddress: input.ipAddress,\n browser: input.browser,\n system: input.system,\n desktop: input.desktop,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n async sendTwoStepChanged(input) {\n await email.enqueue({\n idempotencyKey: `two-step-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'two-step-changed',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n change: input.change,\n actionURL: new URL('/account/security', publicURL).href\n }\n })\n }\n }\n}\n","import type { CloudMFAStatus } from '#cloud/server/auth/adapter'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nconst ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000\n\nexport function createMFAAssuranceService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n return {\n async record(input: {\n sessionId: string\n userId: string\n method: 'totp' | 'recovery-code' | 'passkey'\n }): Promise<void> {\n await database\n .insertInto('mfaAssurance')\n .values({ ...input, verifiedAt: new Date() })\n .onConflict((conflict) =>\n conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })\n )\n .execute()\n },\n async status(input: {\n sessionId: string\n userId: string\n deploymentRole?: 'user' | 'admin'\n twoFactorEnabled: boolean\n passkeyCount: number\n }): Promise<CloudMFAStatus> {\n const assurance = await database\n .selectFrom('mfaAssurance')\n .select('verifiedAt')\n .where('sessionId', '=', input.sessionId)\n .where('userId', '=', input.userId)\n .executeTakeFirst()\n const assured = Boolean(\n assurance && new Date(assurance.verifiedAt).getTime() > Date.now() - ASSURANCE_MAX_AGE_MS\n )\n return {\n required: config.deploymentAdminMFARequired && input.deploymentRole === 'admin' && !assured,\n enabled: input.twoFactorEnabled || input.passkeyCount > 0,\n totpEnabled: input.twoFactorEnabled,\n assured,\n totpAvailable: config.totpEnabled,\n passkeysAvailable: config.passkeysEnabled,\n recoveryCodesAvailable: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n }\n}\n\nexport type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>\n","import type { BetterAuthPlugin } from 'better-auth'\nimport { decodeJwt } from 'jose'\nimport * as v from 'valibot'\n\nimport type { UserPictureService } from './service'\n\n/** The providers whose ID token names the person's picture. */\nconst PICTURE_PROVIDERS = new Set(['google'])\nconst pictureClaimSchema = v.object({ picture: v.pipe(v.string(), v.url()) })\n\n/**\n * The picture a linked account's provider names in the ID token Better Auth keeps on its account\n * row, or null. The token came to Better Auth from the provider during its sign-in flow, which no\n * client can write to the row.\n */\nexport function providerPicture(account: { providerId: string; idToken?: string | null }) {\n if (!PICTURE_PROVIDERS.has(account.providerId) || !account.idToken) return null\n try {\n const claims = v.safeParse(pictureClaimSchema, decodeJwt(account.idToken))\n return claims.success ? claims.output.picture : null\n } catch {\n return null\n }\n}\n\n/**\n * Keeps the picture a Google account names, so pages show the server's copy and never load it\n * from Google. Better Auth writes the account's ID token when it is linked and at each sign-in\n * with it, so accounts made before the server kept pictures move over the next time they sign in\n * this way. Better Auth also takes an `image` on sign-up and user updates; none of those reach the\n * account, since the server writes the addresses of the pictures it keeps itself.\n */\nexport function providerPictures(pictures: UserPictureService): BetterAuthPlugin {\n const keep = async (account: { userId: string; providerId: string; idToken?: string | null }) => {\n const picture = providerPicture(account)\n if (picture) await pictures.copyFromProvider(account.userId, picture)\n }\n return {\n id: 'openpencil-provider-pictures',\n init: () => ({\n options: {\n databaseHooks: {\n user: {\n create: {\n before: async (user) => ({ data: { ...user, image: null } })\n },\n update: {\n // Better Auth merges what a hook returns into the update, so `image` is unset.\n before: async (user) =>\n user.image === undefined ? true : { data: { image: undefined } }\n }\n },\n account: {\n create: { after: keep },\n update: { after: keep }\n }\n }\n }\n })\n }\n}\n","import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'\nimport type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize } from 'image-size'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\n/** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */\nexport const PICTURE_PATH = '/api/pictures'\n/** The longest side a stored picture may have; pages send 256 pixels. */\nconst PICTURE_MAX_SIDE = 1024\n/** How many hex digits of the checksum name a picture in its address. */\nconst PICTURE_VERSION_LENGTH = 16\n/** How long a linked account's picture may take to fetch before sign-in goes on without it. */\nconst PROVIDER_PICTURE_TIMEOUT_MS = 5000\n/** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */\nconst PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']\nconst PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }\nconst userIdSchema = v.pipe(v.string(), v.uuid())\n\n/** The bytes are not a PNG or JPEG picture the server keeps. */\nexport class PictureInvalidError extends Error {\n constructor() {\n super('The picture must be a PNG or JPEG image of at most 1024 by 1024 pixels')\n this.name = 'PictureInvalidError'\n }\n}\n\n/** The format of a picture the server keeps, read from its bytes; anything else is null. */\nexport function pictureFormat(bytes: Uint8Array): UserPictureFormat | null {\n if (bytes.byteLength === 0 || bytes.byteLength > CLOUD_PICTURE_MAX_BYTES) return null\n try {\n const size = imageSize(bytes)\n const format = size.type ? PICTURE_FORMATS[size.type] : undefined\n if (!format || size.width < 1 || size.height < 1) return null\n if (size.width > PICTURE_MAX_SIDE || size.height > PICTURE_MAX_SIDE) return null\n return format\n } catch {\n return null\n }\n}\n\n/** Whether `url` is an HTTPS address on a host a linked account's picture comes from. */\nfunction providerPicture(url: URL): boolean {\n return (\n url.protocol === 'https:' &&\n PROVIDER_PICTURE_HOSTS.some(\n (host) => url.hostname === host || url.hostname.endsWith(`.${host}`)\n )\n )\n}\n\n/** Reads at most `limit` bytes of a response body, or null when it holds more. */\nasync function boundedBody(response: Response, limit: number): Promise<Uint8Array | null> {\n if (!response.body) return null\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n length += value.byteLength\n if (length > limit) {\n await reader.cancel()\n return null\n }\n chunks.push(value)\n }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return bytes\n}\n\ntype AccountPicture = { image: string | null; updatedAt: Date }\n\nfunction samePicture(current: AccountPicture | undefined, seen: AccountPicture | undefined) {\n return (\n current?.image === seen?.image && current?.updatedAt.getTime() === seen?.updatedAt.getTime()\n )\n}\n\nexport type UserPictureOptions = {\n publicURL: string\n /** Fetches a linked account's picture; tests pass their own. */\n fetch?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * The picture each account shows. The server keeps the bytes and serves them itself, so a page\n * that shows a person never asks another service for them; `user.image` holds their address.\n */\nexport function createUserPictures(database: Kysely<CloudDatabase>, options: UserPictureOptions) {\n const fetchPicture = options.fetch ?? ((url, init) => fetch(url, init))\n const origin = new URL(options.publicURL).origin\n\n function address(userId: string, checksum: string): string {\n return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`\n }\n\n /** The address `bytes` are served from as the account's picture. */\n function pictureAddress(userId: string, bytes: Uint8Array): string {\n return address(userId, bytesToHex(sha256(bytes)))\n }\n\n /** Whether `image` is a picture this server serves, rather than another service's. */\n function served(image: string): boolean {\n return image.startsWith(`${origin}${PICTURE_PATH}/`)\n }\n\n /**\n * Keeps `bytes` as the account's picture. A provider's picture is kept only while the account is\n * unchanged since `seen`, read before the picture was fetched: every upload and removal moves\n * `updatedAt`, so one made meanwhile stands, even one that left the image as it was. Returns\n * whether the picture was kept.\n */\n async function save(\n userId: string,\n bytes: Uint8Array,\n source: { from: 'upload' } | { from: 'provider'; seen: AccountPicture | undefined }\n ): Promise<boolean> {\n const format = pictureFormat(bytes)\n if (!format) throw new PictureInvalidError()\n const checksum = bytesToHex(sha256(bytes))\n const image = pictureAddress(userId, bytes)\n const createdAt = new Date()\n return database.transaction().execute(async (transaction) => {\n // Saves and removals lock the account first, so they take turns.\n const current = await transaction\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirst()\n if (source.from === 'provider' && !samePicture(current, source.seen)) return false\n await transaction\n .insertInto('userPicture')\n .values({ userId, bytes, format, checksum, source: source.from, createdAt })\n .onConflict((conflict) =>\n conflict\n .column('userId')\n .doUpdateSet({ bytes, format, checksum, source: source.from, createdAt })\n )\n .execute()\n await transaction\n .updateTable('user')\n .set({ image, updatedAt: createdAt })\n .where('id', '=', userId)\n .execute()\n return true\n })\n }\n\n async function remove(userId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n // The account first, in the same order saves lock, so the two never wait on each other.\n await transaction\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .forUpdate()\n .execute()\n await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n })\n }\n\n return {\n served,\n\n /** Keeps a picture the account's owner uploaded and shows it from now on. */\n async upload(userId: string, bytes: Uint8Array): Promise<string> {\n await save(userId, bytes, { from: 'upload' })\n return pictureAddress(userId, bytes)\n },\n\n /** Goes back to initials. */\n remove,\n\n /** The picture at `/api/pictures/:userId/:version`, or null for any other address. */\n async read(userId: string, version: string) {\n if (!v.is(userIdSchema, userId) || version.length !== PICTURE_VERSION_LENGTH) return null\n const picture = await database\n .selectFrom('userPicture')\n .select(['bytes', 'format', 'checksum'])\n .where('userId', '=', userId)\n .executeTakeFirst()\n return picture?.checksum.startsWith(version) ? picture : null\n },\n\n /**\n * Keeps the picture a linked account named in `image` and shows it instead, so pages never\n * load it from that service. A picture that cannot be fetched or is not one the server keeps\n * leaves initials in its place. An uploaded picture stays.\n */\n async copyFromProvider(userId: string, image: string): Promise<void> {\n if (served(image)) return\n // A picture the account already shows from this server, uploaded or kept before, stays.\n const current = await database\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .executeTakeFirst()\n if (current?.image && served(current.image)) return\n try {\n if (!providerPicture(new URL(image))) throw new PictureInvalidError()\n const response = await fetchPicture(image, {\n redirect: 'error',\n signal: AbortSignal.timeout(PROVIDER_PICTURE_TIMEOUT_MS)\n })\n const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null\n if (!bytes) throw new PictureInvalidError()\n await save(userId, bytes, { from: 'provider', seen: current })\n } catch (error) {\n console.warn('Keeping a linked account picture failed', error)\n await database\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .where('image', '=', image)\n .execute()\n }\n }\n }\n}\n\nexport type UserPictureService = ReturnType<typeof createUserPictures>\n","import { Hono } from 'hono'\n\nimport { PICTURE_PATH, type UserPictureService } from './service'\n\n/**\n * Account pictures, for anyone with a picture's address: pages show people to those they share\n * documents and workspaces with, and the desktop app shows them from another origin.\n */\nexport function createPictureRoutes(pictures: UserPictureService) {\n return new Hono().get(`${PICTURE_PATH}/:userId/:version`, async (context) => {\n const picture = await pictures.read(context.req.param('userId'), context.req.param('version'))\n if (!picture) return context.json({ error: { code: 'not_found' as const } }, 404)\n // The address changes with the picture, but a removed one must stop showing within a day.\n context.header('Cache-Control', 'public, max-age=86400')\n context.header('Content-Type', `image/${picture.format}`)\n context.header('X-Content-Type-Options', 'nosniff')\n context.header('Content-Security-Policy', \"default-src 'none'; sandbox\")\n context.header('Cross-Origin-Resource-Policy', 'cross-origin')\n return context.body(new Uint8Array(picture.bytes))\n })\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { BetterAuthOptions } from 'better-auth'\nimport { importPKCS8, SignJWT } from 'jose'\n\n/** The audience Apple's sign-in tokens carry, which the server also trusts as an origin. */\nexport const APPLE_AUDIENCE = 'https://appleid.apple.com'\nconst APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60\nasync function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {\n if (\n !config.appleClientId ||\n !config.appleTeamId ||\n !config.appleKeyId ||\n !config.applePrivateKey\n ) {\n throw new Error('Apple authentication is not configured')\n }\n const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\\\n', '\\n'), 'ES256')\n const issuedAt = Math.floor(Date.now() / 1000)\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })\n .setIssuer(config.appleTeamId)\n .setSubject(config.appleClientId)\n .setAudience(APPLE_AUDIENCE)\n .setIssuedAt(issuedAt)\n .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)\n .sign(privateKey)\n}\n\n/** The sign-in providers the deployment configures; Apple's secret is signed when it is needed. */\nexport function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {\n const providers: BetterAuthOptions['socialProviders'] = {}\n if (config.googleClientId && config.googleClientSecret) {\n providers.google = {\n clientId: config.googleClientId,\n clientSecret: config.googleClientSecret\n }\n }\n if (config.appleClientId) {\n providers.apple = async () => {\n const provider: {\n clientId: string\n clientSecret: string\n appBundleIdentifier?: string\n } = {\n clientId: config.appleClientId ?? '',\n clientSecret: await generateAppleClientSecret(config)\n }\n if (config.appleAppBundleIdentifier) {\n provider.appBundleIdentifier = config.appleAppBundleIdentifier\n }\n return provider\n }\n }\n return providers\n}\n","import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createUserPictures, providerPictures } from '#cloud/server/pictures'\nimport { passkey } from '@better-auth/passkey'\nimport { APIError, betterAuth } from 'better-auth'\nimport { getMigrations } from 'better-auth/db/migration'\nimport {\n admin,\n bearer,\n captcha,\n deviceAuthorization,\n haveIBeenPwned,\n twoFactor\n} from 'better-auth/plugins'\nimport type { Kysely } from 'kysely'\n\nimport { accountActivity, createSignInActivity } from './activity'\nimport type { CloudAuthAdapter } from './adapter'\nimport type { AuthenticationEmailService } from './email'\nimport { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'\nimport { createMFAAssuranceService } from './mfa-assurance'\nimport { APPLE_AUDIENCE, socialProviders } from './social-providers'\n\nconst BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'\nconst ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60\n\nasync function recordResponseAssurance(\n response: Response,\n method: 'totp' | 'recovery-code' | 'passkey',\n database: Kysely<CloudDatabase>,\n assurance: ReturnType<typeof createMFAAssuranceService>\n): Promise<void> {\n const signedToken = response.headers.get('set-auth-token')\n const token = signedToken?.split('.', 1)[0]\n if (!token) return\n const session = await database\n .selectFrom('session')\n .select(['id', 'userId'])\n .where('token', '=', token)\n .executeTakeFirst()\n if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })\n}\n\nasync function verifySecondFactor(\n auth: { handler(request: Request): Promise<Response> },\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n assurance: ReturnType<typeof createMFAAssuranceService>,\n headers: Headers,\n code: string,\n method: 'totp' | 'recovery-code',\n /** The two-step plugin's endpoint that checks this kind of code. */\n endpoint: { path: string }\n): Promise<Response> {\n const response = await auth.handler(\n new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {\n method: 'POST',\n headers: new Headers({\n ...Object.fromEntries(headers),\n 'Content-Type': 'application/json'\n }),\n body: JSON.stringify({ code, trustDevice: false })\n })\n )\n if (!response.ok) throw APIError.fromStatus(response.status as 401)\n await recordResponseAssurance(response, method, database, assurance)\n return response\n}\n\nexport type CloudAuthRuntimeOptions = {\n email?: AuthenticationEmailService\n runInBackground?: (promise: Promise<unknown>) => void\n /**\n * Whether Better Auth checks the database schema when it starts. Runtimes that start it for\n * every request turn this off; `migrateCloudDatabase` has already checked the recorded version.\n */\n validateSchema?: boolean\n}\n\nexport function createBetterAuthAdapter(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n enrollment: EnrollmentService = createEnrollmentService(database),\n runtime: CloudAuthRuntimeOptions = {}\n): CloudAuthAdapter {\n const authenticationEmail = runtime.email\n const assurance = createMFAAssuranceService(database, config)\n const activity = createSignInActivity(database, authenticationEmail)\n // A new address is confirmed through a link sent to it, so changing one needs email delivery.\n const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)\n // The plugins are built first, so the options below name their endpoints by the paths they declare.\n const twoStep = twoFactor({\n issuer: 'OpenPencil Cloud',\n trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,\n allowPasswordless: true,\n totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },\n backupCodeOptions: {\n disable: !config.totpEnabled || !config.recoveryCodesEnabled,\n storeBackupCodes: 'encrypted'\n }\n })\n const passkeys = passkey({\n rpID: new URL(config.publicURL).hostname,\n rpName: config.passkeyRPName,\n origin: new URL(config.publicURL).origin\n })\n const devices = deviceAuthorization({\n verificationUri: new URL('/auth/device', config.publicURL).href,\n validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')\n })\n const administration = admin()\n const auth = betterAuth({\n appName: 'OpenPencil Cloud',\n baseURL: config.publicURL,\n basePath: AUTH_BASE_PATH,\n // Clients never reach Better Auth's own administration, which `/api/admin` replaces with MFA,\n // origin, last-administrator, and audit checks, nor the two endpoints Cloud's policy manages\n // through its account routes; the server still calls them itself.\n disabledPaths: [\n ...Object.values(administration.endpoints).map((endpoint) => endpoint.path),\n passkeys.endpoints.deletePasskey.path,\n twoStep.endpoints.disableTwoFactor.path\n ],\n secret: config.authSecret,\n database: {\n db: database,\n type: 'postgres',\n casing: 'camel',\n transaction: true\n },\n account: {\n accountLinking: {\n enabled: true,\n disableImplicitLinking: false,\n trustedProviders: ['google', 'apple'],\n allowDifferentEmails: false,\n allowUnlinkingAll: false,\n requireLocalEmailVerified: true\n }\n },\n session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },\n advanced: {\n database: { generateId: 'uuid', validateSchema: runtime.validateSchema },\n ipAddress: {\n ipAddressHeaders: config.authTrustedIPHeaders,\n trustedProxies: config.authTrustedProxies\n },\n ...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})\n },\n rateLimit: {\n enabled: true,\n storage: 'database',\n window: 60,\n max: 100,\n customRules: {\n [devices.endpoints.deviceCode.path]: { window: 60, max: 10 },\n [devices.endpoints.deviceToken.path]: { window: 60, max: 60 },\n [devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },\n [devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },\n [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },\n [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }\n }\n },\n emailAndPassword: config.emailPasswordEnabled\n ? {\n enabled: true,\n disableSignUp: !config.emailPasswordSignUpEnabled,\n requireEmailVerification: true,\n minPasswordLength: config.emailPasswordMinimumLength,\n maxPasswordLength: config.emailPasswordMaximumLength,\n autoSignIn: false,\n resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,\n revokeSessionsOnPasswordReset: true,\n sendResetPassword: authenticationEmail\n ? ({ user, url, token }) =>\n authenticationEmail.sendPasswordReset({\n email: user.email,\n name: user.name,\n url,\n token\n })\n : undefined,\n onPasswordReset: authenticationEmail\n ? ({ user }) =>\n authenticationEmail.sendPasswordChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n url: config.publicURL\n })\n : undefined\n }\n : undefined,\n emailVerification:\n config.emailPasswordEnabled && authenticationEmail\n ? {\n expiresIn: config.emailVerificationExpiresIn,\n sendOnSignUp: true,\n // Signing in unverified only says so; people ask for another link with Send again.\n sendOnSignIn: false,\n autoSignInAfterVerification: true,\n // A change of address sends the link to the new address as `user.email`, on the\n // account it already confirmed; a new account has not confirmed one yet. This runs\n // inside sign-up's transaction, so it must not query the database itself.\n sendVerificationEmail: ({ user, url, token }) =>\n authenticationEmail.sendVerification({\n email: user.email,\n name: user.name,\n url,\n token,\n purpose: user.emailVerified ? 'change' : 'account'\n }),\n afterEmailVerification: async (user) => {\n await enrollment.followEmailChange(user.id, user.email)\n if (config.enrollmentMode === 'approval') {\n await enrollment.request({ email: user.email, name: user.name })\n }\n await enrollment.bindApprovedUser(user.email, user.id)\n }\n }\n : undefined,\n user: {\n changeEmail: { enabled: emailChangeAvailable },\n validateUserInfo: ({ source }) => {\n if (source.action === 'create-user' && config.enrollmentMode === 'closed') {\n return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }\n }\n return undefined\n }\n },\n databaseHooks: {\n user: {\n create: {\n after: async (user) => {\n if (!user.emailVerified) return\n if (config.enrollmentMode === 'approval') {\n await enrollment.request({ email: user.email, name: user.name })\n }\n await enrollment.bindApprovedUser(user.email, user.id)\n }\n }\n }\n },\n plugins: [\n ...(config.captchaProvider && config.captchaSecretKey\n ? [\n captcha({\n provider: config.captchaProvider,\n secretKey: config.captchaSecretKey,\n allowedHostnames: config.captchaAllowedHostnames,\n endpoints: [\n CORE_AUTH_PATHS.signUpEmail,\n CORE_AUTH_PATHS.signInEmail,\n CORE_AUTH_PATHS.requestPasswordReset\n ]\n })\n ]\n : []),\n ...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),\n twoStep,\n passkeys,\n administration,\n // Device authorization returns opaque database session tokens, not signed cookies.\n bearer(),\n devices,\n // After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.\n accountActivity(\n activity,\n { twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },\n (user) => notifyTwoStep(user, 'passkey-added')\n ),\n providerPictures(createUserPictures(database, { publicURL: config.publicURL }))\n ],\n socialProviders: socialProviders(config),\n trustedOrigins: [\n config.publicURL,\n ...config.trustedOrigins,\n ...(config.appleClientId ? [APPLE_AUDIENCE] : [])\n ]\n })\n\n // Administrators are granted only through the `admin` command or by another administrator.\n const deploymentRole = (user: { id: string; role?: string | null }) =>\n user.role === 'admin' ? ('admin' as const) : ('user' as const)\n\n const resolveIdentity = async (headers: Headers) => {\n const session = await auth.api.getSession({ headers })\n if (!session) return null\n return {\n userId: session.user.id,\n email: session.user.email,\n name: session.user.name,\n image: session.user.image ?? null,\n deploymentRole: deploymentRole(session.user)\n }\n }\n\n /** The signed-in person, read past the cookie cache, for changes about their own account. */\n const currentSession = (headers: Headers) =>\n auth.api.getSession({ headers, query: { disableCookieCache: true } })\n\n /** The current session when it signed in recently enough to change how the account is reached. */\n async function freshSession(headers: Headers) {\n const session = await currentSession(headers)\n const createdAt = session?.session.createdAt\n if (\n !session ||\n !createdAt ||\n Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000\n ) {\n throw APIError.from('FORBIDDEN', {\n code: 'SESSION_NOT_FRESH',\n message: 'Session is not fresh'\n })\n }\n return session\n }\n\n async function notifyTwoStep(\n user: { id: string; email: string; name: string },\n change: Parameters<AuthenticationEmailService['sendTwoStepChanged']>[0]['change']\n ): Promise<void> {\n await authenticationEmail?.sendTwoStepChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n change\n })\n }\n\n /** The signed-in person while their account may use the server, which awaiting approval it may not. */\n async function resolveSession(headers: Headers) {\n const identity = await resolveIdentity(headers)\n if (!identity) return null\n if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {\n return null\n }\n return identity\n }\n\n /**\n * The endpoints that read or change an account, which only an account that may use the server\n * reaches; one awaiting approval still signs in and out. Better Auth checks the session inside\n * most of these endpoints rather than declaring it, so they are listed by their own objects.\n */\n const activeAccountPaths = new Set(\n [\n auth.api.generatePasskeyRegistrationOptions,\n auth.api.listPasskeys,\n auth.api.updatePasskey,\n auth.api.verifyPasskeyRegistration,\n auth.api.enableTwoFactor,\n auth.api.generateBackupCodes,\n auth.api.getTOTPURI,\n auth.api.accountInfo,\n auth.api.changeEmail,\n auth.api.changePassword,\n auth.api.deleteUser,\n auth.api.getAccessToken,\n auth.api.linkSocialAccount,\n auth.api.listUserAccounts,\n auth.api.listSessions,\n auth.api.refreshToken,\n auth.api.revokeOtherSessions,\n auth.api.revokeSession,\n auth.api.revokeSessions,\n auth.api.unlinkAccount\n ].map((endpoint) => authRequestPath(endpoint.path))\n )\n /** The second factor a request proves, by the endpoint it is for. */\n const assuranceMethods = new Map<string, 'totp' | 'recovery-code' | 'passkey'>([\n [authRequestPath(twoStep.endpoints.verifyTOTP.path), 'totp'],\n [authRequestPath(twoStep.endpoints.verifyBackupCode.path), 'recovery-code'],\n [authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path), 'passkey']\n ])\n\n return {\n handler: async (request) => {\n const path = new URL(request.url).pathname\n if (activeAccountPaths.has(path) && !(await resolveSession(request.headers))) {\n return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })\n }\n const response = await auth.handler(request)\n const method = assuranceMethods.get(path)\n if (response.ok && method)\n await recordResponseAssurance(response, method, database, assurance)\n return response\n },\n resolveIdentity,\n resolveSession,\n async listAuthenticationMethods(headers) {\n const accounts = await auth.api.listUserAccounts({ headers })\n return accounts.map((account) => ({\n id: account.id,\n providerId: account.providerId,\n createdAt: account.createdAt\n }))\n },\n async changePassword(headers, input) {\n const session = authenticationEmail ? await auth.api.getSession({ headers }) : null\n await auth.api.changePassword({\n headers,\n body: { ...input, revokeOtherSessions: false }\n })\n await auth.api.revokeOtherSessions({ headers })\n if (authenticationEmail && session) {\n await authenticationEmail.sendPasswordChanged({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n url: config.publicURL\n })\n }\n },\n async startSocialLink(headers, input) {\n await freshSession(headers)\n const response = await auth.api.linkSocialAccount({\n headers,\n body: {\n provider: input.provider,\n callbackURL: input.callbackURL,\n errorCallbackURL: input.callbackURL,\n disableRedirect: true\n }\n })\n return response.url\n },\n async unlinkAuthenticationMethod(headers, methodId) {\n await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })\n },\n async banUser(headers, userId, reason) {\n await auth.api.banUser({ headers, body: { userId, banReason: reason } })\n },\n async unbanUser(headers, userId) {\n await auth.api.unbanUser({ headers, body: { userId } })\n },\n async revokeUserSessions(headers, userId) {\n await auth.api.revokeUserSessions({ headers, body: { userId } })\n },\n async setRole(headers, userId, role) {\n await auth.api.setRole({ headers, body: { userId, role } })\n },\n async mfaStatus(headers) {\n const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })\n if (!session) return null\n const passkeys = await auth.api.listPasskeys({ headers })\n return assurance.status({\n sessionId: session.session.id,\n userId: session.user.id,\n deploymentRole: deploymentRole(session.user),\n twoFactorEnabled:\n 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true,\n passkeyCount: passkeys.length\n })\n },\n async enableTOTP(headers, password) {\n const response = await auth.api.enableTwoFactor({\n headers,\n body: { password, method: 'totp' }\n })\n if (response.method !== 'totp') throw new Error('TOTP setup was unavailable')\n return { totpURI: response.totpURI, backupCodes: response.backupCodes }\n },\n async verifyTOTP(headers, code) {\n const before = await currentSession(headers)\n const response = await verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'totp',\n twoStep.endpoints.verifyTOTP\n )\n // The first code from a new authenticator is what turns it on.\n if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {\n await notifyTwoStep(before.user, 'authenticator-on')\n }\n return response\n },\n async verifyRecoveryCode(headers, code) {\n return verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'recovery-code',\n twoStep.endpoints.verifyBackupCode\n )\n },\n async generateRecoveryCodes(headers, password) {\n return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes\n },\n async disableTOTP(headers, password) {\n await auth.api.disableTwoFactor({ headers, body: { password } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'authenticator-off')\n },\n async listPasskeys(headers) {\n return (await auth.api.listPasskeys({ headers })).map((item) => ({\n id: item.id,\n name: item.name,\n createdAt: item.createdAt\n }))\n },\n async deletePasskey(headers, id) {\n await auth.api.deletePasskey({ headers, body: { id } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'passkey-removed')\n },\n emailChangeAvailable,\n async profile(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return {\n id: session.user.id,\n name: session.user.name,\n email: session.user.email,\n image: session.user.image ?? null,\n createdAt: new Date(session.user.createdAt)\n }\n },\n async updateProfile(headers, input) {\n await auth.api.updateUser({ headers, body: { name: input.name } })\n },\n async changeEmail(headers, input) {\n const session = await freshSession(headers)\n if (session.user.email === input.newEmail) {\n throw APIError.from('BAD_REQUEST', {\n code: 'EMAIL_UNCHANGED',\n message: 'Email is the same'\n })\n }\n await auth.api.changeEmail({ headers, body: input })\n await authenticationEmail?.sendEmailChangeRequested({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n newEmail: input.newEmail\n })\n },\n async sessions(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return activity.sessions(session.user.id, session.session.id)\n },\n async revokeSession(headers, sessionId) {\n const session = await currentSession(headers)\n if (!session) throw APIError.fromStatus('UNAUTHORIZED')\n if (session.session.id === sessionId) {\n throw APIError.from('BAD_REQUEST', {\n code: 'CURRENT_SESSION',\n message: 'Sign out to end this session'\n })\n }\n const target = await database\n .selectFrom('session')\n .select('token')\n .where('id', '=', sessionId)\n .where('userId', '=', session.user.id)\n .executeTakeFirst()\n if (target) await auth.api.revokeSession({ headers, body: { token: target.token } })\n },\n async revokeOtherSessions(headers) {\n await auth.api.revokeOtherSessions({ headers })\n },\n async signIns(headers) {\n const session = await currentSession(headers)\n return session ? activity.signIns(session.user.id) : null\n },\n schemaVersion: BETTER_AUTH_SCHEMA_VERSION,\n async migrate() {\n const migrations = await getMigrations(auth.options)\n await migrations.runMigrations()\n }\n }\n}\n","import { createEnrollmentService } from '#cloud/admin/enrollment/service'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\nimport { createAuthenticationEmailService } from './email'\nimport { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'\n\nexport function createCloudAuthenticationRuntime(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n email: TransactionalEmailService,\n options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}\n) {\n const enrollment = createEnrollmentService(database, {\n publicURL: config.publicURL,\n adminRecipients: config.enrollmentAdminNotificationEmails,\n email\n })\n const auth = createBetterAuthAdapter(config, database, enrollment, {\n email: createAuthenticationEmailService(email, config.publicURL),\n ...options\n })\n return { auth, enrollment }\n}\n","import type { CloudAuthAdapter, CloudIdentity } from '#cloud/server/auth/adapter'\n\nexport type CloudActor = {\n userId: string\n email: string\n name: string\n deploymentRole?: 'user' | 'admin'\n}\n\nexport type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>\nexport type CloudSessionResolver = (request: Request) => Promise<CloudActor | null>\n\nexport function createCloudIdentityResolver(auth: CloudAuthAdapter): CloudIdentityResolver {\n return (request) => auth.resolveIdentity(request.headers)\n}\n\nexport function createCloudSessionResolver(auth: CloudAuthAdapter): CloudSessionResolver {\n return (request) => auth.resolveSession(request.headers)\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport {\n cloudAdminUserFilterSchema,\n type CloudAdminUser,\n type CloudAdminUserDetail,\n type CloudAdminUserFilter\n} from '#cloud/contract'\nimport {\n createSignInActivity,\n type AuthenticationEmailService,\n type CloudAuthAdapter\n} from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { UserPictureService } from '#cloud/server/pictures'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { countBy, keyBy } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\n/** The sign-ins a person's page lists. */\nconst DETAIL_SIGN_INS = 20\n\ntype UserExpression = ExpressionBuilder<CloudDatabase, 'user'>\n\n/** A search for part of a name or email, matched literally and without case. */\nfunction searchCondition(search: string) {\n const pattern = containsPattern(search)\n return (expression: UserExpression) =>\n expression.or([\n expression('user.email', 'ilike', pattern),\n expression('user.name', 'ilike', pattern)\n ])\n}\n\nconst FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {\n all: (expression) => expression.lit(true),\n administrators: (expression) => expression('user.role', '=', 'admin'),\n suspended: (expression) => expression('user.banned', '=', true),\n 'without-two-step': (expression) =>\n expression.and([\n // Better Auth leaves the flag unset on accounts that never turned it on.\n expression('user.twoFactorEnabled', 'is not', true),\n expression.not(\n expression.exists(\n expression\n .selectFrom('passkey')\n .select('passkey.id')\n .whereRef('passkey.userId', '=', 'user.id')\n )\n )\n ])\n}\n\nexport type AdminUserQuery = AdminListQuery<CloudAdminUserFilter>\n\ntype UserRow = {\n id: string\n name: string\n email: string\n image: string | null\n role: string | null\n banned: boolean | null\n banReason: string | null\n twoFactorEnabled: boolean | null\n createdAt: Date | string\n}\n\nexport function createAdminUserService(\n database: Kysely<CloudDatabase>,\n auth: CloudAuthAdapter,\n options: {\n requireMFA?: boolean\n notify?: AuthenticationEmailService\n /** Takes down a person's picture; without it, `removePicture` refuses. */\n pictures?: UserPictureService\n } = {}\n) {\n const activity = createSignInActivity(database)\n\n async function audit(\n actorId: string,\n action: string,\n userId: string,\n metadata: Record<string, unknown> = {}\n ): Promise<void> {\n await database\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action,\n subjectType: 'user',\n subjectId: userId,\n metadata\n })\n .execute()\n }\n\n function refuseSelf(actorId: string, userId: string, action: string): void {\n if (actorId === userId) {\n throw new AdminDomainError(\n 'self_admin_action_forbidden',\n `Administrators cannot ${action} themselves`\n )\n }\n }\n\n async function requireSafeTarget(\n actorId: string,\n userId: string,\n action: 'ban' | 'demote'\n ): Promise<void> {\n refuseSelf(actorId, userId, action)\n const target = await database\n .selectFrom('user')\n .select('role')\n .where('id', '=', userId)\n .executeTakeFirst()\n if (target?.role !== 'admin') return\n const count = await database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('role', '=', 'admin')\n .where((expression) =>\n expression.or([expression('banned', '=', false), expression('banned', 'is', null)])\n )\n .executeTakeFirstOrThrow()\n if (Number(count.count) <= 1) {\n throw new AdminDomainError(\n 'last_admin_required',\n 'Cannot remove the last deployment administrator'\n )\n }\n }\n\n /** What the list shows about each account beyond its own row. */\n async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {\n const ids = rows.map((row) => row.id)\n if (ids.length === 0) return []\n const [passkeys, sessions, memberships] = await Promise.all([\n database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),\n database\n .selectFrom('session')\n .select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])\n .where('session.userId', 'in', ids)\n .where('session.expiresAt', '>', new Date())\n .groupBy('session.userId')\n .execute(),\n database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute()\n ])\n const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))\n const lastActive = keyBy(sessions, (session) => session.userId)\n const workspaceCounts = countBy(memberships, (membership) => membership.userId)\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n email: row.email,\n image: row.image,\n role: row.role ?? undefined,\n banned: row.banned,\n banReason: row.banReason,\n createdAt: dateString(row.createdAt) ?? '',\n twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),\n lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),\n workspaceCount: workspaceCounts[row.id] ?? 0\n }))\n }\n\n const userColumns = [\n 'user.id',\n 'user.name',\n 'user.email',\n 'user.image',\n 'user.role',\n 'user.banned',\n 'user.banReason',\n 'user.twoFactorEnabled',\n 'user.emailVerified',\n 'user.createdAt'\n ] as const\n\n return {\n /** A page of accounts in sign-up order, with how many match the search under each filter. */\n async list(query: AdminUserQuery = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('user')\n if (search) searched = searched.where(searchCondition(search))\n const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select(userColumns)\n .orderBy('user.createdAt')\n .orderBy('user.id')\n .limit(limit)\n .offset(offset)\n .execute()\n return { users: await accountSummaries(rows), total: counts[filter], counts }\n },\n\n /** Everything an administrator reads about one account; null when there is none. */\n async detail(userId: string): Promise<CloudAdminUserDetail | null> {\n const row = await database\n .selectFrom('user')\n .select(userColumns)\n .where('user.id', '=', userId)\n .executeTakeFirst()\n if (!row) return null\n const [[summary], methods, passkeys, sessions, signIns, workspaces] = await Promise.all([\n accountSummaries([row]),\n database\n .selectFrom('account')\n .select(['providerId', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt')\n .execute(),\n database\n .selectFrom('passkey')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('userId', '=', userId)\n .executeTakeFirstOrThrow(),\n activity.sessions(userId, ''),\n activity.signIns(userId, DETAIL_SIGN_INS),\n database\n .selectFrom('workspaceMember')\n .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')\n .select((expression) => [\n 'workspace.id',\n 'workspace.name',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n expression\n .selectFrom('workspaceMember as member')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .whereRef('member.workspaceId', '=', 'workspace.id')\n .as('memberCount')\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspaceMember.createdAt')\n .execute()\n ])\n if (!summary) return null\n return {\n user: { ...summary, emailVerified: row.emailVerified },\n methods: methods.map((method) => ({\n provider: method.providerId,\n createdAt: dateString(method.createdAt) ?? ''\n })),\n authenticator: row.twoFactorEnabled === true,\n passkeyCount: Number(passkeys.count),\n sessions,\n signIns,\n workspaces: workspaces.map((workspace) => ({\n id: workspace.id,\n name: workspace.name,\n role: workspace.role,\n memberCount: Number(workspace.memberCount ?? 0),\n joinedAt: dateString(workspace.createdAt) ?? ''\n }))\n }\n },\n\n async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {\n await requireSafeTarget(actorId, userId, 'ban')\n await auth.banUser(headers, userId, reason)\n await audit(actorId, 'user.banned', userId, reason ? { reason } : {})\n },\n async unban(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.unbanUser(headers, userId)\n await audit(actorId, 'user.unbanned', userId)\n },\n async revokeSessions(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.revokeUserSessions(headers, userId)\n await audit(actorId, 'user.sessions-revoked', userId)\n },\n async setAdmin(\n headers: Headers,\n actorId: string,\n userId: string,\n enabled: boolean\n ): Promise<void> {\n if (!enabled) await requireSafeTarget(actorId, userId, 'demote')\n if (enabled && options.requireMFA) {\n const user = await database\n .selectFrom('user')\n .select('twoFactorEnabled')\n .where('id', '=', userId)\n .executeTakeFirst()\n const passkey = await database\n .selectFrom('passkey')\n .select('id')\n .where('userId', '=', userId)\n .executeTakeFirst()\n if (!user?.twoFactorEnabled && !passkey) {\n throw new AdminDomainError(\n 'mfa_required',\n 'Users must enroll MFA before becoming deployment administrators'\n )\n }\n }\n await auth.setRole(headers, userId, enabled ? 'admin' : 'user')\n await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)\n },\n\n /**\n * Removes an account's authenticator app, recovery codes, and passkeys, for someone who lost\n * them; they sign in with their password or a linked account and set them up again.\n */\n async resetTwoStep(actorId: string, userId: string): Promise<void> {\n refuseSelf(actorId, userId, 'reset two-step sign-in for')\n const user = await database.transaction().execute(async (transaction) => {\n const target = await transaction\n .selectFrom('user')\n .select(['id', 'email', 'name'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n await transaction.deleteFrom('twoFactor').where('userId', '=', userId).execute()\n await transaction.deleteFrom('passkey').where('userId', '=', userId).execute()\n await transaction.deleteFrom('mfaAssurance').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ twoFactorEnabled: false, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'user.two-step-reset',\n subjectType: 'user',\n subjectId: userId,\n metadata: {}\n })\n .execute()\n return target\n })\n await options.notify?.sendTwoStepChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n change: 'reset-by-administrator'\n })\n },\n\n /** Takes down a person's picture, such as one that should not be shown; initials replace it. */\n async removePicture(actorId: string, userId: string): Promise<void> {\n if (!options.pictures) throw new Error('Pictures are not available')\n await database\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .executeTakeFirstOrThrow()\n await options.pictures.remove(userId)\n await audit(actorId, 'user.picture-removed', userId)\n }\n }\n}\n\nexport type AdminUserService = ReturnType<typeof createAdminUserService>\n","/** The workspace's plan does not include the AI service. */\nexport class AINotEntitledError extends Error {\n constructor() {\n super('The workspace is not entitled to the AI service')\n this.name = 'AINotEntitledError'\n }\n}\n","import { CloudConfigError, type CloudServerConfig } from '#cloud/server/config/schema'\nimport { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK } from 'jose'\n\nconst ALGORITHM = 'ES256'\n\nexport type AISigningKey = {\n privateKey: CryptoKey\n /** The public half, as published in the JWKS. */\n publicJWK: JWK & { kid: string }\n}\n\n/**\n * Imports the P-256 key that signs AI service tokens. Its `kid` is the public key's thumbprint,\n * so replacing the key changes the `kid`, and a service that caches the JWKS refetches it on the\n * first token it cannot match. Tokens the old key signed fail once and are re-requested.\n */\nexport async function importAISigningKey(pem: string): Promise<AISigningKey> {\n const privateKey = await importPKCS8(pem, ALGORITHM, { extractable: true })\n const { kty, crv, x, y } = await exportJWK(privateKey)\n const publicJWK = { kty, crv, x, y }\n const kid = await calculateJwkThumbprint(publicJWK)\n return {\n privateKey: await importPKCS8(pem, ALGORITHM),\n publicJWK: { ...publicJWK, kid, alg: ALGORITHM, use: 'sig' }\n }\n}\n\n/**\n * Imports the configured signing key at startup, so a key that cannot sign stops the runtime\n * instead of failing every token request after discovery has advertised the AI service.\n */\nexport async function loadAISigningKey(\n config: Pick<CloudServerConfig, 'aiSigningKey'>\n): Promise<AISigningKey | undefined> {\n if (!config.aiSigningKey) return undefined\n try {\n return await importAISigningKey(config.aiSigningKey)\n } catch {\n throw new CloudConfigError('AI signing key must be a PKCS #8 P-256 private key')\n }\n}\n\nexport const AI_SIGNING_ALGORITHM = ALGORITHM\n","import type {\n DocumentAccess,\n DocumentAccessSource,\n DocumentPermission,\n WorkspaceRole\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { maxBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type AccessDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nconst PERMISSION_WEIGHT: Record<DocumentPermission, number> = { view: 1, edit: 2 }\n\nfunction workspacePermission(role: WorkspaceRole): DocumentPermission {\n return role === 'viewer' ? 'view' : 'edit'\n}\n\nexport async function resolveDocumentAccess(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<DocumentAccess | undefined> {\n const document = await database\n .selectFrom('document')\n .leftJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .leftJoin('documentGrant', (join) =>\n join\n .onRef('documentGrant.documentId', '=', 'document.id')\n .on('documentGrant.userId', '=', userId)\n .on('documentGrant.revokedAt', 'is', null)\n )\n .select([\n 'document.createdBy',\n 'workspaceMember.role as workspaceRole',\n 'documentGrant.permission as grantPermission'\n ])\n .where('document.id', '=', documentId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) return undefined\n\n const sources: DocumentAccessSource[] = []\n const candidates: DocumentPermission[] = []\n const owner = document.createdBy === userId\n if (owner) {\n sources.push('owner')\n candidates.push('edit')\n }\n if (document.workspaceRole) {\n sources.push('workspace')\n candidates.push(workspacePermission(document.workspaceRole))\n }\n if (document.grantPermission) {\n sources.push('direct-grant')\n candidates.push(document.grantPermission)\n }\n const permission = maxBy(candidates, (candidate) => PERMISSION_WEIGHT[candidate])\n if (!permission) return undefined\n const workspaceCanManage =\n document.workspaceRole === 'admin' || document.workspaceRole === 'editor'\n return {\n permission,\n canManageSharing: owner || workspaceCanManage || document.grantPermission === 'edit',\n sources\n }\n}\n\nexport function canEditDocument(access: DocumentAccess): boolean {\n return access.permission === 'edit'\n}\n\n/**\n * Removing a document belongs to its owner and its workspace's admins and editors. A direct grant\n * or an accepted invitation lets someone edit, never delete the owner's document.\n */\nexport async function canDeleteDocument(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<boolean> {\n const document = await database\n .selectFrom('document')\n .leftJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .select(['document.createdBy', 'workspaceMember.role as workspaceRole'])\n .where('document.id', '=', documentId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) return false\n return (\n document.createdBy === userId ||\n document.workspaceRole === 'admin' ||\n document.workspaceRole === 'editor'\n )\n}\n","/** The document does not exist, or the person may not know it does. */\nexport class DocumentNotFoundError extends Error {\n override readonly name = 'DocumentNotFoundError'\n}\n/** The person may see the document but not do this to it. */\nexport class DocumentForbiddenError extends Error {\n override readonly name = 'DocumentForbiddenError'\n}\n/** A save named a base revision the document has moved on from. */\nexport class DocumentConflictError extends Error {\n override readonly name = 'DocumentConflictError'\n}\n/** An upload is not the file it declared, or no longer one that can land. */\nexport class UploadInvalidError extends Error {\n override readonly name = 'UploadInvalidError'\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport class StorageQuotaExceededError extends Error {\n override readonly name = 'StorageQuotaExceededError'\n}\n\nexport type StorageQuotaSnapshot = {\n committedBytes: number\n reservedBytes: number\n}\n\ntype StorageDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport function createStorageQuotaService(database: Kysely<CloudDatabase>) {\n async function snapshot(\n executor: StorageDatabase,\n workspaceId: string,\n now = new Date()\n ): Promise<StorageQuotaSnapshot> {\n const [usage, reservation] = await Promise.all([\n executor\n .selectFrom('workspaceStorageUsage')\n .select('committedBytes')\n .where('workspaceId', '=', workspaceId)\n .executeTakeFirst(),\n executor\n .selectFrom('uploadStorageReservation')\n .select((expression) =>\n expression.fn.coalesce(expression.fn.sum('bytes'), expression.val(0)).as('reservedBytes')\n )\n .where('workspaceId', '=', workspaceId)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .where('expiresAt', '>', now)\n .executeTakeFirstOrThrow()\n ])\n return {\n committedBytes: Number(usage?.committedBytes ?? 0),\n reservedBytes: Number(reservation.reservedBytes)\n }\n }\n\n async function reserve(\n executor: StorageDatabase,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n await executor\n .insertInto('workspaceStorageUsage')\n .values({ workspaceId: input.workspaceId, committedBytes: 0 })\n .onConflict((conflict) => conflict.column('workspaceId').doNothing())\n .execute()\n await executor\n .selectFrom('workspaceStorageUsage')\n .select('workspaceId')\n .where('workspaceId', '=', input.workspaceId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const usage = await snapshot(executor, input.workspaceId)\n if (\n input.maximumBytes !== null &&\n usage.committedBytes + usage.reservedBytes + input.bytes > input.maximumBytes\n ) {\n throw new StorageQuotaExceededError('Workspace storage quota exceeded')\n }\n await executor\n .insertInto('uploadStorageReservation')\n .values({\n id: crypto.randomUUID(),\n workspaceId: input.workspaceId,\n uploadId: input.uploadId,\n bytes: input.bytes,\n expiresAt: input.expiresAt,\n committedAt: null,\n releasedAt: null\n })\n .onConflict((conflict) => conflict.column('uploadId').doNothing())\n .execute()\n }\n\n async function commit(executor: StorageDatabase, uploadId: string): Promise<void> {\n const reservation = await executor\n .selectFrom('uploadStorageReservation')\n .select(['id', 'workspaceId', 'bytes', 'committedAt', 'releasedAt'])\n .where('uploadId', '=', uploadId)\n .forUpdate()\n .executeTakeFirst()\n if (!reservation || reservation.committedAt || reservation.releasedAt) return\n await executor\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) =>\n expression('committedBytes', '+', Number(reservation.bytes)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', reservation.workspaceId)\n .execute()\n await executor\n .updateTable('uploadStorageReservation')\n .set({ committedAt: new Date() })\n .where('id', '=', reservation.id)\n .execute()\n }\n\n async function release(executor: StorageDatabase, uploadId: string): Promise<void> {\n await executor\n .updateTable('uploadStorageReservation')\n .set({ releasedAt: new Date() })\n .where('uploadId', '=', uploadId)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .execute()\n }\n\n return {\n snapshot: (workspaceId: string) => snapshot(database, workspaceId),\n\n async reserve(input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<void> {\n await database.transaction().execute((transaction) => reserve(transaction, input))\n },\n\n reserveInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n return reserve(transaction, input)\n },\n\n async commit(uploadId: string): Promise<void> {\n await database.transaction().execute((transaction) => commit(transaction, uploadId))\n },\n\n commitInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return commit(transaction, uploadId)\n },\n\n async release(uploadId: string): Promise<void> {\n await release(database, uploadId)\n },\n\n releaseInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return release(transaction, uploadId)\n }\n }\n}\n\nexport type StorageQuotaService = ReturnType<typeof createStorageQuotaService>\n","import {\n parseCommitImageUploads,\n parseCommitUpload,\n parseCreateDocument,\n parseCreateUpload,\n parseRequestImageLinks,\n parseRequestImageUploads\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport type { DocumentService } from '#cloud/server/documents/service'\nimport { StorageQuotaExceededError } from '#cloud/server/quota'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type DocumentRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** The response a document domain error stands for, or null for any other error. */\nexport function documentDomainError(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof DocumentConflictError) {\n return context.json({ error: { code: 'revision_conflict' as const } }, 409)\n }\n if (error instanceof StorageQuotaExceededError) {\n return context.json({ error: { code: 'storage_quota_exceeded' as const } }, 409)\n }\n if (error instanceof UploadInvalidError) {\n return context.json({ error: { code: 'invalid_upload' as const } }, 422)\n }\n return null\n}\n\n/** Answers with what `respond` gives, or with the response a document domain error stands for. */\nasync function documentResponse<T extends Response>(\n context: Context,\n respond: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await respond()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\nexport function createDocumentRoutes(\n service: DocumentService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<DocumentRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/workspaces/:workspaceId/documents',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.documentCreation,\n (context) => context.req.method !== 'POST',\n (context) => context.req.param('workspaceId') ?? 'unknown'\n )\n )\n router.use(\n '/documents/:documentId/images',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n (context) => context.req.method !== 'POST',\n (context) => context.req.param('documentId') ?? 'unknown'\n )\n )\n router.use(\n '/documents/:documentId/uploads',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n (context) => context.req.method !== 'POST',\n (context) => context.req.param('documentId') ?? 'unknown'\n )\n )\n }\n return router\n .get('/shared-documents', async (context) =>\n context.json({ documents: await service.listShared(context.get('actor').userId) })\n )\n .get('/workspaces/:workspaceId/documents', async (context) => {\n const documents = await service.list(\n context.get('actor').userId,\n context.req.param('workspaceId')\n )\n if (!documents) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ documents })\n })\n .get('/workspaces/:workspaceId/usage', async (context) => {\n try {\n return context.json({\n usage: await service.usage(context.get('actor').userId, context.req.param('workspaceId'))\n })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .post(\n '/workspaces/:workspaceId/documents',\n validatedJSON(parseCreateDocument),\n async (context) => {\n try {\n const document = await service.create(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.valid('json')\n )\n return context.json({ document }, 201)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n }\n )\n .delete('/documents/:documentId', async (context) => {\n try {\n await service.remove(context.get('actor').userId, context.req.param('documentId'))\n return context.body(null, 204)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .get('/documents/:documentId/access', async (context) => {\n try {\n return context.json({\n access: await service.access(context.get('actor').userId, context.req.param('documentId'))\n })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .get('/documents/:documentId', async (context) => {\n try {\n return context.json({\n document: await service.download(\n context.get('actor').userId,\n context.req.param('documentId')\n )\n })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .post('/documents/:documentId/uploads', validatedJSON(parseCreateUpload), (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.createUpload(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/documents/:documentId/images/commit',\n validatedJSON(parseCommitImageUploads),\n (context) =>\n documentResponse(context, async () => {\n await service.commitImageUploads(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json').uploads\n )\n return context.body(null, 204)\n })\n )\n .post('/documents/:documentId/images/links', validatedJSON(parseRequestImageLinks), (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.imageLinks(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json').checksums\n )\n )\n )\n )\n .post('/documents/:documentId/images', validatedJSON(parseRequestImageUploads), (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.requestImageUploads(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post('/uploads/:uploadId/commit', validatedJSON(parseCommitUpload), async (context) => {\n try {\n const document = await service.commitUpload(\n context.get('actor').userId,\n context.req.param('uploadId'),\n context.req.valid('json')\n )\n return context.json({ document })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ExpressionBuilder } from 'kysely'\n\n/**\n * No revision refers to the stored file any more, and no workspace keeps it as an image, so it\n * can leave the object store.\n */\nexport function unreferencedObject(expression: ExpressionBuilder<CloudDatabase, 'storageObject'>) {\n return expression.and([\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision')\n .select('documentRevision.id')\n .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceImage')\n .select('workspaceImage.checksum')\n .whereRef('workspaceImage.storageObjectId', '=', 'storageObject.id')\n )\n )\n ])\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { Kysely } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\nexport type DocumentCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n retentionMs: number\n now?: Date\n}\n\nexport type DocumentCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n objectsDeleted: number\n bytesReclaimed: number\n}\n\nexport type DocumentCleanupService = {\n cleanupDeletedDocuments(options: DocumentCleanupOptions): Promise<DocumentCleanupResult>\n}\n\ntype ClaimedDocument = {\n id: string\n workspaceId: string\n deletedAt: Date\n}\n\ntype StoredRevisionObject = {\n id: string\n objectKey: string\n byteSize: number\n}\n\nexport function createDocumentCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore\n): DocumentCleanupService {\n return {\n async cleanupDeletedDocuments(options) {\n const now = options.now ?? new Date()\n const retentionBefore = new Date(now.getTime() - options.retentionMs)\n const staleBefore = new Date(now.getTime() - options.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const documents = await claimDocuments(\n database,\n options.batchSize,\n retentionBefore,\n staleBefore,\n now,\n claimId\n )\n const result: DocumentCleanupResult = {\n claimed: documents.length,\n cleaned: 0,\n failed: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0\n }\n for (const document of documents) {\n try {\n const revisionObjects = await documentObjects(database, document.id)\n for (const object of revisionObjects) await objects.delete(object.objectKey)\n const reclaimed = await removeDocumentMetadata(\n database,\n document,\n revisionObjects,\n retentionBefore,\n claimId\n )\n if (!reclaimed) continue\n result.cleaned++\n result.objectsDeleted += reclaimed.objectsDeleted\n result.bytesReclaimed += reclaimed.bytesReclaimed\n } catch {\n result.failed++\n await releaseClaim(database, document.id, claimId)\n }\n }\n return result\n }\n }\n}\n\nasync function claimDocuments(\n database: Kysely<CloudDatabase>,\n batchSize: number,\n retentionBefore: Date,\n staleBefore: Date,\n now: Date,\n claimId: string\n): Promise<ClaimedDocument[]> {\n return database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('document')\n .select(['id', 'workspaceId', 'deletedAt'])\n .where('deletedAt', 'is not', null)\n .where('deletedAt', '<=', retentionBefore)\n .where((expression) =>\n expression.or([\n expression('cleanupClaimId', 'is', null),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('upload')\n .select('upload.id')\n .whereRef('upload.documentId', '=', 'document.id')\n .where('upload.status', 'in', ['pending', 'cleaning'])\n )\n )\n )\n .orderBy('deletedAt')\n .limit(batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n const claimed = candidates.filter(\n (document): document is ClaimedDocument => document.deletedAt !== null\n )\n if (claimed.length === 0) return []\n await transaction\n .updateTable('document')\n .set({ cleanupClaimId: claimId, cleanupClaimedAt: now })\n .where(\n 'id',\n 'in',\n claimed.map((document) => document.id)\n )\n .execute()\n return claimed\n })\n}\n\nasync function documentObjects(\n database: Kysely<CloudDatabase>,\n documentId: string\n): Promise<StoredRevisionObject[]> {\n const rows = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select(['storageObject.id', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('documentRevision.documentId', '=', documentId)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision as otherRevision')\n .select('otherRevision.id')\n .whereRef('otherRevision.storageObjectId', '=', 'storageObject.id')\n .where('otherRevision.documentId', '!=', documentId)\n )\n )\n )\n .execute()\n return rows.map((row) => ({ ...row, byteSize: Number(row.byteSize) }))\n}\n\nasync function removeDocumentMetadata(\n database: Kysely<CloudDatabase>,\n document: ClaimedDocument,\n objects: StoredRevisionObject[],\n retentionBefore: Date,\n claimId: string\n): Promise<{ objectsDeleted: number; bytesReclaimed: number } | null> {\n return database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'cleanupClaimId'])\n .where('id', '=', document.id)\n .forUpdate()\n .executeTakeFirst()\n if (\n !locked?.deletedAt ||\n locked.deletedAt > retentionBefore ||\n locked.cleanupClaimId !== claimId\n ) {\n return null\n }\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: null })\n .where('id', '=', document.id)\n .execute()\n await transaction.deleteFrom('documentRevision').where('documentId', '=', document.id).execute()\n let objectsDeleted = 0\n let bytesReclaimed = 0\n for (const object of objects) {\n const deleted = await transaction\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .executeTakeFirst()\n if (Number(deleted.numDeletedRows) > 0) {\n objectsDeleted++\n bytesReclaimed += object.byteSize\n }\n }\n if (bytesReclaimed > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', bytesReclaimed),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', document.workspaceId)\n .execute()\n }\n await transaction.deleteFrom('document').where('id', '=', document.id).execute()\n return { objectsDeleted, bytesReclaimed }\n })\n}\n\nasync function releaseClaim(\n database: Kysely<CloudDatabase>,\n documentId: string,\n claimId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ cleanupClaimId: null, cleanupClaimedAt: null })\n .where('id', '=', documentId)\n .where('cleanupClaimId', '=', claimId)\n .execute()\n}\n","import type {\n CommitUploadInput,\n DocumentImageDownload,\n DocumentImageLink,\n ImageUploadOffer,\n RequestImageUploadsInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { StorageQuotaService } from '#cloud/server/quota'\nimport { uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\n/** Images are stored as the bytes their file holds, whatever format those are. */\nexport const IMAGE_CONTENT_TYPE = 'application/octet-stream'\n\ntype Executor = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/** An image no revision has used for this long may be released; a save uploads first. */\nexport const IMAGE_RELEASE_GRACE_MS = 24 * 60 * 60_000\n\n/**\n * The images a workspace's documents use, each stored once under the SHA-256 the object store\n * verified, and which of them each stored revision uses under the names its file gives them.\n */\nexport function createDocumentImages(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n quota: StorageQuotaService\n) {\n /**\n * Gives up uploads a request reserved when it could not offer them all, so a retry is not\n * refused for space they hold. A multipart upload the store began is aborted first; one that\n * cannot be stays pending for cleanup, which aborts it once it expires.\n */\n async function abandonUploads(\n uploads: readonly { uploadId: string; objectKey: string }[],\n offers: readonly ImageUploadOffer[]\n ): Promise<void> {\n const begun = new Map(offers.map((offer) => [offer.uploadId, offer.upload]))\n for (const { uploadId, objectKey } of uploads) {\n try {\n const upload = begun.get(uploadId)\n if (upload?.kind === 'multipart') {\n await objects.abortUpload({ key: objectKey, uploadId: upload.uploadId })\n }\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .where('status', '=', 'pending')\n .execute()\n } catch (error) {\n // Cleanup releases it once it expires.\n console.warn('Giving up an image upload failed', error)\n }\n }\n }\n\n return {\n /**\n * Uploads for the images of `input` the workspace lacks, each with its own object key and\n * reservation, so an abandoned one is cleaned up like any other upload. Images it holds\n * already need nothing.\n */\n async requestUploads(input: {\n userId: string\n documentId: string\n workspaceId: string\n images: RequestImageUploadsInput['images']\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<ImageUploadOffer[]> {\n const requested = uniqBy(input.images, (image) => image.checksum)\n // Held images are renewed, so none is released before the save that asked commits.\n const held = new Set(\n (\n await database\n .updateTable('workspaceImage')\n .set({ touchedAt: new Date() })\n .where('workspaceId', '=', input.workspaceId)\n .where(\n 'checksum',\n 'in',\n requested.map((image) => image.checksum)\n )\n .returning('checksum')\n .execute()\n ).map((row) => row.checksum)\n )\n const missing = requested\n .filter((image) => !held.has(image.checksum))\n .map((image) => {\n const uploadId = crypto.randomUUID()\n return {\n ...image,\n uploadId,\n objectKey: `documents/${input.workspaceId}/images/${uploadId}`\n }\n })\n if (missing.length === 0) return []\n await database.transaction().execute(async (transaction) => {\n for (const image of missing) {\n await transaction\n .insertInto('upload')\n .values({\n id: image.uploadId,\n kind: 'image',\n documentId: input.documentId,\n baseRevisionId: null,\n objectKey: image.objectKey,\n checksum: image.checksum,\n byteSize: image.byteSize,\n contentType: IMAGE_CONTENT_TYPE,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: input.userId,\n expiresAt: input.expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: input.workspaceId,\n uploadId: image.uploadId,\n bytes: image.byteSize,\n expiresAt: input.expiresAt,\n maximumBytes: input.maximumBytes\n })\n }\n })\n const offers: ImageUploadOffer[] = []\n try {\n for (const image of missing) {\n const upload = await objects.createUpload({\n key: image.objectKey,\n byteSize: image.byteSize,\n checksum: image.checksum,\n contentType: IMAGE_CONTENT_TYPE,\n expiresAt: input.expiresAt\n })\n offers.push({ checksum: image.checksum, uploadId: image.uploadId, upload })\n if (upload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: upload.uploadId })\n .where('id', '=', image.uploadId)\n .execute()\n }\n }\n } catch (error) {\n await abandonUploads(missing, offers)\n throw error\n }\n return offers\n },\n\n /**\n * Stores a verified image upload as the workspace's copy of that image. When another upload of\n * the same bytes got there first, this one's file is left unreferenced for cleanup to delete\n * and its reservation is released rather than counted twice.\n */\n async landInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n uploadId: string\n workspaceId: string\n objectKey: string\n stored: { checksum: string; byteSize: number; contentType: string }\n }\n ): Promise<void> {\n const storageObjectId = crypto.randomUUID()\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: input.objectKey,\n checksum: input.stored.checksum,\n byteSize: input.stored.byteSize,\n contentType: input.stored.contentType\n })\n .execute()\n const landed = await transaction\n .insertInto('workspaceImage')\n .values({\n workspaceId: input.workspaceId,\n checksum: input.stored.checksum,\n storageObjectId\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'checksum']).doNothing())\n .returning('checksum')\n .executeTakeFirst()\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', input.uploadId)\n .execute()\n if (landed) await quota.commitInTransaction(transaction, input.uploadId)\n else await quota.releaseInTransaction(transaction, input.uploadId)\n },\n\n /**\n * Records the images a new revision uses. Each must be the workspace's already; holding them\n * until the revision refers to them keeps a release of an unused image from racing the save.\n * Whether every image was there.\n */\n async attachInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: { workspaceId: string; revisionId: string; images: CommitUploadInput['images'] }\n ): Promise<boolean> {\n const images = uniqBy(input.images, (image) => image.name)\n if (images.length === 0) return true\n const checksums = uniq(images.map((image) => image.checksum))\n const held = await transaction\n .selectFrom('workspaceImage')\n .select('checksum')\n .where('workspaceId', '=', input.workspaceId)\n .where('checksum', 'in', checksums)\n .forShare()\n .execute()\n if (held.length !== checksums.length) return false\n await transaction\n .insertInto('revisionImage')\n .values(\n images.map((image) => ({\n revisionId: input.revisionId,\n name: image.name,\n workspaceId: input.workspaceId,\n checksum: image.checksum\n }))\n )\n .execute()\n return true\n }\n }\n}\n\nexport type DocumentImages = ReturnType<typeof createDocumentImages>\n\n/** Gives a revision made from another, by a restore or a duplicate, the same images. */\nexport async function copyRevisionImages(\n transaction: Transaction<CloudDatabase>,\n fromRevisionId: string,\n toRevisionId: string\n): Promise<void> {\n await transaction\n .insertInto('revisionImage')\n .columns(['revisionId', 'name', 'workspaceId', 'checksum'])\n .expression((expression) =>\n expression\n .selectFrom('revisionImage')\n .select((select) => [\n select.val(toRevisionId).as('revisionId'),\n 'name',\n 'workspaceId',\n 'checksum'\n ])\n .where('revisionId', '=', fromRevisionId)\n )\n .execute()\n}\n\n/** Where to download each image a revision uses, under its name in the file. */\nexport async function revisionImageDownloads(\n executor: Executor,\n objects: ObjectStore,\n revisionId: string,\n expiresAt: Date\n): Promise<DocumentImageDownload[]> {\n const rows = await executor\n .selectFrom('revisionImage')\n .innerJoin('workspaceImage', (join) =>\n join\n .onRef('workspaceImage.workspaceId', '=', 'revisionImage.workspaceId')\n .onRef('workspaceImage.checksum', '=', 'revisionImage.checksum')\n )\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select([\n 'revisionImage.name',\n 'revisionImage.checksum',\n 'storageObject.objectKey',\n 'storageObject.byteSize'\n ])\n .where('revisionImage.revisionId', '=', revisionId)\n .orderBy('revisionImage.name')\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n name: row.name,\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt })\n }))\n )\n}\n\n/**\n * Releases up to `batchSize` images no revision uses that no save has asked for since `before`:\n * their bytes go back to the workspace's usage, and their files, no longer anyone's, are left for\n * the object sweep. A save holds the images it refers to, so it either lands first and keeps them\n * or finds them gone and uploads them again. How many were released and their bytes.\n */\nexport async function releaseUnusedImages(\n database: Kysely<CloudDatabase>,\n before: Date,\n batchSize: number\n): Promise<{ released: number; bytes: number }> {\n return database.transaction().execute(async (transaction) => {\n const unused = await transaction\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.workspaceId', 'workspaceImage.checksum', 'storageObject.byteSize'])\n .where('workspaceImage.touchedAt', '<', before)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n )\n )\n )\n .limit(batchSize)\n .forUpdate('workspaceImage')\n .skipLocked()\n .execute()\n let bytes = 0\n for (const image of unused) {\n await transaction\n .deleteFrom('workspaceImage')\n .where('workspaceId', '=', image.workspaceId)\n .where('checksum', '=', image.checksum)\n .execute()\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', Number(image.byteSize)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', image.workspaceId)\n .execute()\n bytes += Number(image.byteSize)\n }\n return { released: unused.length, bytes }\n })\n}\n\n/**\n * Where to download the images of `checksums` the document's workspace holds, for someone who may\n * view the document. A live room names images by checksum before any save does, and an editor\n * whose image the workspace already holds through another document uploads nothing for this one,\n * so the workspace, not the document, is what an image belongs to. Asking needs the image's\n * SHA-256, which only someone with its bytes has.\n */\nexport async function documentImageLinks(\n executor: Executor,\n objects: ObjectStore,\n input: { documentId: string; checksums: string[]; expiresAt: Date }\n): Promise<DocumentImageLink[]> {\n const rows = await executor\n .selectFrom('workspaceImage')\n .innerJoin('document', 'document.workspaceId', 'workspaceImage.workspaceId')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.checksum', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('document.id', '=', input.documentId)\n .where('workspaceImage.checksum', 'in', uniq(input.checksums))\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt: input.expiresAt })\n }))\n )\n}\n\n/** The images the workspace's current revisions use, each counted once however many use it. */\nexport async function currentImageUsage(\n executor: Executor,\n workspaceId: string\n): Promise<{ objectCount: number; bytesUsed: number }> {\n const usage = await executor\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select((expression) => [\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('workspaceImage.workspaceId', '=', workspaceId)\n .where((expression) =>\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .innerJoin('document', 'document.currentRevisionId', 'revisionImage.revisionId')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n .where('document.deletedAt', 'is', null)\n )\n )\n .executeTakeFirstOrThrow()\n return { objectCount: Number(usage.objectCount), bytesUsed: Number(usage.bytesUsed) }\n}\n","import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\n\n/** How far back a workspace without full revision history keeps its versions. */\nexport const LIMITED_HISTORY_DAYS = 30\n\n/**\n * The oldest moment a workspace's history reaches, or null when it keeps everything: with the\n * `revisionHistory` entitlement off, only the last 30 days, as on a free plan.\n */\nexport async function historyStart(\n policy: CloudPolicy | undefined,\n deploymentMode: CloudPolicyContext['deploymentMode'],\n workspaceId: string,\n now: Date\n): Promise<Date | null> {\n const full = policy\n ? await policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, true, {\n targetingKey: workspaceId,\n workspaceId,\n deploymentMode\n })\n : true\n return full ? null : new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { IMAGE_RELEASE_GRACE_MS, releaseUnusedImages } from '#cloud/server/documents/images'\nimport { historyStart, LIMITED_HISTORY_DAYS } from '#cloud/server/documents/versions/history'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { groupBy, sumBy, uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\n/** How long a save between versions is kept before compaction may delete it. */\nexport const REVISION_COMPACTION_GRACE_MS = 24 * 60 * 60_000\n\nexport type RevisionCompactionOptions = {\n batchSize: number\n /** How long a save stays before it can be compacted, so recent work is never lost to it. */\n graceMs: number\n now?: Date\n}\n\nexport type RevisionCompactionResult = {\n versionsPruned: number\n /** Images no revision used any more, released after their grace period. */\n imagesReleased: number\n revisionsDeleted: number\n objectsDeleted: number\n bytesReclaimed: number\n failed: number\n}\n\nexport type RevisionCompactionService = {\n compactRevisions(options: RevisionCompactionOptions): Promise<RevisionCompactionResult>\n}\n\n/**\n * Keeps a document's stored history to its versions. A save that is neither the document's\n * current state nor kept by a version is deleted once it is older than the grace period, and its\n * file with it when nothing else uses it; a workspace without full history first loses the\n * versions older than its 30 days.\n */\nexport function createRevisionCompactionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: { policy?: CloudPolicy; deploymentMode?: CloudPolicyContext['deploymentMode'] } = {}\n): RevisionCompactionService {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n async function pruneVersions(now: Date, batchSize: number): Promise<number> {\n if (!options.policy) return 0\n const limitedBefore = new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n const workspaces = await database\n .selectFrom('documentVersion')\n .innerJoin('document', 'document.id', 'documentVersion.documentId')\n .select('document.workspaceId')\n .distinct()\n .where('documentVersion.createdAt', '<', limitedBefore)\n .execute()\n let pruned = 0\n for (const { workspaceId } of workspaces) {\n const start = await historyStart(options.policy, deploymentMode, workspaceId, now)\n if (!start) continue\n const deleted = await database\n .deleteFrom('documentVersion')\n .where('id', 'in', (query) =>\n query\n .selectFrom('documentVersion as version')\n .innerJoin('document', 'document.id', 'version.documentId')\n .select('version.id')\n .where('document.workspaceId', '=', workspaceId)\n .where('version.createdAt', '<', start)\n // The document's current state stays listed however old it is.\n .whereRef('version.revisionId', '!=', 'document.currentRevisionId')\n .limit(batchSize)\n )\n .executeTakeFirst()\n pruned += Number(deleted.numDeletedRows)\n }\n return pruned\n }\n\n /** Saves that may go: old, unversioned, not current, in a document that is not deleted. */\n function compactable(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>, before: Date) {\n return source\n .selectFrom('documentRevision')\n .innerJoin('document', 'document.id', 'documentRevision.documentId')\n .where('documentRevision.createdAt', '<', before)\n .where('document.deletedAt', 'is', null)\n .where((expression) =>\n expression.or([\n expression('document.currentRevisionId', 'is', null),\n expression('document.currentRevisionId', '!=', expression.ref('documentRevision.id'))\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentVersion')\n .select('documentVersion.id')\n .whereRef('documentVersion.revisionId', '=', 'documentRevision.id')\n )\n )\n )\n }\n\n /** A file no revision refers to: freed by compaction, waiting for the object store. */\n function unreferencedObjects(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>) {\n return source.selectFrom('storageObject').where(unreferencedObject)\n }\n\n /**\n * Deletes up to `limit` compactable saves of one document and returns the bytes of files nothing\n * refers to any more to the workspace's usage. Their rows stay until the files are gone, so a\n * delete that fails is tried again on the next pass.\n */\n async function compactDocument(\n documentId: string,\n workspaceId: string,\n before: Date,\n limit: number\n ) {\n return database.transaction().execute(async (transaction) => {\n // Saves and restores lock the document too, so none can keep a revision deleted here.\n await transaction\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n const revisions = await compactable(transaction, before)\n .select(['documentRevision.id', 'documentRevision.storageObjectId'])\n .where('documentRevision.documentId', '=', documentId)\n .limit(limit)\n .execute()\n if (revisions.length === 0) return { revisions: 0, bytes: 0 }\n await transaction\n .deleteFrom('documentRevision')\n .where(\n 'id',\n 'in',\n revisions.map((revision) => revision.id)\n )\n .execute()\n const freed = await unreferencedObjects(transaction)\n .select('byteSize')\n .where('id', 'in', uniq(revisions.map((revision) => revision.storageObjectId)))\n .execute()\n const bytes = sumBy(freed, (object) => Number(object.byteSize))\n if (bytes > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', bytes),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', workspaceId)\n .execute()\n }\n return { revisions: revisions.length, bytes }\n })\n }\n\n /** Deletes freed files from the object store, then their rows; a failure stays for next time. */\n async function sweepObjects(batchSize: number, result: RevisionCompactionResult) {\n const freed = await unreferencedObjects(database)\n .select(['id', 'objectKey'])\n .limit(batchSize)\n .execute()\n for (const object of freed) {\n try {\n await objects.delete(object.objectKey)\n await database\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .execute()\n result.objectsDeleted++\n } catch {\n result.failed++\n }\n }\n }\n\n return {\n async compactRevisions(input) {\n const now = input.now ?? new Date()\n const before = new Date(now.getTime() - input.graceMs)\n const result: RevisionCompactionResult = {\n versionsPruned: await pruneVersions(now, input.batchSize),\n imagesReleased: 0,\n revisionsDeleted: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0,\n failed: 0\n }\n const candidates = await compactable(database, before)\n .select(['documentRevision.documentId', 'document.workspaceId'])\n .limit(input.batchSize)\n .execute()\n let capacity = input.batchSize\n for (const [documentId, rows] of Object.entries(\n groupBy(candidates, (row) => row.documentId)\n )) {\n const workspaceId = rows[0]?.workspaceId\n if (!workspaceId || capacity <= 0) continue\n try {\n const compacted = await compactDocument(documentId, workspaceId, before, capacity)\n capacity -= compacted.revisions\n result.revisionsDeleted += compacted.revisions\n result.bytesReclaimed += compacted.bytes\n } catch {\n result.failed++\n }\n }\n // Compaction just freed the images of the saves it deleted; the release lets their grace pass.\n // A release that raced a save referring to an image fails whole and is tried next time.\n try {\n const images = await releaseUnusedImages(\n database,\n new Date(now.getTime() - IMAGE_RELEASE_GRACE_MS),\n input.batchSize\n )\n result.imagesReleased = images.released\n result.bytesReclaimed += images.bytes\n } catch {\n result.failed++\n }\n await sweepObjects(input.batchSize, result)\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nexport type UploadCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n now?: Date\n}\n\nexport type UploadCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n}\n\nexport type UploadCleanupService = {\n cleanupExpiredUploads(options: UploadCleanupOptions): Promise<UploadCleanupResult>\n}\n\ntype ClaimedUpload = {\n id: string\n objectKey: string\n multipartUploadId: string | null\n}\n\nexport function createUploadCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore\n): UploadCleanupService {\n const quota = createStorageQuotaService(database)\n return {\n async cleanupExpiredUploads(options) {\n const now = options.now ?? new Date()\n const staleBefore = new Date(now.getTime() - options.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const uploads = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('upload')\n .select(['id', 'objectKey', 'multipartUploadId'])\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('expiresAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'finalizing'),\n expression('finalizationStartedAt', '<=', staleBefore)\n ]),\n expression.and([\n expression('status', '=', 'cleaning'),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('expiresAt')\n .limit(options.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n const ids = candidates.map((upload) => upload.id)\n await transaction\n .updateTable('upload')\n .set({\n status: 'cleaning',\n finalizationStartedAt: null,\n cleanupClaimId: claimId,\n cleanupClaimedAt: now\n })\n .where('id', 'in', ids)\n .execute()\n return candidates\n })\n\n let cleaned = 0\n let failed = 0\n for (const upload of uploads) {\n try {\n await removeUploadObject(objects, upload)\n const result = await database\n .updateTable('upload')\n .set({\n status: 'abandoned',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) > 0) {\n await quota.release(upload.id)\n cleaned++\n }\n } catch {\n failed++\n await database\n .updateTable('upload')\n .set({\n status: 'pending',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .execute()\n }\n }\n return { claimed: uploads.length, cleaned, failed }\n }\n }\n}\n\n/**\n * Aborting covers a multipart upload that never finished; deleting covers one that did, such as an\n * upload whose commit lost to a newer revision after its parts were assembled.\n */\nasync function removeUploadObject(objects: ObjectStore, upload: ClaimedUpload): Promise<void> {\n if (upload.multipartUploadId) {\n await objects.abortUpload({ key: upload.objectKey, uploadId: upload.multipartUploadId })\n }\n await objects.delete(upload.objectKey)\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { createRateLimitCleanupService } from '#cloud/server/rate-limit/cleanup'\nimport type { Kysely } from 'kysely'\n\nimport { createDocumentCleanupService } from './documents'\nimport { createRevisionCompactionService } from './revisions'\nimport { createUploadCleanupService } from './uploads'\nimport type { CleanupPassOptions, CleanupServices } from './worker'\n\n/** Every cleanup service, over a deployment's database and bucket. */\nexport function createCleanupServices(\n config: Pick<CloudServerConfig, 'deployment'>,\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n policy: CloudPolicy\n): CleanupServices {\n return {\n uploads: createUploadCleanupService(database, objects),\n documents: createDocumentCleanupService(database, objects),\n revisions: createRevisionCompactionService(database, objects, {\n policy,\n deploymentMode: config.deployment\n }),\n rateLimits: createRateLimitCleanupService(database)\n }\n}\n\n/** The batch, lease, and retention a deployment sets for each cleanup pass. */\nexport function cleanupPassOptions(config: CloudServerConfig): CleanupPassOptions {\n return {\n batchSize: config.cleanupBatchSize,\n documentRetentionMs: config.documentRetentionMs,\n leaseDurationMs: config.cleanupLeaseDurationMs\n }\n}\n","/**\n * Waits `milliseconds`, or less if `signal` aborts first. One timer and one listener that is\n * removed again, so a long-lived signal doesn't collect a composite signal per wait.\n */\nexport async function waitForWorkerInterval(\n milliseconds: number,\n signal: AbortSignal\n): Promise<void> {\n if (signal.aborted) return\n const stopped = new AbortController()\n await new Promise<void>((resolve) => {\n stopped.signal.addEventListener('abort', () => resolve(), { once: true })\n const timer = setTimeout(() => stopped.abort(), milliseconds)\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer)\n stopped.abort()\n },\n { once: true, signal: stopped.signal }\n )\n })\n}\n","import { waitForWorkerInterval } from './interval'\n\nexport type PeriodicWorkerOptions<Result> = {\n intervalMs: number\n run(): Promise<Result>\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type PeriodicWorker<Result> = {\n runOnce(): Promise<Result>\n stop(): Promise<void>\n}\n\nexport function startPeriodicWorker<Result>(\n options: PeriodicWorkerOptions<Result>\n): PeriodicWorker<Result> {\n const controller = new AbortController()\n const abort = () => controller.abort()\n options.signal?.addEventListener('abort', abort, { once: true })\n\n async function loop(): Promise<void> {\n while (!controller.signal.aborted) {\n try {\n await options.run()\n } catch (error) {\n options.onError?.(error)\n }\n await waitForWorkerInterval(options.intervalMs, controller.signal)\n }\n }\n\n const running = loop()\n return {\n runOnce: () => options.run(),\n async stop() {\n controller.abort()\n options.signal?.removeEventListener('abort', abort)\n await running\n }\n }\n}\n","import { startPeriodicWorker } from '../worker/periodic'\nimport type { DocumentCleanupResult, DocumentCleanupService } from './documents'\nimport {\n REVISION_COMPACTION_GRACE_MS,\n type RevisionCompactionResult,\n type RevisionCompactionService\n} from './revisions'\nimport type { UploadCleanupResult, UploadCleanupService } from './uploads'\n\nexport type CleanupWorkerOptions = {\n batchSize: number\n documentRetentionMs: number\n intervalMs: number\n leaseDurationMs: number\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type CleanupResult = {\n uploads: UploadCleanupResult\n documents: DocumentCleanupResult\n revisions: RevisionCompactionResult | null\n rateLimits: number\n}\n\nexport type CleanupServices = {\n documents: DocumentCleanupService\n uploads: UploadCleanupService\n revisions?: RevisionCompactionService\n rateLimits?: { cleanupExpired(before: Date): Promise<number> }\n}\n\nexport type CleanupWorker = {\n runOnce(): Promise<CleanupResult>\n stop(): Promise<void>\n}\n\nexport type CleanupPassOptions = Pick<\n CleanupWorkerOptions,\n 'batchSize' | 'documentRetentionMs' | 'leaseDurationMs'\n>\n\n/** One cleanup pass, for runtimes that schedule passes themselves. */\nexport async function runCleanup(\n cleanup: CleanupServices,\n options: CleanupPassOptions\n): Promise<CleanupResult> {\n const uploads = await cleanup.uploads.cleanupExpiredUploads({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs\n })\n const documents = await cleanup.documents.cleanupDeletedDocuments({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs,\n retentionMs: options.documentRetentionMs\n })\n const revisions = cleanup.revisions\n ? await cleanup.revisions.compactRevisions({\n batchSize: options.batchSize,\n graceMs: REVISION_COMPACTION_GRACE_MS\n })\n : null\n const rateLimits = cleanup.rateLimits\n ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))\n : 0\n return { uploads, documents, revisions, rateLimits }\n}\n\nexport function startCleanupWorker(\n cleanup: CleanupServices,\n options: CleanupWorkerOptions\n): CleanupWorker {\n return startPeriodicWorker({\n intervalMs: options.intervalMs,\n signal: options.signal,\n onError: options.onError,\n run: () => runCleanup(cleanup, options)\n })\n}\n","import type { DocumentSummary } from '#cloud/contract'\nimport type { DocumentDatabase, DocumentSummaryRow } from '#cloud/server/documents/repository'\n\nconst SUMMARY_COLUMNS = [\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n] as const\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function documentSummary(row: DocumentSummaryRow): DocumentSummary {\n return {\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n}\n\nexport async function getDocumentSummaryRow(\n database: DocumentDatabase,\n documentId: string\n): Promise<DocumentSummaryRow | undefined> {\n return database\n .selectFrom('document')\n .select(SUMMARY_COLUMNS)\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { DocumentServiceOptions } from '#cloud/server/documents/service'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { Kysely } from 'kysely'\n\n/**\n * The document `userId` may write to, and how large one file and the workspace's storage may\n * be for this save: technical limits, tightened by policy.\n */\nexport async function writableDocument(\n database: Kysely<CloudDatabase>,\n options: Pick<DocumentServiceOptions, 'policy' | 'technicalMaximumUploadBytes'>,\n userId: string,\n documentId: string\n) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n // Access was resolved just above, so the document is read without resolving it again.\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) throw new DocumentNotFoundError()\n const document = documentSummary(row)\n const policyContext = {\n targetingKey: document.workspaceId,\n actorId: userId,\n workspaceId: document.workspaceId,\n documentId,\n deploymentMode: 'self-hosted' as const\n }\n const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER\n const maximumFileBytes = Math.min(\n technicalMaximum,\n options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumFileBytes,\n technicalMaximum,\n policyContext\n )\n : technicalMaximum\n )\n const maximumStorageBytes = options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumStorageBytes,\n Number.MAX_SAFE_INTEGER,\n policyContext\n )\n : Number.MAX_SAFE_INTEGER\n return {\n document,\n maximumFileBytes,\n maximumStorageBytes:\n maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes\n }\n}\n","import type { DocumentSummary, SharedDocument, WorkspaceRole } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { CreateDocumentRecord } from '#cloud/server/documents/types'\nimport { uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\nimport * as v from 'valibot'\n\nimport { resolveDocumentAccess } from './access'\nimport { documentSummary, getDocumentSummaryRow } from './summary'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n\nexport type DocumentDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport type DocumentSummaryRow = Omit<DocumentSummary, 'createdAt' | 'updatedAt'> & {\n createdAt: Date | string\n updatedAt: Date | string\n}\n\nexport async function workspaceRole(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceRole | undefined> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', userId)\n .executeTakeFirst()\n return member?.role\n}\n\nexport async function listDocuments(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<DocumentSummary[] | undefined> {\n if (!(await workspaceRole(database, userId, workspaceId))) return undefined\n const rows = await database\n .selectFrom('document')\n .select([\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n ])\n .where('workspaceId', '=', workspaceId)\n .where('deletedAt', 'is', null)\n .orderBy('updatedAt', 'desc')\n .execute()\n return rows.map(documentSummary)\n}\n\n/** Documents granted to the person directly that live in workspaces they are not a member of. */\nexport async function listSharedDocuments(\n database: DocumentDatabase,\n userId: string\n): Promise<SharedDocument[]> {\n const rows = await database\n .selectFrom('documentGrant')\n .innerJoin('document', 'document.id', 'documentGrant.documentId')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select([\n 'document.id',\n 'document.workspaceId',\n 'document.name',\n 'document.kind',\n 'document.currentRevisionId',\n 'document.version',\n 'document.createdAt',\n 'document.updatedAt',\n 'workspace.name as workspaceName',\n 'documentGrant.permission',\n 'documentGrant.createdAt as sharedAt',\n 'documentGrant.createdBy'\n ])\n .where('documentGrant.userId', '=', userId)\n .where('documentGrant.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', userId)\n )\n )\n )\n .orderBy('document.updatedAt', 'desc')\n .execute()\n // Grants can be made by operator tools whose IDs are not accounts, so only UUIDs are looked up.\n const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(uuidSchema, id))\n const names = new Map(\n granters.length === 0\n ? []\n : (\n await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', granters)\n .execute()\n ).map((user) => [user.id, user.name] as const)\n )\n return rows.map(({ workspaceName, permission, sharedAt, createdBy, ...row }) => {\n const sharedByName = names.get(createdBy)\n return {\n ...documentSummary(row),\n workspaceName,\n permission,\n sharedBy: sharedByName === undefined ? null : { name: sharedByName },\n sharedAt: sharedAt instanceof Date ? sharedAt.toISOString() : sharedAt\n }\n })\n}\n\nexport async function findDocument(\n database: DocumentDatabase,\n userId: string,\n documentId: string\n): Promise<(DocumentSummary & { role: WorkspaceRole }) | undefined> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) return undefined\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) return undefined\n const role: WorkspaceRole = access.permission === 'edit' ? 'editor' : 'viewer'\n return { ...documentSummary(row), role }\n}\n\nexport async function insertDocument(\n database: DocumentDatabase,\n input: CreateDocumentRecord\n): Promise<void> {\n await database.insertInto('document').values(input).execute()\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Transaction } from 'kysely'\n\n/** How long the newest version may be old before a save keeps the state it replaces. */\nexport const CHECKPOINT_INTERVAL_MS = 30 * 60_000\n\n/** Keeps a revision in the history, unless a version already keeps it. */\nexport async function keepRevision(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n revisionId: string\n createdBy: string\n createdAt: Date\n restoredFromVersionId?: string\n }\n): Promise<void> {\n await transaction\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId: input.documentId,\n revisionId: input.revisionId,\n kind: 'checkpoint',\n name: null,\n description: null,\n createdBy: input.createdBy,\n restoredFromVersionId: input.restoredFromVersionId ?? null,\n createdAt: input.createdAt\n })\n .onConflict((conflict) => conflict.column('revisionId').doNothing())\n .execute()\n}\n\n/**\n * Records the history's checkpoints as a save lands: the document's first save, and the state a\n * save replaces once the newest version is half an hour old. Each stretch of editing, and how the\n * document was left at the end of every session, stays in the history; the saves between them are\n * compacted later. Whether the history gained a checkpoint.\n */\nexport async function recordCheckpoint(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n previousRevisionId: string | null\n revisionId: string\n userId: string\n now: Date\n }\n): Promise<boolean> {\n if (!input.previousRevisionId) {\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.revisionId,\n createdBy: input.userId,\n createdAt: input.now\n })\n return true\n }\n const newest = await transaction\n .selectFrom('documentVersion')\n .select('createdAt')\n .where('documentId', '=', input.documentId)\n .orderBy('createdAt', 'desc')\n .limit(1)\n .executeTakeFirst()\n if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) {\n return false\n }\n const previous = await transaction\n .selectFrom('documentRevision')\n .select(['createdBy', 'createdAt'])\n .where('id', '=', input.previousRevisionId)\n .executeTakeFirst()\n if (!previous) return false\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.previousRevisionId,\n createdBy: previous.createdBy,\n createdAt: previous.createdAt\n })\n return true\n}\n\n/**\n * Tells the document's live rooms that its history changed. The change stands whatever the hook\n * does; an open list that misses it loads the history again when it is next opened.\n */\nexport function announceVersions(\n onVersionsChanged: ((documentId: string) => void) | undefined,\n documentId: string\n): void {\n try {\n onVersionsChanged?.(documentId)\n } catch (error) {\n console.error('[Cloud] Announcing a version history change failed:', error)\n }\n}\n","import type {\n CommitImageUploadsInput,\n CommitUploadInput,\n CreateDocumentInput,\n CreateUploadInput,\n DocumentDownload,\n DocumentSummary,\n ImageUploadOffer,\n RequestImageUploadsInput,\n SharedDocument\n} from '#cloud/contract'\nimport { createUploadCleanupService } from '#cloud/server/cleanup'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n canDeleteDocument,\n canEditDocument,\n resolveDocumentAccess\n} from '#cloud/server/documents/access'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport {\n createDocumentImages,\n currentImageUsage,\n documentImageLinks,\n revisionImageDownloads\n} from '#cloud/server/documents/images'\nimport { writableDocument } from '#cloud/server/documents/limits'\nimport {\n findDocument,\n insertDocument,\n listDocuments,\n listSharedDocuments,\n workspaceRole\n} from '#cloud/server/documents/repository'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport type { CreateDocumentUploadResult } from '#cloud/server/documents/types'\nimport { announceVersions, recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'\nimport type { ObjectStore, StoredObject } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport { isUndefined, limitAsync, omitBy, uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nconst DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000\nconst UPLOAD_LIFETIME_MS = 15 * 60 * 1000\n/** How many of a save's images are checked and landed at once. */\nconst IMAGE_COMMIT_CONCURRENCY = 8\nconst WRITABLE_ROLES = new Set(['admin', 'editor'])\n\nexport type DocumentServiceOptions = {\n policy?: CloudPolicy\n technicalMaximumUploadBytes?: number\n /** Called once a save adds a checkpoint to the document's history. */\n onVersionsChanged?: (documentId: string) => void\n}\n\n/** Whether the stored object is the file the upload declared, which the commit names again. */\nfunction matchesUpload(\n stored: { checksum: string; byteSize: number; contentType: string },\n upload: { checksum: string; byteSize: number | string | bigint; contentType: string }\n): boolean {\n return (\n stored.checksum === upload.checksum &&\n stored.byteSize === Number(upload.byteSize) &&\n stored.contentType === upload.contentType\n )\n}\n\nexport function createDocumentService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: DocumentServiceOptions = {}\n) {\n const cleanup = createUploadCleanupService(database, objects)\n const quota = createStorageQuotaService(database)\n const images = createDocumentImages(database, objects, quota)\n\n /**\n * Makes a committed upload the document's current revision, unless it already was, and records\n * the checkpoint the save adds, if any. Whether the history gained one.\n */\n async function landRevision(\n transaction: Transaction<CloudDatabase>,\n {\n userId,\n uploadId,\n upload,\n stored,\n revisionId,\n storageObjectId,\n images: revisionImages,\n name,\n kind\n }: {\n userId: string\n uploadId: string\n upload: {\n documentId: string\n workspaceId: string\n baseRevisionId: string | null\n objectKey: string\n }\n stored: { checksum: string; byteSize: number; contentType: string }\n revisionId: string\n storageObjectId: string\n images: CommitUploadInput['images']\n name: CommitUploadInput['name']\n kind: CommitUploadInput['kind']\n }\n ): Promise<boolean> {\n const lockedUpload = await transaction\n .selectFrom('upload')\n .select('status')\n .where('id', '=', uploadId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (lockedUpload.status === 'committed') return false\n if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()\n const document = await transaction\n .selectFrom('document')\n .select(['currentRevisionId'])\n .where('id', '=', upload.documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (document.currentRevisionId !== upload.baseRevisionId) {\n throw new DocumentConflictError()\n }\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: upload.objectKey,\n checksum: stored.checksum,\n byteSize: stored.byteSize,\n contentType: stored.contentType\n })\n .execute()\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: upload.documentId,\n parentRevisionId: upload.baseRevisionId,\n storageObjectId,\n createdBy: userId\n })\n .execute()\n const attached = await images.attachInTransaction(transaction, {\n workspaceId: upload.workspaceId,\n revisionId,\n images: revisionImages\n })\n if (!attached) throw new UploadInvalidError()\n await transaction\n .updateTable('document')\n .set({\n // A revision may also retitle its document, or say the file it holds is a board.\n ...omitBy({ name, kind }, isUndefined),\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1)\n })\n .where('id', '=', upload.documentId)\n .execute()\n const checkpointed = await recordCheckpoint(transaction, {\n documentId: upload.documentId,\n previousRevisionId: document.currentRevisionId,\n revisionId,\n userId,\n now: new Date()\n })\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', uploadId)\n .execute()\n await quota.commitInTransaction(transaction, uploadId)\n return checkpointed\n }\n\n /** Links for images a live room names, by checksum. */\n async function imageLinksOf(documentId: string, checksums: string[]) {\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n images: await documentImageLinks(database, objects, { documentId, checksums, expiresAt })\n }\n }\n\n async function createDownload(documentId: string): Promise<DocumentDownload> {\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row?.currentRevisionId) throw new DocumentNotFoundError()\n const document: DocumentSummary = documentSummary(row)\n const revision = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.id as revisionId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', document.currentRevisionId)\n .where('documentRevision.documentId', '=', documentId)\n .executeTakeFirst()\n if (!revision) throw new DocumentNotFoundError()\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document,\n revisionId: revision.revisionId,\n byteSize: Number(revision.byteSize),\n checksum: revision.checksum,\n contentType: revision.contentType,\n download: await objects.createDownload({ key: revision.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, revision.revisionId, expiresAt)\n }\n }\n\n /** What committing an upload reads of it and its document. */\n function selectUploads() {\n return database\n .selectFrom('upload')\n .innerJoin('document', 'document.id', 'upload.documentId')\n .select([\n 'upload.id',\n 'upload.documentId',\n 'upload.kind',\n 'document.workspaceId',\n 'upload.baseRevisionId',\n 'upload.objectKey',\n 'upload.checksum',\n 'upload.byteSize',\n 'upload.contentType',\n 'upload.multipartUploadId',\n 'upload.status',\n 'upload.expiresAt'\n ])\n }\n type UploadRow = Awaited<ReturnType<ReturnType<typeof selectUploads>['executeTakeFirstOrThrow']>>\n\n /**\n * Claims a pending upload, completes it when it came in parts, checks the store holds the file\n * it declared, and lands it with `land`. An upload that fails goes back to pending, so its\n * commit can be tried again.\n */\n async function finalizeUpload<T>(\n upload: UploadRow,\n multipart: CommitUploadInput['multipart'],\n land: (stored: StoredObject) => Promise<T>\n ): Promise<T> {\n if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {\n throw new UploadInvalidError()\n }\n const claimed = await database\n .updateTable('upload')\n .set({ status: 'finalizing', finalizationStartedAt: new Date() })\n .where('id', '=', upload.id)\n .where('status', '=', 'pending')\n .returning('id')\n .executeTakeFirst()\n if (!claimed) throw new UploadInvalidError()\n try {\n if (multipart) {\n if (\n !objects.capabilities.multipartUpload ||\n multipart.uploadId !== upload.multipartUploadId\n ) {\n throw new UploadInvalidError()\n }\n await objects.completeUpload({\n key: upload.objectKey,\n uploadId: multipart.uploadId,\n parts: multipart.parts\n })\n }\n const stored = await objects.head(upload.objectKey)\n if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()\n return await land(stored)\n } catch (error) {\n await database\n .updateTable('upload')\n .set({ status: 'pending', finalizationStartedAt: null })\n .where('id', '=', upload.id)\n .where('status', '=', 'finalizing')\n .execute()\n throw error\n }\n }\n\n function landImage(upload: UploadRow, stored: StoredObject): Promise<void> {\n return database.transaction().execute((transaction) =>\n images.landInTransaction(transaction, {\n uploadId: upload.id,\n workspaceId: upload.workspaceId,\n objectKey: upload.objectKey,\n stored\n })\n )\n }\n\n async function commitUpload(\n userId: string,\n uploadId: string,\n input: CommitUploadInput\n ): Promise<DocumentSummary> {\n const upload = await selectUploads()\n .where('upload.id', '=', uploadId)\n .where('upload.createdBy', '=', userId)\n .executeTakeFirst()\n if (!upload) throw new DocumentNotFoundError()\n const access = await resolveDocumentAccess(database, userId, upload.documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n if (input.checksum !== upload.checksum) throw new UploadInvalidError()\n if (upload.status !== 'committed') {\n const checkpointed =\n upload.kind === 'image'\n ? await finalizeUpload(upload, input.multipart, (stored) =>\n landImage(upload, stored).then(() => false)\n )\n : await finalizeUpload(upload, input.multipart, (stored) =>\n database.transaction().execute((transaction) =>\n landRevision(transaction, {\n userId,\n uploadId,\n upload,\n stored,\n revisionId: crypto.randomUUID(),\n storageObjectId: crypto.randomUUID(),\n images: input.images,\n name: input.name,\n kind: input.kind\n })\n )\n )\n if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)\n }\n const document = await findDocument(database, userId, upload.documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n }\n\n return {\n async cleanupExpiredUploads(now = new Date()): Promise<number> {\n const result = await cleanup.cleanupExpiredUploads({\n batchSize: 100,\n leaseDurationMs: 5 * 60 * 1000,\n now\n })\n if (result.failed > 0) throw new Error('One or more expired uploads could not be cleaned')\n return result.cleaned\n },\n\n list(userId: string, workspaceId: string): Promise<DocumentSummary[] | undefined> {\n return listDocuments(database, userId, workspaceId)\n },\n\n listShared(userId: string): Promise<SharedDocument[]> {\n return listSharedDocuments(database, userId)\n },\n\n async usage(userId: string, workspaceId: string) {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n const result = await database\n .selectFrom('document')\n .leftJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')\n .leftJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select((expression) => [\n expression.fn.count('document.id').as('documentCount'),\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('document.workspaceId', '=', workspaceId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirstOrThrow()\n const shared = await currentImageUsage(database, workspaceId)\n return {\n bytesUsed: Number(result.bytesUsed) + shared.bytesUsed,\n objectCount: Number(result.objectCount) + shared.objectCount,\n documentCount: Number(result.documentCount)\n }\n },\n\n async access(userId: string, documentId: string) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return access\n },\n\n async downloadShared(documentId: string): Promise<DocumentDownload> {\n return createDownload(documentId)\n },\n\n /** Links for images a live room names, for someone who may view the document. */\n async imageLinks(userId: string, documentId: string, checksums: string[]) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return imageLinksOf(documentId, checksums)\n },\n\n /** Links for images a live room names, for a guest a share already let in. */\n imageLinksShared(documentId: string, checksums: string[]) {\n return imageLinksOf(documentId, checksums)\n },\n\n async download(userId: string, documentId: string): Promise<DocumentDownload> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return createDownload(documentId)\n },\n\n async remove(userId: string, documentId: string): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access) || !(await canDeleteDocument(database, userId, documentId))) {\n throw new DocumentForbiddenError()\n }\n await database\n .updateTable('document')\n .set({ deletedAt: new Date() })\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .execute()\n },\n\n async create(\n userId: string,\n workspaceId: string,\n input: CreateDocumentInput\n ): Promise<DocumentSummary> {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()\n const documentId = input.id ?? crypto.randomUUID()\n await insertDocument(database, {\n id: documentId,\n workspaceId,\n name: input.name,\n kind: input.kind,\n createdBy: userId\n })\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n },\n\n async createUpload(\n userId: string,\n documentId: string,\n input: CreateUploadInput\n ): Promise<CreateDocumentUploadResult> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (document.currentRevisionId !== input.baseRevisionId) throw new DocumentConflictError()\n if (input.byteSize > maximumFileBytes) throw new UploadInvalidError()\n const uploadId = crypto.randomUUID()\n const objectKey = `documents/${document.workspaceId}/${documentId}/uploads/${uploadId}.fig`\n const expiresAt = new Date(Date.now() + UPLOAD_LIFETIME_MS)\n await database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('upload')\n .values({\n id: uploadId,\n documentId,\n baseRevisionId: input.baseRevisionId,\n objectKey,\n checksum: input.checksum,\n byteSize: input.byteSize,\n contentType: input.contentType,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: userId,\n expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: document.workspaceId,\n uploadId,\n bytes: input.byteSize,\n expiresAt,\n maximumBytes: maximumStorageBytes\n })\n })\n let objectUpload\n try {\n objectUpload = await objects.createUpload({\n key: objectKey,\n byteSize: input.byteSize,\n checksum: input.checksum,\n contentType: input.contentType,\n expiresAt\n })\n } catch (error) {\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .execute()\n throw error\n }\n if (objectUpload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: objectUpload.uploadId })\n .where('id', '=', uploadId)\n .execute()\n }\n return { id: uploadId, upload: objectUpload }\n },\n\n /** Uploads for the images a save of the document will name that its workspace lacks. */\n async requestImageUploads(\n userId: string,\n documentId: string,\n input: RequestImageUploadsInput\n ): Promise<{ uploads: ImageUploadOffer[] }> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (input.images.some((image) => image.byteSize > maximumFileBytes)) {\n throw new UploadInvalidError()\n }\n return {\n uploads: await images.requestUploads({\n userId,\n documentId,\n workspaceId: document.workspaceId,\n images: input.images,\n expiresAt: new Date(Date.now() + UPLOAD_LIFETIME_MS),\n maximumBytes: maximumStorageBytes\n })\n }\n },\n commitUpload,\n\n /**\n * Commits the image uploads a save asked for in one request, however many there are: each\n * must be an image upload this person made for the document.\n */\n async commitImageUploads(\n userId: string,\n documentId: string,\n uploads: CommitImageUploadsInput['uploads']\n ): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n const ids = uniq(uploads.map((upload) => upload.uploadId))\n const rows = new Map(\n (\n await selectUploads()\n .where('upload.id', 'in', ids)\n .where('upload.documentId', '=', documentId)\n .where('upload.createdBy', '=', userId)\n .execute()\n ).map((row) => [row.id, row])\n )\n if (rows.size !== ids.length || [...rows.values()].some((row) => row.kind !== 'image')) {\n throw new UploadInvalidError()\n }\n for (const commit of uploads) {\n if (rows.get(commit.uploadId)?.checksum !== commit.checksum) throw new UploadInvalidError()\n }\n // Each image is its own object, so a few are checked and landed at once, each once however\n // often the request names it.\n const land = limitAsync(\n (upload: UploadRow, multipart: CommitUploadInput['multipart']) =>\n finalizeUpload(upload, multipart, (stored) => landImage(upload, stored)),\n IMAGE_COMMIT_CONCURRENCY\n )\n await Promise.all(\n uniqBy(uploads, (commit) => commit.uploadId).map(async (commit) => {\n const upload = rows.get(commit.uploadId)\n if (!upload) throw new UploadInvalidError()\n if (upload.status !== 'committed') await land(upload, commit.multipart)\n })\n )\n }\n }\n}\n\nexport type DocumentService = ReturnType<typeof createDocumentService>\n","import { parseCreateAIToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { AINotEntitledError } from './errors'\nimport type { AITokenService } from './service'\n\nexport type AIRouteEnvironment = { Variables: { actor: CloudActor } }\n\n/** Without a service, the deployment has no AI service and the token route is not found. */\nexport function createAIRoutes(\n service: AITokenService | undefined,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<AIRouteEnvironment>()\n if (service && rateLimit) {\n router.use(\n '/ai/token',\n createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.aiToken)\n )\n }\n return router.post('/ai/token', validatedJSON(parseCreateAIToken), async (context) => {\n if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)\n try {\n return context.json(\n await service.issue(context.get('actor'), context.req.valid('json').workspaceId)\n )\n } catch (error) {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof AINotEntitledError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n throw error\n }\n })\n}\n","import { CLOUD_AI_TOKEN_AUDIENCE, type AIToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\n\nimport { AINotEntitledError } from './errors'\nimport { AI_SIGNING_ALGORITHM, type AISigningKey } from './keys'\n\nexport type AITokenServiceOptions = {\n database: Kysely<CloudDatabase>\n policy: CloudPolicy\n deploymentMode: 'official' | 'self-hosted'\n /** The Cloud public URL, which services check as the token's `iss`. */\n issuer: string\n signingKey: AISigningKey\n lifetimeSeconds: number\n}\n\nexport function createAITokenService(options: AITokenServiceOptions) {\n const { privateKey, publicJWK } = options.signingKey\n\n return {\n /**\n * Signs a token that lets a workspace member reach the AI service on the workspace's behalf.\n * Entitlements are read for every token, so a plan change reaches the service within one\n * token lifetime.\n */\n async issue(actor: CloudActor, workspaceId: string): Promise<AIToken> {\n if (!(await workspaceRole(options.database, actor.userId, workspaceId))) {\n throw new DocumentNotFoundError()\n }\n const context = {\n targetingKey: workspaceId,\n actorId: actor.userId,\n workspaceId,\n deploymentMode: options.deploymentMode\n }\n const [enabled, allowance] = await Promise.all([\n options.policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),\n options.policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)\n ])\n if (!enabled) throw new AINotEntitledError()\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAt = issuedAt + options.lifetimeSeconds\n const token = await new SignJWT({\n workspaceId,\n monthlyCreditAllowance: allowance < 0 ? null : allowance\n })\n .setProtectedHeader({ alg: AI_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })\n .setIssuer(options.issuer)\n .setAudience(CLOUD_AI_TOKEN_AUDIENCE)\n .setSubject(actor.userId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(privateKey)\n return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }\n },\n\n jwks() {\n return { keys: [publicJWK] }\n }\n }\n}\n\nexport type AITokenService = ReturnType<typeof createAITokenService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nexport async function requireSharingAccess(\n database: Kysely<CloudDatabase>,\n userId: string,\n documentId: string\n): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!access.canManageSharing) throw new DocumentForbiddenError()\n}\n\n/**\n * Ends every collaboration ticket and room key issued for the document so far: removing someone's\n * access must also remove them from its live room.\n */\nexport async function advanceCollaborationEpoch(\n database: Kysely<CloudDatabase>,\n documentId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1) })\n .where('id', '=', documentId)\n .executeTakeFirst()\n}\n","import { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\n\nconst CONTINUATION_SALT = utf8ToBytes('openpencil-cloud-invitation-continuation')\nconst CONTINUATION_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\n\nexport function hashCapability(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function capabilityHashMatches(stored: string, value: string): boolean {\n let expected: Uint8Array\n try {\n expected = hexToBytes(stored)\n } catch {\n return false\n }\n const actual = sha256(utf8ToBytes(value))\n if (expected.length !== actual.length) return false\n let difference = 0\n for (const [index, expectedByte] of expected.entries()) {\n difference |= expectedByte ^ (actual[index] ?? 0)\n }\n return difference === 0\n}\n\nfunction continuationKey(secret: string): Uint8Array {\n return hkdf(sha256, utf8ToBytes(secret), CONTINUATION_SALT, new Uint8Array(), 32)\n}\n\nexport async function encryptContinuationToken(secret: string, token: string): Promise<string> {\n return new CompactEncrypt(utf8ToBytes(token))\n .setProtectedHeader(CONTINUATION_HEADER)\n .encrypt(continuationKey(secret))\n}\n\nexport async function decryptContinuationToken(secret: string, value: string): Promise<string> {\n const { plaintext, protectedHeader } = await compactDecrypt(value, continuationKey(secret))\n if (\n protectedHeader.alg !== CONTINUATION_HEADER.alg ||\n protectedHeader.enc !== CONTINUATION_HEADER.enc\n ) {\n throw new Error('Unsupported invitation continuation encryption')\n }\n return new TextDecoder().decode(plaintext)\n}\n","export class InvitationDeliveryError extends Error {\n override readonly name = 'InvitationDeliveryError'\n}\n\nexport class DocumentShareInvalidError extends Error {\n override readonly name = 'DocumentShareInvalidError'\n}\n\n/** A valid link this server opens only for people signed in to it. */\nexport class DocumentShareSignInRequiredError extends Error {\n override readonly name = 'DocumentShareSignInRequiredError'\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\nimport { staticEntitlementsSchema } from './schema'\nimport { staticEntitlementValues, type StaticEntitlementsInput } from './static'\n\nexport class DatabaseEntitlementSource implements EntitlementSource {\n constructor(private readonly database: Kysely<CloudDatabase>) {}\n\n private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {\n if (subject.type !== 'workspace') return {}\n const row = await this.database\n .selectFrom('workspaceEntitlement')\n .select('values')\n .where('workspaceId', '=', subject.id)\n .executeTakeFirst()\n return row ? staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values)) : {}\n }\n\n async boolean(subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, _key: string): Promise<string | null> {\n return null\n }\n}\n\nexport function createWorkspaceEntitlementRepository(database: Kysely<CloudDatabase>) {\n return {\n async get(workspaceId: string) {\n return database\n .selectFrom('workspaceEntitlement')\n .selectAll()\n .where('workspaceId', '=', workspaceId)\n .executeTakeFirst()\n },\n\n async set(workspaceId: string, values: StaticEntitlementsInput, source: string) {\n const validated = v.parse(staticEntitlementsSchema, values)\n return database\n .insertInto('workspaceEntitlement')\n .values({ workspaceId, values: validated, source })\n .onConflict((conflict) =>\n conflict.column('workspaceId').doUpdateSet({\n values: validated,\n source,\n revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n )\n .returningAll()\n .executeTakeFirstOrThrow()\n },\n\n /**\n * Stores entitlements an external writer versioned, unless the stored row carries a newer\n * version: billing events arrive out of order, and a late one must not undo a newer plan.\n * An unversioned row, such as one an operator set, is replaced.\n */\n async setVersioned(\n workspaceId: string,\n values: StaticEntitlementsInput,\n source: string,\n externalVersion: number\n ): Promise<{ applied: boolean }> {\n const validated = v.parse(staticEntitlementsSchema, values)\n const row = await database\n .insertInto('workspaceEntitlement')\n .values({ workspaceId, values: validated, source, externalVersion })\n .onConflict((conflict) =>\n conflict\n .column('workspaceId')\n .doUpdateSet({\n values: validated,\n source,\n externalVersion,\n revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n .where((expression) =>\n expression.or([\n expression('workspaceEntitlement.externalVersion', 'is', null),\n expression('workspaceEntitlement.externalVersion', '<', externalVersion)\n ])\n )\n )\n .returning('workspaceId')\n .executeTakeFirst()\n return { applied: row !== undefined }\n },\n\n async clear(workspaceId: string): Promise<void> {\n await database\n .deleteFrom('workspaceEntitlement')\n .where('workspaceId', '=', workspaceId)\n .execute()\n }\n }\n}\n","export type EntitlementSubject = {\n type: 'workspace' | 'user' | 'organization' | 'deployment'\n id: string\n}\n\nexport type EntitlementSource = {\n boolean(subject: EntitlementSubject, key: string): Promise<boolean | null>\n number(subject: EntitlementSubject, key: string): Promise<number | null>\n string(subject: EntitlementSubject, key: string): Promise<string | null>\n}\n\nexport class StaticEntitlementSource implements EntitlementSource {\n constructor(private readonly values: Readonly<Record<string, boolean | number | string>>) {}\n\n async boolean(_subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = this.values[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(_subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = this.values[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, key: string): Promise<string | null> {\n const value = this.values[key]\n return typeof value === 'string' ? value : null\n }\n}\n","import {\n type EvaluationContext,\n type Logger,\n type Provider,\n type ProviderMetadata,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\n\nfunction subject(context: EvaluationContext): EntitlementSubject {\n const type = context.subjectType\n return {\n type: type === 'user' || type === 'organization' || type === 'deployment' ? type : 'workspace',\n id: context.targetingKey ?? 'deployment'\n }\n}\n\nexport class EntitlementOpenFeatureProvider implements Provider {\n readonly metadata: ProviderMetadata = { name: 'openpencil-entitlements' }\n readonly runsOn = 'server' as const\n\n constructor(private readonly source: EntitlementSource) {}\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const value = await this.source.boolean(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const value = await this.source.number(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const value = await this.source.string(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveObjectEvaluation<T>(\n _flagKey: string,\n defaultValue: T\n ): Promise<ResolutionDetails<T>> {\n return { value: defaultValue, reason: 'DEFAULT' }\n }\n}\n","import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'\nimport {\n DefaultLogger,\n TypedInMemoryProvider,\n type EvaluationContext,\n type Provider,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'\n\nconst DEFAULT_FLAGS = {\n [CLOUD_FEATURE_KEYS.links]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestView]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestEdit]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestPresence]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.collaboration]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.serverEnforcedWrites]: {\n variants: { enabled: false, disabled: false },\n defaultVariant: 'disabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.revisionHistory]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: {\n variants: { default: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES },\n defaultVariant: 'default',\n disabled: false\n }\n} as const\n\nfunction evaluationContext(context: CloudPolicyContext): EvaluationContext {\n const evaluation: EvaluationContext = {\n targetingKey: context.targetingKey,\n deploymentMode: context.deploymentMode\n }\n if (context.actorId) evaluation.actorId = context.actorId\n if (context.workspaceId) evaluation.workspaceId = context.workspaceId\n if (context.organizationId) evaluation.organizationId = context.organizationId\n if (context.documentId) evaluation.documentId = context.documentId\n return evaluation\n}\n\nconst logger = new DefaultLogger()\n\n/** A flag's value, or the default when the provider failed or reported an error, as a client does. */\nasync function resolved<T>(evaluation: () => Promise<ResolutionDetails<T>>, defaultValue: T) {\n try {\n const details = await evaluation()\n return details.errorCode ? defaultValue : details.value\n } catch {\n return defaultValue\n }\n}\n\n/**\n * Answers entitlement questions from one OpenFeature provider. It asks the provider directly\n * rather than through the global `OpenFeature` API: each app has its own provider, and the API\n * keeps every provider registered under a domain reachable for the life of the process, with the\n * database its entitlement source holds.\n */\nexport class CloudPolicy {\n constructor(private readonly provider: Provider) {}\n\n boolean(key: string, defaultValue: boolean, context: CloudPolicyContext): Promise<boolean> {\n return resolved(\n () =>\n this.provider.resolveBooleanEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n ),\n defaultValue\n )\n }\n\n number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {\n return resolved(\n () =>\n this.provider.resolveNumberEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n ),\n defaultValue\n )\n }\n}\n\nexport function createDefaultCloudPolicy(provider?: Provider): CloudPolicy {\n return new CloudPolicy(provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nimport { DatabaseEntitlementSource } from './database'\nimport { StaticEntitlementSource } from './entitlements'\nimport { createDefaultCloudPolicy } from './policy'\nimport { EntitlementOpenFeatureProvider } from './provider'\nimport { staticEntitlementValues } from './static'\n\n/** The policy a deployment configures: its static entitlements, or the database's. */\nexport function createConfiguredCloudPolicy(\n config: Pick<CloudServerConfig, 'staticEntitlements'>,\n database: Kysely<CloudDatabase>\n) {\n return createDefaultCloudPolicy(\n new EntitlementOpenFeatureProvider(\n config.staticEntitlements\n ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))\n : new DatabaseEntitlementSource(database)\n )\n )\n}\n","import type { WorkspaceEntitlements } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport type { CloudPolicy } from './policy'\n\nexport function createEntitlementService(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n technicalMaximumFileBytes: number,\n technicalMaximumParticipants = Number.MAX_SAFE_INTEGER\n) {\n const quota = createStorageQuotaService(database)\n return {\n async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {\n if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()\n const context = {\n targetingKey: workspaceId,\n actorId: userId,\n workspaceId,\n deploymentMode: 'self-hosted' as const\n }\n const [\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudAI,\n maximumFileBytes,\n maximumStorage,\n maximumParticipants,\n monthlyCreditAllowance,\n usage\n ] = await Promise.all([\n policy.boolean(CLOUD_FEATURE_KEYS.links, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),\n policy.number(\n CLOUD_FEATURE_KEYS.maximumParticipants,\n technicalMaximumParticipants,\n context\n ),\n policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context),\n quota.snapshot(workspaceId)\n ])\n // Technical limits are ceilings: an entitlement can lower them but never raise them.\n const participants = Math.min(technicalMaximumParticipants, maximumParticipants)\n return {\n features: {\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudAI\n },\n limits: {\n maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),\n maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,\n maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,\n monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance\n },\n usage: {\n committedStorageBytes: usage.committedBytes,\n reservedStorageBytes: usage.reservedBytes\n }\n }\n }\n }\n}\n\nexport type EntitlementService = ReturnType<typeof createEntitlementService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentForbiddenError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'\nimport type { Kysely } from 'kysely'\n\nexport type SharingPolicyOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport type CapabilityLinkPolicyInput = {\n actorId: string\n documentId: string\n}\n\nexport function createSharingPolicy(\n database: Kysely<CloudDatabase>,\n options: SharingPolicyOptions\n) {\n async function requireCapabilityLink(input: CapabilityLinkPolicyInput): Promise<void> {\n if (!options.policy) return\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', input.documentId)\n .executeTakeFirstOrThrow()\n const context: CloudPolicyContext = {\n targetingKey: document.workspaceId,\n actorId: input.actorId,\n workspaceId: document.workspaceId,\n documentId: input.documentId,\n deploymentMode: options.deploymentMode ?? 'self-hosted'\n }\n // Whether guests may follow the link is checked when they do, so edit links still work for\n // people signed in to the server.\n if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.links, false, context))) {\n throw new DocumentForbiddenError()\n }\n }\n\n return { requireCapabilityLink }\n}\n\nexport type SharingPolicy = ReturnType<typeof createSharingPolicy>\n","import type {\n CreateDocumentShareInput,\n DocumentPermission,\n DocumentShare,\n ResolveDocumentShareInput,\n UpdateDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely, UpdateObject } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { shareContract } from '../contracts'\nimport { capabilityHashMatches, hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '../errors'\nimport { createSharingPolicy } from '../policy'\n\nconst SHARE_SECRET_BYTES = 24\n\nexport type DocumentShareCapability = {\n share: DocumentShare\n secret: string\n path: string\n}\n\nexport type ResolvedSharePrincipal =\n | { kind: 'user'; userId: string; name: string; email: string }\n | { kind: 'guest'; guestId: string; name: string }\n\nexport type ResolvedDocumentShare = {\n documentId: string\n permission: DocumentPermission\n principal: ResolvedSharePrincipal\n roomEpoch: number\n}\n\nexport type CapabilityServiceOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCapabilityService(\n database: Kysely<CloudDatabase>,\n options: CapabilityServiceOptions\n) {\n const sharingPolicy = createSharingPolicy(database, options)\n\n async function updateActiveShare(\n userId: string,\n documentId: string,\n shareId: string,\n changes: UpdateObject<CloudDatabase, 'documentShare'>\n ) {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .updateTable('documentShare')\n .set(changes)\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n return {\n async listShares(userId: string, documentId: string): Promise<DocumentShare[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentShare')\n .selectAll()\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt', 'desc')\n .execute()\n return rows.map(shareContract)\n },\n\n async createShare(\n userId: string,\n documentId: string,\n input: CreateDocumentShareInput\n ): Promise<DocumentShareCapability> {\n await requireSharingAccess(database, userId, documentId)\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const id = crypto.randomUUID()\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n return transaction\n .insertInto('documentShare')\n .values({\n id,\n documentId,\n permission: input.permission,\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n createdBy: userId,\n expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,\n revokedAt: null,\n lastUsedAt: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n })\n return { share: shareContract(row), secret, path: `/share/${id}#${secret}` }\n },\n\n async updateShare(\n userId: string,\n documentId: string,\n shareId: string,\n input: UpdateDocumentShareInput\n ): Promise<DocumentShare> {\n // Authorization comes first, so a caller without access learns nothing about the share\n // or the document's link policy.\n await requireSharingAccess(database, userId, documentId)\n const current = await database\n .selectFrom('documentShare')\n .select('id')\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!current) throw new DocumentNotFoundError()\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }\n if (input.permission) changes.permission = input.permission\n if (input.expiresAt !== undefined) {\n changes.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n }\n const row = await updateActiveShare(userId, documentId, shareId, changes)\n return shareContract(row)\n },\n\n async rotateShare(\n userId: string,\n documentId: string,\n shareId: string\n ): Promise<DocumentShareCapability> {\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const updated = await transaction\n .updateTable('documentShare')\n .set({\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n updatedAt: new Date()\n })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!updated) throw new DocumentNotFoundError()\n return updated\n })\n return { share: shareContract(row), secret, path: `/share/${shareId}#${secret}` }\n },\n\n async revokeShare(userId: string, documentId: string, shareId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentShare')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n },\n\n async resolveShare(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<ResolvedDocumentShare> {\n const row = await database\n .selectFrom('documentShare')\n .innerJoin('document', 'document.id', 'documentShare.documentId')\n .select([\n 'documentShare.id',\n 'documentShare.documentId',\n 'documentShare.permission',\n 'documentShare.secretHash',\n 'documentShare.roomEpoch',\n 'documentShare.expiresAt'\n ])\n .where('documentShare.id', '=', shareId)\n .where('documentShare.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (\n !row ||\n !capabilityHashMatches(row.secretHash, input.secret) ||\n (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now())\n ) {\n throw new DocumentShareInvalidError()\n }\n if (!actor && options.policy) {\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', row.documentId)\n .executeTakeFirstOrThrow()\n const featureKey =\n row.permission === 'edit' ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView\n if (\n !(await options.policy.boolean(featureKey, false, {\n targetingKey: document.workspaceId,\n workspaceId: document.workspaceId,\n documentId: row.documentId,\n deploymentMode: options.deploymentMode ?? 'self-hosted'\n }))\n ) {\n // Guests are not let in here; people signed in to the server are.\n throw new DocumentShareSignInRequiredError()\n }\n }\n await database\n .updateTable('documentShare')\n .set({ lastUsedAt: new Date() })\n .where('id', '=', shareId)\n .execute()\n return {\n documentId: row.documentId,\n permission: row.permission,\n principal: actor\n ? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }\n : {\n kind: 'guest',\n guestId: input.guestId ?? crypto.randomUUID(),\n name: input.guestName ?? 'Guest'\n },\n roomEpoch: row.roomEpoch\n }\n }\n }\n}\n\nexport type CapabilityService = ReturnType<typeof createCapabilityService>\n","import type { DocumentGrant, PutDocumentGrantInput } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { grantContract } from '../contracts'\n\nexport function createGrantService(database: Kysely<CloudDatabase>) {\n return {\n async listGrants(userId: string, documentId: string): Promise<DocumentGrant[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentGrant')\n .select(['id', 'documentId', 'userId', 'permission', 'createdBy', 'createdAt', 'updatedAt'])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt')\n .execute()\n return rows.map(grantContract)\n },\n\n async putGrant(\n userId: string,\n documentId: string,\n targetUserId: string,\n input: PutDocumentGrantInput\n ): Promise<DocumentGrant> {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .insertInto('documentGrant')\n .values({\n id: crypto.randomUUID(),\n documentId,\n userId: targetUserId,\n permission: input.permission,\n createdBy: userId,\n revokedAt: null\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'userId']).doUpdateSet({\n permission: input.permission,\n createdBy: userId,\n revokedAt: null,\n updatedAt: new Date()\n })\n )\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirstOrThrow()\n return grantContract(row)\n },\n\n /** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */\n async revokeGrant(userId: string, documentId: string, targetUserId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentGrant')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('documentId', '=', documentId)\n .where('userId', '=', targetUserId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n }\n }\n}\n\nexport type GrantService = ReturnType<typeof createGrantService>\n","import type { InvitationPreview } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentShareInvalidError } from '#cloud/server/sharing/errors'\nimport type { Kysely } from 'kysely'\n\nimport { capabilityHashMatches, decryptContinuationToken, encryptContinuationToken } from './crypto'\n\nconst CONTINUATION_LIFETIME_MS = 10 * 60_000\n\nexport type InvitationContinuationService = ReturnType<typeof createInvitationContinuationService>\n\nexport function createInvitationContinuationService(\n database: Kysely<CloudDatabase>,\n secret: string,\n validateInvitation: (invitationId: string, token: string) => Promise<InvitationPreview>\n) {\n return {\n async create(input: { invitationId: string; token: string }): Promise<{ id: string }> {\n await validateInvitation(input.invitationId, input.token)\n const id = crypto.randomUUID()\n await database\n .insertInto('invitationContinuation')\n .values({\n id,\n invitationId: input.invitationId,\n tokenEncrypted: await encryptContinuationToken(secret, input.token),\n expiresAt: new Date(Date.now() + CONTINUATION_LIFETIME_MS),\n consumedAt: null\n })\n .execute()\n return { id }\n },\n\n async consume(id: string): Promise<{ invitationId: string; token: string }> {\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .selectFrom('invitationContinuation')\n .select(['invitationId', 'tokenEncrypted', 'expiresAt', 'consumedAt'])\n .where('id', '=', id)\n .forUpdate()\n .executeTakeFirst()\n if (!row || row.consumedAt || new Date(row.expiresAt).getTime() <= Date.now()) {\n throw new DocumentShareInvalidError()\n }\n await transaction\n .updateTable('invitationContinuation')\n .set({ consumedAt: new Date() })\n .where('id', '=', id)\n .execute()\n return {\n invitationId: row.invitationId,\n token: await decryptContinuationToken(secret, row.tokenEncrypted)\n }\n })\n }\n }\n}\n\nexport function invitationTokenIsActive(\n invitation: {\n tokenHash: string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n revokedAt: Date | string | null\n },\n token: string\n): boolean {\n return (\n capabilityHashMatches(invitation.tokenHash, token) &&\n !invitation.acceptedAt &&\n !invitation.revokedAt &&\n new Date(invitation.expiresAt).getTime() > Date.now()\n )\n}\n\nexport function recipientHint(email: string): string {\n const [local = '', domain = ''] = email.split('@')\n const visible = local.slice(0, 2)\n return `${visible}${'*'.repeat(Math.max(3, local.length - visible.length))}@${domain}`\n}\n\nexport function invitationMatchesActor(actor: CloudActor, email: string): boolean {\n return email === actor.email.trim().toLowerCase()\n}\n","import type { CreateWorkspaceInput, WorkspaceRole, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type WorkspaceDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport async function listWorkspaces(\n database: WorkspaceDatabase,\n userId: string\n): Promise<WorkspaceSummary[]> {\n const rows = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspaceMember.role'\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspace.updatedAt', 'desc')\n .execute()\n\n return rows.map((row) => ({\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }))\n}\n\nexport async function findWorkspace(\n database: WorkspaceDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceSummary | undefined> {\n const row = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspaceMember.role'\n ])\n .where('workspace.id', '=', workspaceId)\n .where('workspaceMember.userId', '=', userId)\n .executeTakeFirst()\n return row\n ? {\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n : undefined\n}\n\nexport async function insertWorkspace(\n database: WorkspaceDatabase,\n actorId: string,\n input: CreateWorkspaceInput & { id: string; slug: string }\n): Promise<boolean> {\n const inserted = await database\n .insertInto('workspace')\n .values({\n id: input.id,\n name: input.name,\n slug: input.slug,\n createdBy: actorId\n })\n .onConflict((conflict) => conflict.column('slug').doNothing())\n .returning('id')\n .executeTakeFirst()\n return inserted !== undefined\n}\n\nexport async function insertWorkspaceMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n userId: string,\n role: WorkspaceRole\n): Promise<void> {\n await database.insertInto('workspaceMember').values({ workspaceId, userId, role }).execute()\n}\n","import type {\n CreateWorkspaceInvitationInput,\n CreatedWorkspaceInvitation,\n InvitationPreview,\n WorkspaceInvitation,\n WorkspaceMembers,\n WorkspaceRole,\n WorkspaceSummary\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email/types'\nimport {\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '#cloud/server/sharing/continuation'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { hashCapability } from '#cloud/server/sharing/crypto'\nimport { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'\nimport type { Kysely } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nconst INVITATION_SECRET_BYTES = 24\nconst INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000\n\n/** The workspace does not exist, or the person is not a member of it. */\nexport class WorkspaceNotFoundError extends Error {\n constructor() {\n super('Workspace not found')\n this.name = 'WorkspaceNotFoundError'\n }\n}\n\n/** Only a workspace's administrators may do this. */\nexport class WorkspaceForbiddenError extends Error {\n constructor() {\n super('Workspace administrators only')\n this.name = 'WorkspaceForbiddenError'\n }\n}\n\n/** The change would leave a workspace with members but no administrator. */\nexport class WorkspaceLastAdminError extends Error {\n constructor() {\n super('A workspace needs an administrator')\n this.name = 'WorkspaceLastAdminError'\n }\n}\n\n/**\n * A workspace still holds documents: live ones, or deleted ones kept until cleanup removes their\n * files, which deleting the workspace now would leave behind in object storage.\n */\nexport class WorkspaceNotEmptyError extends Error {\n constructor(readonly reason: 'documents' | 'pending-cleanup') {\n super('Workspace still holds documents')\n this.name = 'WorkspaceNotEmptyError'\n }\n}\n\n/** The person invited already belongs to the workspace. */\nexport class WorkspaceAlreadyMemberError extends Error {\n constructor() {\n super('Already a member of this workspace')\n this.name = 'WorkspaceAlreadyMemberError'\n }\n}\n\n/** The invitation is unknown, used, withdrawn, expired, or meant for someone else. */\nexport class WorkspaceInvitationInvalidError extends Error {\n constructor() {\n super('Workspace invitation is not valid')\n this.name = 'WorkspaceInvitationInvalidError'\n }\n}\n\nexport type WorkspaceMemberServiceOptions = {\n email?: TransactionalEmailService\n publicURL: string\n}\n\nfunction invitationContract(row: {\n id: string\n emailNormalized: string\n role: WorkspaceRole\n invitedBy: string\n inviterName: string | null\n invitedAt: Date | string\n expiresAt: Date | string\n}): WorkspaceInvitation {\n return {\n id: row.id,\n email: row.emailNormalized,\n role: row.role,\n invitedBy: { id: row.invitedBy, name: row.inviterName },\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }\n}\n\nasync function adminCount(database: WorkspaceDatabase, workspaceId: string): Promise<number> {\n const rows = await database\n .selectFrom('workspaceMember')\n .select('userId')\n .where('workspaceId', '=', workspaceId)\n .where('role', '=', 'admin')\n .forUpdate()\n .execute()\n return rows.length\n}\n\n/** A member's row, locked until the transaction ends so roles change one at a time. */\nasync function lockedMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n memberId: string\n): Promise<{ role: WorkspaceRole }> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .forUpdate()\n .executeTakeFirst()\n if (!member) throw new WorkspaceNotFoundError()\n return member\n}\n\n/**\n * Who belongs to a workspace and who is invited to it. Administrators invite, change roles, and\n * remove people; anyone may leave. A workspace with members always keeps an administrator.\n */\nexport function createWorkspaceMemberService(\n database: Kysely<CloudDatabase>,\n options: WorkspaceMemberServiceOptions\n) {\n async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new WorkspaceNotFoundError()\n return workspace\n }\n\n async function requireAdmin(userId: string, workspaceId: string): Promise<WorkspaceSummary> {\n const workspace = await membership(userId, workspaceId)\n if (workspace.role !== 'admin') throw new WorkspaceForbiddenError()\n return workspace\n }\n\n /** A workspace's members with their accounts; user ids are text in membership rows. */\n function memberUsers(workspaceId: string) {\n return database\n .selectFrom('workspaceMember')\n .innerJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('workspaceMember.userId')\n )\n )\n )\n .where('workspaceMember.workspaceId', '=', workspaceId)\n }\n\n function acceptanceURL(invitationId: string, token: string): string {\n return cloudInvitationURL(options.publicURL, invitationId, token)\n }\n\n /** Invites someone by email; a newer invitation to the same address replaces the older. */\n async function invite(\n userId: string,\n workspaceId: string,\n input: CreateWorkspaceInvitationInput\n ): Promise<CreatedWorkspaceInvitation> {\n const workspace = await requireAdmin(userId, workspaceId)\n const existing = await memberUsers(workspaceId)\n .select('workspaceMember.userId')\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)\n )\n .executeTakeFirst()\n if (existing) throw new WorkspaceAlreadyMemberError()\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', userId)\n .executeTakeFirst()\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const url = acceptanceURL(id, token)\n const row = await database.transaction().execute(async (transaction) => {\n await transaction\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('workspaceId', '=', workspaceId)\n .where('emailNormalized', '=', input.email)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .execute()\n const inserted = await transaction\n .insertInto('workspaceInvitation')\n .values({\n id,\n workspaceId,\n emailNormalized: input.email,\n role: input.role,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning(['id', 'emailNormalized', 'role', 'invitedBy', 'invitedAt', 'expiresAt'])\n .executeTakeFirstOrThrow()\n await options.email?.enqueue(\n {\n idempotencyKey: `workspace-invitation/${id}`,\n kind: 'workspace-invitation',\n recipientEmail: input.email,\n payload: {\n inviterName: inviter?.name ?? 'An OpenPencil user',\n workspaceName: workspace.name,\n role: input.role,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL: url\n }\n },\n transaction\n )\n return inserted\n })\n return {\n invitation: invitationContract({ ...row, inviterName: inviter?.name ?? null }),\n acceptanceURL: url\n }\n }\n\n return {\n async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {\n await requireAdmin(userId, workspaceId)\n await database\n .updateTable('workspace')\n .set({ name, updatedAt: new Date() })\n .where('id', '=', workspaceId)\n .execute()\n return membership(userId, workspaceId)\n },\n\n async list(userId: string, workspaceId: string): Promise<WorkspaceMembers> {\n const workspace = await membership(userId, workspaceId)\n const members = await memberUsers(workspaceId)\n .select([\n 'workspaceMember.userId',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n 'user.name',\n 'user.email',\n 'user.image'\n ])\n .orderBy('workspaceMember.createdAt')\n .execute()\n const invitations =\n workspace.role === 'admin'\n ? await database\n .selectFrom('workspaceInvitation')\n .leftJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('workspaceInvitation.invitedBy')\n )\n )\n )\n .select([\n 'workspaceInvitation.id',\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.invitedAt',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.invitedBy',\n 'user.name as inviterName'\n ])\n .where('workspaceInvitation.workspaceId', '=', workspaceId)\n .where('workspaceInvitation.acceptedAt', 'is', null)\n .where('workspaceInvitation.revokedAt', 'is', null)\n .where('workspaceInvitation.expiresAt', '>', new Date())\n .orderBy('workspaceInvitation.invitedAt')\n .execute()\n : []\n return {\n members: members.map((member) => ({\n userId: member.userId,\n name: member.name,\n email: member.email,\n image: member.image,\n role: member.role,\n joinedAt: dateString(member.createdAt) ?? ''\n })),\n invitations: invitations.map(invitationContract)\n }\n },\n\n invite,\n\n /** Sends a waiting invitation again with a new link; the old link stops working. */\n async resendInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<CreatedWorkspaceInvitation> {\n await requireAdmin(userId, workspaceId)\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select(['emailNormalized', 'role'])\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!invitation) throw new WorkspaceNotFoundError()\n return invite(userId, workspaceId, {\n email: invitation.emailNormalized,\n role: invitation.role\n })\n },\n\n async revokeInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<void> {\n await requireAdmin(userId, workspaceId)\n const result = await database\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new WorkspaceNotFoundError()\n },\n\n async updateRole(\n userId: string,\n workspaceId: string,\n memberId: string,\n role: WorkspaceRole\n ): Promise<void> {\n await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n if (member.role === 'admin' && role !== 'admin') {\n if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()\n }\n await transaction\n .updateTable('workspaceMember')\n .set({ role })\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n })\n },\n\n /** Deletes an empty workspace, with its members and invitations. */\n async delete(userId: string, workspaceId: string): Promise<void> {\n await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n // Locked first, so a document created meanwhile waits and then finds no workspace.\n await transaction\n .selectFrom('workspace')\n .select('id')\n .where('id', '=', workspaceId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const documents = await transaction\n .selectFrom('document')\n .select(['deletedAt'])\n .where('workspaceId', '=', workspaceId)\n .execute()\n if (documents.some((document) => document.deletedAt === null)) {\n throw new WorkspaceNotEmptyError('documents')\n }\n if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')\n await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()\n })\n },\n\n /** Removes a member, or lets someone leave; the last administrator cannot go. */\n async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {\n if (memberId === userId) await membership(userId, workspaceId)\n else await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {\n throw new WorkspaceLastAdminError()\n }\n await transaction\n .deleteFrom('workspaceMember')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n })\n },\n\n /** What a workspace invitation link offers, or null when the id is not one. */\n async preview(invitationId: string, token: string): Promise<InvitationPreview | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .innerJoin('workspace', 'workspace.id', 'workspaceInvitation.workspaceId')\n .select([\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.tokenHash',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.acceptedAt',\n 'workspaceInvitation.revokedAt',\n 'workspaceInvitation.invitedBy',\n 'workspace.name as workspaceName'\n ])\n .where('workspaceInvitation.id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (!invitationTokenIsActive(invitation, token)) throw new WorkspaceInvitationInvalidError()\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'workspace',\n workspaceName: invitation.workspaceName,\n role: invitation.role,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n },\n\n /**\n * Joins the workspace an invitation names, or returns null when the id is not a workspace\n * invitation. Someone already in it keeps the role they have.\n */\n async accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select([\n 'workspaceId',\n 'emailNormalized',\n 'role',\n 'tokenHash',\n 'expiresAt',\n 'acceptedAt',\n 'revokedAt'\n ])\n .where('id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, token)\n ) {\n throw new WorkspaceInvitationInvalidError()\n }\n return database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('workspaceMember')\n .values({\n workspaceId: invitation.workspaceId,\n userId: actor.userId,\n role: invitation.role\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'userId']).doNothing())\n .execute()\n await transaction\n .updateTable('workspaceInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n const member = await transaction\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', invitation.workspaceId)\n .where('userId', '=', actor.userId)\n .executeTakeFirstOrThrow()\n return { workspaceId: invitation.workspaceId, role: member.role }\n })\n }\n }\n}\n\nexport type WorkspaceMemberService = ReturnType<typeof createWorkspaceMemberService>\n","import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'\nimport {\n DocumentShareInvalidError,\n DocumentShareSignInRequiredError,\n InvitationDeliveryError\n} from '#cloud/server/sharing/errors'\nimport { WorkspaceInvitationInvalidError } from '#cloud/server/workspaces/members'\nimport type { Context } from 'hono'\n\nexport function sharingDomainError(context: Context, error: unknown): Response | null {\n if (\n error instanceof DocumentNotFoundError ||\n error instanceof DocumentShareInvalidError ||\n error instanceof WorkspaceInvitationInvalidError\n ) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n if (error instanceof InvitationDeliveryError) {\n return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return null\n}\n\nexport async function sharingRoute<T>(\n context: Context,\n action: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n const response = sharingDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n","import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\n\n/**\n * Who follows a link: the person signed in to the server, if any, whom the server lets in where\n * it turns guests away.\n */\nexport async function shareActor(\n request: Request,\n resolveSession?: CloudSessionResolver\n): Promise<CloudActor | undefined> {\n return resolveSession ? ((await resolveSession(request)) ?? undefined) : undefined\n}\n","import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport type { DocumentService } from '#cloud/server/documents'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { shareActor } from './actor'\n\nexport function createPublicDocumentRoutes(\n sharing: DocumentSharingService,\n documents: DocumentService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post('/shares/:shareId/document', validatedJSON(parseResolveDocumentShare), (context) =>\n sharingRoute(context, async () => {\n const resolution = await sharing.resolveShare(\n context.req.param('shareId'),\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json({\n resolution,\n document: await documents.downloadShared(resolution.documentId)\n })\n })\n )\n .post('/shares/:shareId/images', validatedJSON(parseRequestSharedImageLinks), (context) =>\n sharingRoute(context, async () => {\n const { checksums, ...share } = context.req.valid('json')\n const resolution = await sharing.resolveShare(\n context.req.param('shareId'),\n share,\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json(await documents.imageLinksShared(resolution.documentId, checksums))\n })\n )\n}\n","import type {\n AcceptDocumentInvitationInput,\n AcceptedInvitation,\n CreateDocumentInvitationInput,\n CreateInvitationContinuationInput,\n DocumentInvitation,\n InvitationPreview,\n WorkspaceRole\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { Kysely } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nimport { requireSharingAccess } from '../access'\nimport {\n createInvitationContinuationService,\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '../continuation'\nimport { dateString, grantContract, invitationContract } from '../contracts'\nimport { hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'\n\nconst INVITATION_SECRET_BYTES = 24\nconst INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000\n\n/** Workspace invitations share the invitation link; their ids are not document invitations. */\nexport type WorkspaceInvitationResolver = {\n preview(invitationId: string, token: string): Promise<InvitationPreview | null>\n accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null>\n}\n\nexport type InvitationServiceOptions = {\n workspaceInvitations?: WorkspaceInvitationResolver\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n}\n\nexport function createInvitationService(\n database: Kysely<CloudDatabase>,\n options: InvitationServiceOptions\n) {\n async function previewDocumentInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const invitation = await database\n .selectFrom('documentInvitation')\n .innerJoin('document', 'document.id', 'documentInvitation.documentId')\n .select([\n 'documentInvitation.emailNormalized',\n 'documentInvitation.permission',\n 'documentInvitation.tokenHash',\n 'documentInvitation.expiresAt',\n 'documentInvitation.acceptedAt',\n 'documentInvitation.revokedAt',\n 'documentInvitation.invitedBy',\n 'document.name as documentName'\n ])\n .where('documentInvitation.id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation || !invitationTokenIsActive(invitation, input.token)) {\n throw new DocumentShareInvalidError()\n }\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'document',\n documentName: invitation.documentName,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n permission: invitation.permission,\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n }\n\n const continuation = options.continuationSecret\n ? createInvitationContinuationService(\n database,\n options.continuationSecret,\n // Continuations are kept for document invitations only.\n async (invitationId, token) => previewDocumentInvitation(invitationId, { token })\n )\n : null\n\n return {\n async listInvitations(userId: string, documentId: string): Promise<DocumentInvitation[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentInvitation')\n .select([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('invitedAt')\n .execute()\n return rows.map(invitationContract)\n },\n\n async createInvitation(\n userId: string,\n documentId: string,\n input: CreateDocumentInvitationInput\n ): Promise<{ invitation: DocumentInvitation; token: string }> {\n await requireSharingAccess(database, userId, documentId)\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const deliveryContext =\n (options.delivery || options.outbox) && options.publicURL\n ? await Promise.all([\n database\n .selectFrom('user')\n .select('name')\n .where('id', '=', userId)\n .executeTakeFirst(),\n database\n .selectFrom('document')\n .select('name')\n .where('id', '=', documentId)\n .executeTakeFirstOrThrow()\n ])\n : null\n const acceptanceURL =\n deliveryContext && options.publicURL\n ? cloudInvitationURL(options.publicURL, id, token)\n : null\n const message =\n deliveryContext && acceptanceURL\n ? {\n deliveryId: id,\n recipientEmail: input.email,\n inviterName: deliveryContext[0]?.name ?? 'An OpenPencil user',\n documentName: deliveryContext[1].name,\n permission: input.permission,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL\n }\n : null\n const row = await database.transaction().execute(async (transaction) => {\n const inserted = await transaction\n .insertInto('documentInvitation')\n .values({\n id,\n documentId,\n emailNormalized: input.email,\n permission: input.permission,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .executeTakeFirstOrThrow()\n if (options.outbox && message) {\n await options.outbox.enqueueDocumentInvitation(message, transaction)\n }\n return inserted\n })\n const invitation = invitationContract(row)\n if (options.delivery && message && !options.outbox) {\n try {\n await options.delivery.sendDocumentInvitation(message)\n } catch (error) {\n await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', id)\n .execute()\n throw new InvitationDeliveryError('Invitation delivery failed', { cause: error })\n }\n }\n return { invitation, token }\n },\n\n async createInvitationContinuation(input: CreateInvitationContinuationInput) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.create(input)\n },\n\n async consumeInvitationContinuation(id: string) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.consume(id)\n },\n\n /** What an invitation link offers: a document, or a workspace when the id is one of those. */\n async previewInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const workspace = await options.workspaceInvitations?.preview(invitationId, input.token)\n return workspace ?? previewDocumentInvitation(invitationId, input)\n },\n\n async acceptInvitation(\n actor: CloudActor,\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<AcceptedInvitation> {\n const workspace = await options.workspaceInvitations?.accept(actor, invitationId, input.token)\n if (workspace) return { kind: 'workspace', ...workspace }\n const invitation = await database\n .selectFrom('documentInvitation')\n .select([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'tokenHash',\n 'expiresAt',\n 'acceptedAt',\n 'revokedAt'\n ])\n .where('id', '=', invitationId)\n .executeTakeFirst()\n if (\n !invitation ||\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, input.token)\n ) {\n throw new DocumentShareInvalidError()\n }\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .insertInto('documentGrant')\n .values({\n id: crypto.randomUUID(),\n documentId: invitation.documentId,\n userId: actor.userId,\n permission: invitation.permission,\n // The grant is the inviter's, so \"shared by\" names them, not the recipient.\n createdBy: invitation.invitedBy,\n revokedAt: null\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'userId']).doUpdateSet({\n permission: invitation.permission,\n createdBy: invitation.invitedBy,\n revokedAt: null,\n updatedAt: new Date()\n })\n )\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirstOrThrow()\n await transaction\n .updateTable('documentInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n return { kind: 'document' as const, grant: grantContract(row) }\n })\n },\n\n async revokeInvitation(\n userId: string,\n documentId: string,\n invitationId: string\n ): Promise<void> {\n await requireSharingAccess(database, userId, documentId)\n const result = await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n }\n }\n}\n\nexport type InvitationService = ReturnType<typeof createInvitationService>\n","import {\n parseAcceptDocumentInvitation,\n parseCreateInvitationContinuation,\n parseCreateDocumentInvitation,\n parseLookupCloudUser,\n parseCreateDocumentShare,\n parsePutDocumentGrant,\n parseResolveDocumentShare,\n parseUpdateDocumentShare\n} from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport type { DocumentSharingService } from '#cloud/server/sharing/service'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { shareActor } from './actor'\n\nexport type SharingRouteEnvironment = {\n Variables: { actor: CloudActor }\n}\n\nexport function createDocumentSharingRoutes(\n service: DocumentSharingService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<SharingRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/invitations',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n (context) => context.req.method !== 'POST',\n (context) => context.req.param('documentId') ?? 'unknown'\n )\n )\n }\n return router\n .post('/documents/:documentId/users/lookup', validatedJSON(parseLookupCloudUser), (context) =>\n sharingRoute(context, async () =>\n context.json({\n user: await service.lookupUser(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n )\n })\n )\n )\n .get('/documents/:documentId/users/:userId', (context) =>\n sharingRoute(context, async () =>\n context.json({\n user: await service.userProfile(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('userId')\n )\n })\n )\n )\n .get('/documents/:documentId/shares', (context) =>\n sharingRoute(context, async () =>\n context.json({\n shares: await service.listShares(\n context.get('actor').userId,\n context.req.param('documentId')\n )\n })\n )\n )\n .post('/documents/:documentId/shares', validatedJSON(parseCreateDocumentShare), (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createShare(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/shares/:shareId',\n validatedJSON(parseUpdateDocumentShare),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n share: await service.updateShare(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('shareId'),\n context.req.valid('json')\n )\n })\n )\n )\n .post('/documents/:documentId/shares/:shareId/rotate', (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.rotateShare(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('shareId')\n )\n )\n )\n )\n .delete('/documents/:documentId/shares/:shareId', (context) =>\n sharingRoute(context, async () => {\n await service.revokeShare(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('shareId')\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/grants', (context) =>\n sharingRoute(context, async () =>\n context.json({\n grants: await service.listGrants(\n context.get('actor').userId,\n context.req.param('documentId')\n )\n })\n )\n )\n .put('/documents/:documentId/grants/:userId', validatedJSON(parsePutDocumentGrant), (context) =>\n sharingRoute(context, async () =>\n context.json({\n grant: await service.putGrant(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('userId'),\n context.req.valid('json')\n )\n })\n )\n )\n .delete('/documents/:documentId/grants/:userId', (context) =>\n sharingRoute(context, async () => {\n await service.revokeGrant(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('userId')\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/invitations', (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitations: await service.listInvitations(\n context.get('actor').userId,\n context.req.param('documentId')\n )\n })\n )\n )\n .post(\n '/documents/:documentId/invitations',\n validatedJSON(parseCreateDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createInvitation(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/invitations/:invitationId/accept',\n validatedJSON(parseAcceptDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n accepted: await service.acceptInvitation(\n context.get('actor'),\n context.req.param('invitationId'),\n context.req.valid('json')\n )\n })\n )\n )\n .delete('/documents/:documentId/invitations/:invitationId', (context) =>\n sharingRoute(context, async () => {\n await service.revokeInvitation(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('invitationId')\n )\n return context.body(null, 204)\n })\n )\n}\n\nexport function createPublicSharingRoutes(\n service: DocumentSharingService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post(\n '/invitations/continuations',\n validatedJSON(parseCreateInvitationContinuation),\n (context) =>\n sharingRoute(context, async () =>\n context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)\n )\n )\n .post('/invitations/continuations/:continuationId/consume', (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.consumeInvitationContinuation(context.req.param('continuationId'))\n )\n )\n )\n .post(\n '/invitations/:invitationId/preview',\n validatedJSON(parseAcceptDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitation: await service.previewInvitation(\n context.req.param('invitationId'),\n context.req.valid('json')\n )\n })\n )\n )\n .post('/shares/:shareId/resolve', validatedJSON(parseResolveDocumentShare), (context) =>\n sharingRoute(context, async () =>\n context.json({\n resolution: await service.resolveShare(\n context.req.param('shareId'),\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n })\n )\n )\n}\n","import type { CloudUserProfile, LookupCloudUserInput } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nimport { requireSharingAccess } from './access'\nimport {\n createCapabilityService,\n type DocumentShareCapability,\n type ResolvedDocumentShare,\n type ResolvedSharePrincipal\n} from './capabilities/service'\nimport { createGrantService } from './grants/service'\nimport { createInvitationService, type WorkspaceInvitationResolver } from './invitations/service'\n\nexport type { DocumentShareCapability, ResolvedDocumentShare, ResolvedSharePrincipal }\n\nexport type DocumentSharingServiceOptions = {\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n workspaceInvitations?: WorkspaceInvitationResolver\n}\n\nexport function createDocumentSharingService(\n database: Kysely<CloudDatabase>,\n options: DocumentSharingServiceOptions = {}\n) {\n const capabilities = createCapabilityService(database, options)\n const grants = createGrantService(database)\n const invitations = createInvitationService(database, options)\n\n return {\n async lookupUser(\n userId: string,\n documentId: string,\n input: LookupCloudUserInput\n ): Promise<CloudUserProfile | null> {\n await requireSharingAccess(database, userId, documentId)\n const user = await database\n .selectFrom('user')\n .select(['id', 'name', 'email', 'image'])\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)\n )\n .executeTakeFirst()\n return user ?? null\n },\n\n async userProfile(\n userId: string,\n documentId: string,\n profileUserId: string\n ): Promise<CloudUserProfile | null> {\n await requireSharingAccess(database, userId, documentId)\n // Only people connected to this document: its owner, its workspace's members, the holders\n // and givers of its grants, and the people who invited others to it. User IDs are text in\n // these tables, so they are compared with the requested ID rather than `user.id`.\n const related = await database\n .selectFrom('document')\n .select('document.id')\n .where('document.id', '=', documentId)\n .where((expression) =>\n expression.or([\n expression('document.createdBy', '=', profileUserId),\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', profileUserId)\n ),\n expression.exists(\n expression\n .selectFrom('documentGrant')\n .select('documentGrant.id')\n .whereRef('documentGrant.documentId', '=', 'document.id')\n .where((grant) =>\n grant.or([\n grant.and([\n grant('documentGrant.userId', '=', profileUserId),\n grant('documentGrant.revokedAt', 'is', null)\n ]),\n grant('documentGrant.createdBy', '=', profileUserId)\n ])\n )\n ),\n expression.exists(\n expression\n .selectFrom('documentInvitation')\n .select('documentInvitation.id')\n .whereRef('documentInvitation.documentId', '=', 'document.id')\n .where('documentInvitation.invitedBy', '=', profileUserId)\n )\n ])\n )\n .executeTakeFirst()\n if (!related) return null\n const user = await database\n .selectFrom('user')\n .select(['id', 'name', 'email', 'image'])\n .where('id', '=', profileUserId)\n .executeTakeFirst()\n return user ?? null\n },\n\n ...capabilities,\n ...grants,\n ...invitations\n }\n}\n\nexport type DocumentSharingService = ReturnType<typeof createDocumentSharingService>\n","import { parseResolveDocumentShare } from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration/service'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CollaborationRouteEnvironment = { Variables: { actor: CloudActor } }\n\nfunction notFound(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError || error instanceof DocumentShareInvalidError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return null\n}\n\nexport function createCollaborationRoutes(\n service: CollaborationTicketService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<CollaborationRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/collaboration-ticket',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.collaborationTicket,\n undefined,\n (context) => context.req.param('documentId') ?? 'unknown-document'\n )\n )\n }\n return router.post('/documents/:documentId/collaboration-ticket', async (context) => {\n try {\n return context.json({\n ticket: await service.issueUserTicket(context.get('actor'), context.req.param('documentId'))\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n })\n}\n\nexport function createPublicCollaborationRoutes(\n service: CollaborationTicketService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono().post(\n '/shares/:shareId/collaboration-ticket',\n validatedJSON(parseResolveDocumentShare),\n async (context) => {\n try {\n return context.json({\n ticket: await service.issueShareTicket(\n context.req.param('shareId'),\n context.req.valid('json'),\n resolveSession ? ((await resolveSession(context.req.raw)) ?? undefined) : undefined\n )\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n","import {\n RELAY_DOCUMENT_PARAM,\n type CollaborationPrincipal,\n type CollaborationTicket,\n type DocumentPermission,\n type ResolveDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { base64url, SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\nimport { withQuery } from 'ufo'\n\nconst TICKET_LIFETIME_SECONDS = 5 * 60\n\nasync function derivedRoomKey(authSecret: string, documentId: string, roomEpoch: number) {\n const inputBytes = new TextEncoder().encode(`${authSecret}:room:${documentId}:${roomEpoch}`)\n const key = await crypto.subtle.importKey('raw', inputBytes, 'HKDF', false, ['deriveBits'])\n const bits = await crypto.subtle.deriveBits(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new TextEncoder().encode(`openpencil-cloud:${documentId}`),\n info: new TextEncoder().encode(`collaboration-room:${roomEpoch}`)\n },\n key,\n 256\n )\n return base64url.encode(new Uint8Array(bits))\n}\n\nexport type CollaborationTicketClaims = {\n authSecret: string\n documentId: string\n principal: CollaborationPrincipal\n permission: DocumentPermission\n roomEpoch: number\n /**\n * The relay that enforces writes; without one the ticket is for peer-to-peer rooms. The ticket's\n * URL names the document, so a runtime can route the socket to where the room lives.\n */\n relayURL?: string\n}\n\n/** Signs a ticket for a document's collaboration room once access has been decided. */\nexport async function signCollaborationTicket({\n authSecret,\n documentId,\n principal,\n permission,\n roomEpoch,\n relayURL\n}: CollaborationTicketClaims): Promise<CollaborationTicket> {\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAtSeconds = issuedAt + TICKET_LIFETIME_SECONDS\n const roomId = `cloud:${documentId}:${roomEpoch}`\n const roomKey = await derivedRoomKey(authSecret, documentId, roomEpoch)\n const claims = {\n documentId,\n roomId,\n principal,\n permission,\n roomEpoch,\n serverEnforcedWrites: Boolean(relayURL)\n }\n const token = await new SignJWT(claims)\n .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAtSeconds)\n .setSubject(principal.kind === 'user' ? principal.userId : principal.guestId)\n .sign(new TextEncoder().encode(authSecret))\n return {\n token,\n provider: relayURL ? ('relay' as const) : ('trystero' as const),\n ...(relayURL ? { serverURL: withQuery(relayURL, { [RELAY_DOCUMENT_PARAM]: documentId }) } : {}),\n ...claims,\n roomKey,\n expiresAt: new Date(expiresAtSeconds * 1000).toISOString()\n }\n}\n\nexport type CollaborationTicketServiceOptions = {\n database: Kysely<CloudDatabase>\n sharing: DocumentSharingService\n authSecret: string\n relayURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCollaborationTicketService({\n database,\n sharing,\n authSecret,\n relayURL,\n policy,\n deploymentMode = 'self-hosted'\n}: CollaborationTicketServiceOptions) {\n return {\n async issueUserTicket(actor: CloudActor, documentId: string): Promise<CollaborationTicket> {\n const access = await resolveDocumentAccess(database, actor.userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (policy) {\n const workspace = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', documentId)\n .executeTakeFirstOrThrow()\n if (\n !(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, {\n targetingKey: workspace.workspaceId,\n actorId: actor.userId,\n workspaceId: workspace.workspaceId,\n documentId,\n deploymentMode\n }))\n ) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId,\n principal: { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },\n permission: access.permission,\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n },\n\n async issueShareTicket(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<CollaborationTicket> {\n const resolved = await sharing.resolveShare(shareId, input, actor)\n if (policy) {\n const workspace = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', resolved.documentId)\n .executeTakeFirstOrThrow()\n const context = {\n targetingKey: workspace.workspaceId,\n ...(actor ? { actorId: actor.userId } : {}),\n workspaceId: workspace.workspaceId,\n documentId: resolved.documentId,\n deploymentMode\n }\n if (!(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context))) {\n throw new DocumentNotFoundError()\n }\n if (!actor && !(await policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context))) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', resolved.documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId: resolved.documentId,\n principal: resolved.principal,\n permission: resolved.permission,\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n }\n }\n}\n\nexport type CollaborationTicketService = ReturnType<typeof createCollaborationTicketService>\n","import {\n collaborationPrincipalSchema,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport { jwtVerify } from 'jose'\nimport * as v from 'valibot'\n\nconst relayClaimsSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n principal: collaborationPrincipalSchema,\n permission: v.picklist(['view', 'edit']),\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n serverEnforcedWrites: v.literal(true),\n exp: v.pipe(v.number(), v.integer())\n})\n\nexport type RelayAuthorization = {\n roomId: string\n documentId: string\n roomEpoch: number\n permission: DocumentPermission\n principal: CollaborationPrincipal\n /** When the ticket stops being valid, in milliseconds since the epoch. */\n expiresAt: number\n}\n\n/** Verifies a collaboration ticket issued for the relay; throws for anything else. */\nexport async function authorizeRelayTicket(\n token: string,\n authSecret: string\n): Promise<RelayAuthorization> {\n const verified = await jwtVerify(token, new TextEncoder().encode(authSecret), {\n algorithms: ['HS256']\n })\n const claims = v.parse(relayClaimsSchema, verified.payload)\n if (claims.roomId !== `cloud:${claims.documentId}:${claims.roomEpoch}`) {\n throw new Error('Collaboration ticket names a different room')\n }\n return {\n roomId: claims.roomId,\n documentId: claims.documentId,\n roomEpoch: claims.roomEpoch,\n permission: claims.permission,\n principal: claims.principal,\n expiresAt: claims.exp * 1000\n }\n}\n\nexport function principalKey(principal: CollaborationPrincipal): string {\n return principal.kind === 'user' ? `user:${principal.userId}` : `guest:${principal.guestId}`\n}\n","import {\n presenceName,\n type CloudPresence,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as v from 'valibot'\n\nconst awarenessStateSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.looseObject({ user: v.optional(v.looseObject({})) })\n)\n\ntype AwarenessEntry = { clientId: number; clock: number; state: string }\n\nfunction decodeEntries(update: Uint8Array): AwarenessEntry[] | null {\n try {\n const decoder = decoding.createDecoder(update)\n const count = decoding.readVarUint(decoder)\n const entries: AwarenessEntry[] = []\n for (let index = 0; index < count; index++) {\n entries.push({\n clientId: decoding.readVarUint(decoder),\n clock: decoding.readVarUint(decoder),\n state: decoding.readVarString(decoder)\n })\n }\n return decoder.pos === update.byteLength ? entries : null\n } catch {\n return null\n }\n}\n\nfunction encodeEntries(entries: AwarenessEntry[]): Uint8Array {\n return encoding.encode((encoder) => {\n encoding.writeVarUint(encoder, entries.length)\n for (const entry of entries) {\n encoding.writeVarUint(encoder, entry.clientId)\n encoding.writeVarUint(encoder, entry.clock)\n encoding.writeVarString(encoder, entry.state)\n }\n })\n}\n\n/** Who the relay verified a peer to be, as other peers see it in presence. */\nexport type VerifiedPresence = {\n principal: CollaborationPrincipal\n permission: DocumentPermission\n}\n\nfunction verifiedIdentity({ principal, permission }: VerifiedPresence): CloudPresence {\n return {\n kind: principal.kind,\n id: principal.kind === 'user' ? principal.userId : principal.guestId,\n name: principal.name,\n permission\n }\n}\n\nexport type StampedAwareness = {\n /** The update to forward, or null when nothing in it may be forwarded. */\n update: Uint8Array | null\n /** Presence clients this update introduced for the peer. */\n claimed: number[]\n}\n\n/**\n * Rewrites a peer's presence update so others see who the relay verified rather than what the\n * peer claims: the display name comes from the ticket, and a `cloud` field carries the verified\n * identity and permission. Entries for presence clients another peer owns are dropped, so one\n * peer cannot speak for another; removals pass through for the peer's own clients only.\n */\nexport function stampAwareness(\n update: Uint8Array,\n presence: VerifiedPresence,\n ownedByOthers: (clientId: number) => boolean\n): StampedAwareness {\n const entries = decodeEntries(update)\n if (!entries) return { update: null, claimed: [] }\n const identity = verifiedIdentity(presence)\n const forwarded: AwarenessEntry[] = []\n const claimed: number[] = []\n for (const entry of entries) {\n if (ownedByOthers(entry.clientId)) continue\n if (entry.state === 'null') {\n forwarded.push(entry)\n continue\n }\n const parsed = v.safeParse(awarenessStateSchema, entry.state)\n if (!parsed.success) continue\n const state = {\n ...parsed.output,\n // The ticket's name, cut to what peers accept, so a long one cannot hide the member.\n user: { ...parsed.output.user, name: presenceName(identity.name) },\n cloud: identity\n }\n claimed.push(entry.clientId)\n forwarded.push({ ...entry, state: JSON.stringify(state) })\n }\n return { update: forwarded.length > 0 ? encodeEntries(forwarded) : null, claimed }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nimport type { CollaborationRelayOptions } from './hub'\n\n/** The relay's lookups of a document: its participant limit under `policy`, and its epoch. */\nexport function relayDocumentLookups(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n deploymentMode: 'official' | 'self-hosted'\n): Pick<CollaborationRelayOptions, 'maximumParticipants' | 'currentRoomEpoch'> {\n return {\n async maximumParticipants(documentId) {\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', documentId)\n .executeTakeFirst()\n if (!document) return 0\n const limit = await policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, -1, {\n targetingKey: document.workspaceId,\n workspaceId: document.workspaceId,\n documentId,\n deploymentMode\n })\n return limit < 0 ? null : limit\n },\n async currentRoomEpoch(documentId) {\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .executeTakeFirst()\n return document?.collaborationEpoch ?? null\n }\n }\n}\n","import {\n COLLAB_ACTIONS,\n createRelayClientAssembler,\n encodeSyncReply,\n decodeRelayClientFrame,\n decodeRoomUpdate,\n MAX_COLLAB_MESSAGE_BYTES,\n RELAY_CLOSE,\n RELAY_SERVER_PEER,\n relayServerMessages,\n type RelayServerFrame\n} from '#cloud/contract'\nimport * as Y from 'yjs'\n\nimport { authorizeRelayTicket, principalKey, type RelayAuthorization } from './authorize'\nimport { stampAwareness } from './awareness'\nimport type { CollaborationStateStore } from './persistence'\n\n/** One client's socket, as a runtime adapter hands it to the relay. */\nexport type RelaySocket = {\n send(data: Uint8Array): void\n close(code: number, reason: string): void\n}\n\n/** What the adapter reports back about that socket. */\nexport type RelayConnection = {\n receive(data: Uint8Array): void\n closed(): void\n}\n\nexport type CollaborationRelayOptions = {\n authSecret: string\n store: CollaborationStateStore\n /**\n * The one document this relay serves, for runtimes that run a relay per document; tickets for\n * any other document are refused.\n */\n documentId?: string\n /**\n * The most one socket message may carry. An editor's larger frames arrive as fragments joined\n * up to `MAX_COLLAB_MESSAGE_BYTES`; anyone else's frame must fit in one message.\n */\n maximumMessageBytes: number\n maximumConnectionsPerRoom: number\n /** The participant limit policy sets for a document, or null for none. */\n maximumParticipants?: (documentId: string) => Promise<number | null>\n /**\n * The document's current collaboration epoch, which a restore advances; a ticket for an earlier\n * room is turned away so nobody rejoins the document as it was.\n */\n currentRoomEpoch?: (documentId: string) => Promise<number | null>\n /** How long after a change the room's document is saved. */\n persistDelayMs?: number\n /** How long a room whose last save failed waits before saving again. */\n persistRetryMs?: number\n /** How long a socket may stay open without presenting a ticket. */\n authTimeoutMs?: number\n onError?: (message: string, error: unknown) => void\n}\n\n/** Messages a viewer may send; their document writes never leave the relay. */\nconst VIEWER_ACTIONS = new Set<string>([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness])\n\ntype Peer = {\n id: string\n socket: RelaySocket\n authorization: RelayAuthorization\n presenceClients: Set<number>\n expiry?: ReturnType<typeof setTimeout>\n}\n\ntype Room = {\n id: string\n identity: { documentId: string; roomEpoch: number }\n document: Y.Doc\n peers: Map<string, Peer>\n persistTimer: ReturnType<typeof setTimeout> | null\n}\n\nexport type CollaborationRelay = ReturnType<typeof createCollaborationRelay>\n\n/**\n * A runtime-neutral relay for collaboration rooms. It forwards room messages between peers and\n * joins every room as a peer itself: it holds the room's document, answers sync requests from\n * it, saves it, drops document writes from viewers, and stamps presence with verified identity.\n */\nexport function createCollaborationRelay(options: CollaborationRelayOptions) {\n const rooms = new Map<string, Room>()\n const opening = new Map<string, Promise<Room>>()\n /** Rooms whose last peer left and whose document is still being saved. */\n const closing = new Map<string, Promise<void>>()\n /** Set by `close()`: a failed save then drops the room instead of retrying. */\n let shuttingDown = false\n const persistDelayMs = options.persistDelayMs ?? 2_000\n const persistRetryMs = options.persistRetryMs ?? 30_000\n const authTimeoutMs = options.authTimeoutMs ?? 10_000\n const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error))\n\n function send(socket: RelaySocket, frame: RelayServerFrame) {\n for (const message of relayServerMessages(frame)) socket.send(message)\n }\n\n function sendAll(sockets: Iterable<RelaySocket>, frame: RelayServerFrame) {\n const messages = relayServerMessages(frame)\n for (const socket of sockets) for (const message of messages) socket.send(message)\n }\n\n async function openRoom(authorization: RelayAuthorization): Promise<Room> {\n const existing = rooms.get(authorization.roomId)\n if (existing) return existing\n const pending = opening.get(authorization.roomId)\n if (pending) return pending\n const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }\n const created = (async () => {\n // A room reopened while its last save is in flight must load what that save writes, or,\n // when the save failed, take the room it kept.\n await closing.get(authorization.roomId)\n const kept = rooms.get(authorization.roomId)\n if (kept) return kept\n const document = new Y.Doc()\n const state = await options.store.load(identity)\n if (state) Y.applyUpdate(document, state)\n const room: Room = {\n id: authorization.roomId,\n identity,\n document,\n peers: new Map(),\n persistTimer: null\n }\n document.on('update', () => schedulePersist(room))\n rooms.set(room.id, room)\n return room\n })()\n opening.set(authorization.roomId, created)\n try {\n return await created\n } finally {\n opening.delete(authorization.roomId)\n }\n }\n\n /** Saves the room's document; false when the store refused it. */\n async function persist(room: Room): Promise<boolean> {\n if (room.persistTimer) clearTimeout(room.persistTimer)\n room.persistTimer = null\n try {\n await options.store.store(room.identity, Y.encodeStateAsUpdate(room.document))\n return true\n } catch (error) {\n report('Saving a collaboration room failed:', error)\n return false\n }\n }\n\n function schedulePersist(room: Room) {\n room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs)\n }\n\n /**\n * Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as\n * V1 updates; only what peers exchange is V2.\n */\n function applyToRoom(room: Room, peer: Peer, namespace: string, payload: Uint8Array): boolean {\n try {\n const update = decodeRoomUpdate(payload, {\n limit: MAX_COLLAB_MESSAGE_BYTES,\n compressed: namespace === COLLAB_ACTIONS.syncReply\n })\n if (!update) {\n peer.socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration update is too large')\n return false\n }\n Y.applyUpdateV2(room.document, update, peer.id)\n return true\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed document update')\n return false\n }\n }\n\n function forward(\n room: Room,\n from: Peer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const frame: RelayServerFrame = { type: 'message', namespace, from: from.id, payload }\n const recipients = target\n ? [room.peers.get(target)]\n : [...room.peers.values()].filter((peer) => peer !== from)\n sendAll(\n recipients.flatMap((peer) => (peer ? [peer.socket] : [])),\n frame\n )\n }\n\n function handleServerMessage(room: Room, peer: Peer, namespace: string, payload: Uint8Array) {\n if (namespace === COLLAB_ACTIONS.syncStep1) {\n let reply: Uint8Array\n try {\n reply = encodeSyncReply(room.document, payload)\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed state vector')\n return\n }\n send(peer.socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncReply,\n from: RELAY_SERVER_PEER,\n payload: reply\n })\n } else if (namespace === COLLAB_ACTIONS.syncReply) {\n applyToRoom(room, peer, namespace, payload)\n }\n }\n\n function handleMessage(\n room: Room,\n peer: Peer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const readOnly = peer.authorization.permission === 'view'\n if (readOnly && !VIEWER_ACTIONS.has(namespace)) return\n // Only the server says the history changed.\n if (namespace === COLLAB_ACTIONS.versions) return\n\n let forwarded = payload\n if (namespace === COLLAB_ACTIONS.awareness) {\n const stamped = stampAwareness(payload, peer.authorization, (clientId) =>\n [...room.peers.values()].some(\n (other) => other !== peer && other.presenceClients.has(clientId)\n )\n )\n for (const clientId of stamped.claimed) peer.presenceClients.add(clientId)\n if (!stamped.update) return\n forwarded = stamped.update\n }\n\n if (target === RELAY_SERVER_PEER) {\n handleServerMessage(room, peer, namespace, payload)\n return\n }\n if (\n (namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) &&\n !applyToRoom(room, peer, namespace, payload)\n ) {\n return\n }\n forward(room, peer, namespace, target, forwarded)\n }\n\n function scheduleExpiry(peer: Peer) {\n clearTimeout(peer.expiry)\n peer.expiry = setTimeout(\n () => peer.socket.close(RELAY_CLOSE.expired, 'Collaboration ticket expired'),\n Math.max(0, peer.authorization.expiresAt - Date.now())\n )\n }\n\n async function admit(\n socket: RelaySocket,\n authorization: RelayAuthorization\n ): Promise<Peer | null> {\n const limit = await options.maximumParticipants?.(authorization.documentId)\n let room: Room\n let epoch: number | null | undefined\n // The room's last peer may have left while it opened, or a restore ended it; a closed room\n // takes no newcomers. The epoch is read once the room is open, so a restore cannot slip between.\n do {\n room = await openRoom(authorization)\n epoch = await options.currentRoomEpoch?.(authorization.documentId)\n } while (rooms.get(room.id) !== room)\n if (epoch != null && authorization.roomEpoch < epoch) {\n socket.close(RELAY_CLOSE.restored, 'The document was restored')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const capacity = Math.min(limit ?? Number.POSITIVE_INFINITY, options.maximumConnectionsPerRoom)\n if (room.peers.size >= capacity) {\n socket.close(RELAY_CLOSE.roomFull, 'Collaboration room is full')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const peer: Peer = {\n id: crypto.randomUUID(),\n socket,\n authorization,\n presenceClients: new Set()\n }\n scheduleExpiry(peer)\n send(socket, {\n type: 'welcome',\n peerId: peer.id,\n peers: [RELAY_SERVER_PEER, ...room.peers.keys()]\n })\n for (const other of room.peers.values()) send(other.socket, { type: 'join', peerId: peer.id })\n room.peers.set(peer.id, peer)\n // Ask for what the newcomer has that the room lacks, such as edits made offline.\n if (authorization.permission === 'edit') {\n send(socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncStep1,\n from: RELAY_SERVER_PEER,\n payload: Y.encodeStateVector(room.document)\n })\n }\n return peer\n }\n\n async function saveAndClose(room: Room) {\n if ((await persist(room)) || shuttingDown) {\n room.document.destroy()\n return\n }\n // The room holds edits the store doesn't have: keep it for whoever joins next, and save\n // again later, closing it once a save lands while nobody is in it.\n rooms.set(room.id, room)\n room.persistTimer = setTimeout(() => {\n void (room.peers.size > 0 ? persist(room) : leaveRoom(room))\n }, persistRetryMs)\n }\n\n async function leaveRoom(room: Room) {\n if (room.peers.size > 0 || rooms.get(room.id) !== room) return\n rooms.delete(room.id)\n const saved = saveAndClose(room)\n closing.set(room.id, saved)\n try {\n await saved\n } finally {\n if (closing.get(room.id) === saved) closing.delete(room.id)\n }\n }\n\n function depart(peer: Peer) {\n clearTimeout(peer.expiry)\n const room = rooms.get(peer.authorization.roomId)\n if (!room?.peers.delete(peer.id)) return\n for (const other of room.peers.values()) send(other.socket, { type: 'leave', peerId: peer.id })\n void leaveRoom(room)\n }\n\n return {\n connect(socket: RelaySocket): RelayConnection {\n let peer: Peer | null = null\n /** Read through an object, since it changes across awaits and between messages. */\n const state = { closed: false, authenticating: false }\n const isClosed = () => state.closed\n const queued: Uint8Array[] = []\n let queuedBytes = 0\n // Only an editor's writes can be large: a viewer's frames, and a peer's before it is\n // admitted, fit in one message, so nobody else can make the relay hold more.\n const assembler = createRelayClientAssembler(() =>\n peer?.authorization.permission === 'edit'\n ? MAX_COLLAB_MESSAGE_BYTES\n : options.maximumMessageBytes\n )\n const authTimer = setTimeout(\n () => socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket'),\n authTimeoutMs\n )\n\n async function authenticate(token: string) {\n let authorization: RelayAuthorization\n try {\n authorization = await authorizeRelayTicket(token, options.authSecret)\n } catch {\n socket.close(RELAY_CLOSE.unauthorized, 'Invalid collaboration ticket')\n return\n }\n if (options.documentId !== undefined && authorization.documentId !== options.documentId) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different document')\n return\n }\n if (state.closed) return\n if (peer) {\n // A refreshed ticket keeps the peer in its room as the same person; a lowered\n // permission applies from now on.\n const current = peer.authorization\n if (\n authorization.roomId !== current.roomId ||\n principalKey(authorization.principal) !== principalKey(current.principal)\n ) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different room or person')\n return\n }\n peer.authorization = authorization\n scheduleExpiry(peer)\n return\n }\n clearTimeout(authTimer)\n const admitted = await admit(socket, authorization)\n // The socket may have closed while the room loaded.\n if (admitted && isClosed()) depart(admitted)\n else peer = admitted\n }\n\n function process(data: Uint8Array) {\n if (data.byteLength > options.maximumMessageBytes) {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const assembled = assembler.push(data)\n if (assembled.type === 'partial') return\n if (assembled.type === 'too-large') {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const frame = assembled.type === 'frame' ? decodeRelayClientFrame(assembled.data) : null\n if (!frame) {\n socket.close(RELAY_CLOSE.protocol, 'Malformed collaboration frame')\n return\n }\n if (frame.type === 'auth') {\n state.authenticating = true\n void authenticate(frame.token)\n .catch((error: unknown) => {\n report('Admitting a collaboration peer failed:', error)\n socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')\n })\n .finally(() => {\n state.authenticating = false\n flush()\n })\n return\n }\n const room = peer && rooms.get(peer.authorization.roomId)\n if (!peer || !room) {\n socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n return\n }\n handleMessage(room, peer, frame.namespace, frame.target, frame.payload)\n }\n\n function flush() {\n while (!state.authenticating && !state.closed && queued.length > 0) {\n const next = queued.shift()\n if (!next) continue\n queuedBytes -= next.byteLength\n process(next)\n }\n }\n\n return {\n receive(data) {\n if (state.closed) return\n queuedBytes += data.byteLength\n // Before admission a peer has sent its ticket and has nothing else to say, so what\n // waits for the room to open is held to one message's worth.\n if (!peer && queuedBytes > options.maximumMessageBytes) {\n queued.length = 0\n queuedBytes = 0\n socket.close(RELAY_CLOSE.messageTooLarge, 'Too much sent before joining the room')\n return\n }\n queued.push(data)\n flush()\n },\n closed() {\n state.closed = true\n queued.length = 0\n queuedBytes = 0\n clearTimeout(authTimer)\n if (peer) depart(peer)\n }\n }\n },\n\n /**\n * Ends a restored document's rooms: everyone in them is told the document was restored, and\n * their edits to the replaced state are dropped rather than saved.\n */\n startOver(documentId: string) {\n // A map's iteration carries on past entries deleted during it.\n for (const room of rooms.values()) {\n if (room.identity.documentId !== documentId) continue\n rooms.delete(room.id)\n if (room.persistTimer) clearTimeout(room.persistTimer)\n for (const peer of room.peers.values()) {\n clearTimeout(peer.expiry)\n peer.socket.close(RELAY_CLOSE.restored, 'The document was restored')\n }\n room.peers.clear()\n room.document.destroy()\n }\n },\n\n /** Tells everyone in a document's rooms that its version history changed. */\n announceVersions(documentId: string) {\n const frame: RelayServerFrame = {\n type: 'message',\n namespace: COLLAB_ACTIONS.versions,\n from: RELAY_SERVER_PEER,\n payload: new Uint8Array()\n }\n sendAll(\n [...rooms.values()]\n .filter((room) => room.identity.documentId === documentId)\n .flatMap((room) => [...room.peers.values()].map((peer) => peer.socket)),\n frame\n )\n },\n\n /** Saves every open room and closes its sockets, as the runtime shuts down. */\n async close() {\n shuttingDown = true\n await Promise.all(\n [...rooms.values()].map(async (room) => {\n for (const peer of room.peers.values()) {\n clearTimeout(peer.expiry)\n peer.socket.close(1001, 'Server shutting down')\n }\n room.peers.clear()\n await leaveRoom(room)\n })\n )\n // Rooms whose last peer left just before, or during, shutdown are still saving.\n await Promise.all(closing.values())\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport type CollaborationRoomIdentity = {\n documentId: string\n roomEpoch: number\n}\n\n/** The relay's saved copy of each room's document, by document and collaboration epoch. */\nexport type CollaborationStateStore = {\n load(room: CollaborationRoomIdentity): Promise<Uint8Array | null>\n store(room: CollaborationRoomIdentity, state: Uint8Array): Promise<void>\n}\n\nexport function createCollaborationStateStore(\n database: Kysely<CloudDatabase>\n): CollaborationStateStore {\n return {\n async load(room) {\n const row = await database\n .selectFrom('documentCollaborationState')\n .select('state')\n .where('documentId', '=', room.documentId)\n .where('roomEpoch', '=', room.roomEpoch)\n .executeTakeFirst()\n return row ? new Uint8Array(row.state) : null\n },\n\n async store(room, state) {\n await database\n .insertInto('documentCollaborationState')\n .values({\n documentId: room.documentId,\n roomEpoch: room.roomEpoch,\n state,\n updatedAt: new Date()\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'roomEpoch']).doUpdateSet({\n state,\n version: (expression) => expression('documentCollaborationState.version', '+', 1),\n updatedAt: new Date()\n })\n )\n .execute()\n }\n }\n}\n","import {\n parseDuplicateDocumentVersion,\n parseSaveDocumentVersion,\n parseUpdateDocumentVersion\n} from '#cloud/contract'\nimport { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents/routes'\nimport { validatedJSON, validatedQuery } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport * as v from 'valibot'\n\nimport type { DocumentVersionService } from './service'\n\nconst pageSchema = v.object({\n before: v.optional(v.pipe(v.string(), v.uuid())),\n limit: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)))\n})\nconst parsePage = (input: unknown) => v.parse(pageSchema, input)\n\nasync function answer(context: Context, run: () => Promise<Response>): Promise<Response> {\n try {\n return await run()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\n/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */\nexport function createDocumentVersionRoutes(service: DocumentVersionService) {\n return new Hono<DocumentRouteEnvironment>()\n .get('/documents/:documentId/versions', validatedQuery(parsePage), (context) =>\n answer(context, async () =>\n context.json(\n await service.list(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('query')\n )\n )\n )\n )\n .post('/documents/:documentId/versions', validatedJSON(parseSaveDocumentVersion), (context) =>\n answer(context, async () =>\n context.json(\n {\n version: await service.save(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/versions/:versionId',\n validatedJSON(parseUpdateDocumentVersion),\n (context) =>\n answer(context, async () =>\n context.json({\n version: await service.update(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('versionId'),\n context.req.valid('json')\n )\n })\n )\n )\n .get('/documents/:documentId/versions/:versionId', (context) =>\n answer(context, async () =>\n context.json(\n await service.download(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('versionId')\n )\n )\n )\n )\n .post('/documents/:documentId/versions/:versionId/restore', (context) =>\n answer(context, async () =>\n context.json(\n await service.restore(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('versionId')\n )\n )\n )\n )\n .post(\n '/documents/:documentId/versions/:versionId/duplicate',\n validatedJSON(parseDuplicateDocumentVersion),\n (context) =>\n answer(context, async () =>\n context.json(\n {\n document: await service.duplicate(\n context.get('actor').userId,\n context.req.param('documentId'),\n context.req.param('versionId'),\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n}\n","import type {\n DocumentVersionDownload,\n DocumentSummary,\n DocumentVersion,\n DocumentVersions,\n DuplicateDocumentVersionInput,\n SaveDocumentVersionInput,\n UpdateDocumentVersionInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { copyRevisionImages, revisionImageDownloads } from '#cloud/server/documents/images'\nimport { findDocument, insertDocument, workspaceRole } from '#cloud/server/documents/repository'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { announceVersions, keepRevision } from './checkpoint'\nimport { historyStart } from './history'\n\nconst DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000\nconst DEFAULT_PAGE_SIZE = 50\nconst MAXIMUM_PAGE_SIZE = 100\nconst WRITABLE_ROLES = new Set(['admin', 'editor'])\n\ntype VersionRow = {\n id: string\n revisionId: string\n kind: 'checkpoint' | 'named'\n name: string | null\n description: string | null\n createdAt: Date\n createdBy: string\n createdByName: string | null\n restoredFromVersionId: string | null\n}\n\nfunction versionOf(row: VersionRow, currentRevisionId: string | null): DocumentVersion {\n return {\n id: row.id,\n revisionId: row.revisionId,\n kind: row.kind,\n name: row.name,\n description: row.description,\n createdAt: row.createdAt.toISOString(),\n createdBy: { id: row.createdBy, name: row.createdByName },\n restoredFromVersionId: row.restoredFromVersionId,\n current: row.revisionId === currentRevisionId\n }\n}\n\n/**\n * A document's version history: its checkpoints and named versions, newest first, and what can be\n * done with one. Anyone who can open the document sees its history; editors name and restore.\n */\nexport function createDocumentVersionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: {\n policy?: CloudPolicy\n deploymentMode?: CloudPolicyContext['deploymentMode']\n /** Called once a restore lands, so the document's live room starts over. */\n onRestored?: (documentId: string) => void\n /** Called once the history changes: a version named, renamed, or turned back into an autosave. */\n onVersionsChanged?: (documentId: string) => void\n } = {}\n) {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n function versions() {\n return database\n .selectFrom('documentVersion')\n .leftJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('documentVersion.createdBy')\n )\n )\n )\n .select([\n 'documentVersion.id',\n 'documentVersion.revisionId',\n 'documentVersion.kind',\n 'documentVersion.name',\n 'documentVersion.description',\n 'documentVersion.createdAt',\n 'documentVersion.createdBy',\n 'user.name as createdByName',\n 'documentVersion.restoredFromVersionId'\n ])\n }\n\n /** The document the person may see the history of, and where that history starts. */\n async function openHistory(userId: string, documentId: string, edit: boolean) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (edit && !canEditDocument(access)) throw new DocumentForbiddenError()\n const document = await getDocumentSummaryRow(database, documentId)\n if (!document) throw new DocumentNotFoundError()\n return {\n document,\n start: await historyStart(options.policy, deploymentMode, document.workspaceId, new Date())\n }\n }\n\n async function findVersion(documentId: string, versionId: string, start: Date | null) {\n let query = versions()\n .where('documentVersion.documentId', '=', documentId)\n .where('documentVersion.id', '=', versionId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n const row = await query.executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n /** The stored file of a revision; read under the document's lock before reusing it. */\n async function storedRevision(\n source: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n revisionId: string\n ) {\n const stored = await source\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.storageObjectId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', revisionId)\n .executeTakeFirst()\n if (!stored) throw new DocumentNotFoundError()\n return stored\n }\n\n return {\n async list(\n userId: string,\n documentId: string,\n page: { before?: string; limit?: number } = {}\n ): Promise<DocumentVersions> {\n const { document, start } = await openHistory(userId, documentId, false)\n const limit = Math.min(Math.max(page.limit ?? DEFAULT_PAGE_SIZE, 1), MAXIMUM_PAGE_SIZE)\n let query = versions().where('documentVersion.documentId', '=', documentId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n if (page.before) {\n const cursor = await findVersion(documentId, page.before, start)\n query = query.where((expression) =>\n expression.or([\n expression('documentVersion.createdAt', '<', cursor.createdAt),\n expression.and([\n expression('documentVersion.createdAt', '=', cursor.createdAt),\n expression('documentVersion.id', '<', cursor.id)\n ])\n ])\n )\n }\n const rows = await query\n .orderBy('documentVersion.createdAt', 'desc')\n .orderBy('documentVersion.id', 'desc')\n .limit(limit + 1)\n .execute()\n const shown = rows.slice(0, limit)\n return {\n versions: shown.map((row) => versionOf(row, document.currentRevisionId)),\n nextCursor: rows.length > limit ? (shown.at(-1)?.id ?? null) : null\n }\n },\n\n /** Names the document as it is now, as Save to version history does. */\n async save(\n userId: string,\n documentId: string,\n input: SaveDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document } = await openHistory(userId, documentId, true)\n const revisionId = document.currentRevisionId\n if (!revisionId) throw new DocumentNotFoundError()\n const description = input.description || null\n await database\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId,\n revisionId,\n kind: 'named',\n name: input.name,\n description,\n createdBy: userId,\n restoredFromVersionId: null\n })\n .onConflict((conflict) =>\n conflict\n .column('revisionId')\n .doUpdateSet({ kind: 'named', name: input.name, description })\n )\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n const row = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return versionOf(row, revisionId)\n },\n\n /** Names a version, renames it, or with a null name deletes its info so it is a checkpoint. */\n async update(\n userId: string,\n documentId: string,\n versionId: string,\n input: UpdateDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document, start } = await openHistory(userId, documentId, true)\n await findVersion(documentId, versionId, start)\n await database\n .updateTable('documentVersion')\n .set(\n input.name\n ? { kind: 'named', name: input.name, description: input.description || null }\n : { kind: 'checkpoint', name: null, description: null }\n )\n .where('id', '=', versionId)\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n return versionOf(await findVersion(documentId, versionId, start), document.currentRevisionId)\n },\n\n async download(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<DocumentVersionDownload> {\n const { document, start } = await openHistory(userId, documentId, false)\n const version = await findVersion(documentId, versionId, start)\n const stored = await storedRevision(database, version.revisionId)\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document: {\n document: documentSummary(document),\n revisionId: version.revisionId,\n byteSize: Number(stored.byteSize),\n checksum: stored.checksum,\n contentType: stored.contentType,\n download: await objects.createDownload({ key: stored.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, version.revisionId, expiresAt)\n },\n version: versionOf(version, document.currentRevisionId)\n }\n },\n\n /**\n * Makes a version the document's current state without losing anything: the state it replaces\n * is kept as a checkpoint, the restored state becomes a new revision of the same stored file,\n * and the document's live room starts over so everyone has the restored version.\n */\n async restore(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<{ document: DocumentSummary; version: DocumentVersion }> {\n const { start } = await openHistory(userId, documentId, true)\n const version = await findVersion(documentId, versionId, start)\n const revisionId = crypto.randomUUID()\n const now = new Date()\n await database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select(['currentRevisionId', 'deletedAt'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!locked || locked.deletedAt) throw new DocumentNotFoundError()\n // Compaction locks the document too, so the version's file cannot go while it is reused.\n const stored = await storedRevision(transaction, version.revisionId)\n if (locked.currentRevisionId) {\n const current = await transaction\n .selectFrom('documentRevision')\n .select('createdBy')\n .where('id', '=', locked.currentRevisionId)\n .executeTakeFirstOrThrow()\n await keepRevision(transaction, {\n documentId,\n revisionId: locked.currentRevisionId,\n createdBy: current.createdBy,\n createdAt: now\n })\n }\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId,\n parentRevisionId: locked.currentRevisionId,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1),\n collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1)\n })\n .where('id', '=', documentId)\n .execute()\n // A moment after the state it replaces, so the history lists it first.\n await keepRevision(transaction, {\n documentId,\n revisionId,\n createdBy: userId,\n createdAt: new Date(now.getTime() + 1),\n restoredFromVersionId: versionId\n })\n })\n // The restore stands whatever the hook does; a stale ticket is still turned away by its epoch.\n try {\n options.onRestored?.(documentId)\n } catch (error) {\n console.error('[Cloud] Ending the rooms of a restored document failed:', error)\n }\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n const restored = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return { document, version: versionOf(restored, revisionId) }\n },\n\n /** Makes a new document in the same workspace from a version, sharing its stored file. */\n async duplicate(\n userId: string,\n documentId: string,\n versionId: string,\n input: DuplicateDocumentVersionInput\n ): Promise<DocumentSummary> {\n const { document, start } = await openHistory(userId, documentId, false)\n const role = await workspaceRole(database, userId, document.workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()\n const version = await findVersion(documentId, versionId, start)\n const copyId = crypto.randomUUID()\n const revisionId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n // Deleted-document cleanup removes files its document alone uses; holding the source\n // until the copy refers to the file means cleanup either finishes first or sees the copy.\n const source = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'cleanupClaimId'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!source || source.deletedAt || source.cleanupClaimId) throw new DocumentNotFoundError()\n const stored = await storedRevision(transaction, version.revisionId)\n await insertDocument(transaction, {\n id: copyId,\n workspaceId: document.workspaceId,\n name: input.name,\n kind: document.kind,\n createdBy: userId\n })\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: copyId,\n parentRevisionId: null,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: revisionId, version: 1 })\n .where('id', '=', copyId)\n .execute()\n await keepRevision(transaction, {\n documentId: copyId,\n revisionId,\n createdBy: userId,\n createdAt: new Date()\n })\n })\n const copy = await findDocument(database, userId, copyId)\n if (!copy) throw new DocumentNotFoundError()\n return copy\n }\n }\n}\n\nexport type DocumentVersionService = ReturnType<typeof createDocumentVersionService>\n","import type { CreateWorkspaceInput, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n findWorkspace,\n insertWorkspace,\n insertWorkspaceMember,\n listWorkspaces\n} from '#cloud/server/workspaces/repository'\nimport type { Kysely } from 'kysely'\n\nexport class WorkspaceSlugConflictError extends Error {\n constructor(readonly slug: string) {\n super(`Workspace slug is already in use: ${slug}`)\n this.name = 'WorkspaceSlugConflictError'\n }\n}\n\nfunction fallbackSlug(name: string): string {\n const normalized = name\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .slice(0, 48)\n return normalized.length >= 3 ? normalized : 'workspace'\n}\n\nfunction generatedSlug(name: string): string {\n return `${fallbackSlug(name)}-${crypto.randomUUID().slice(0, 8)}`\n}\n\nfunction personalWorkspaceName(name: string): string {\n const first = name.trim().split(/\\s+/)[0]\n return first ? `${first}’s workspace` : 'Personal workspace'\n}\n\nexport function createWorkspaceService(database: Kysely<CloudDatabase>) {\n return {\n list(userId: string): Promise<WorkspaceSummary[]> {\n return listWorkspaces(database, userId)\n },\n\n get(userId: string, workspaceId: string): Promise<WorkspaceSummary | undefined> {\n return findWorkspace(database, userId, workspaceId)\n },\n\n async create(userId: string, input: CreateWorkspaceInput): Promise<WorkspaceSummary> {\n const workspaceId = crypto.randomUUID()\n const slug = input.slug ?? generatedSlug(input.name)\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, userId, {\n ...input,\n id: workspaceId,\n slug\n })\n if (!inserted) throw new WorkspaceSlugConflictError(slug)\n await insertWorkspaceMember(transaction, workspaceId, userId, 'admin')\n })\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new Error('Created workspace could not be read')\n return workspace\n },\n\n /**\n * Gives an active account with no workspace one of its own, so it has somewhere to save. The\n * slug is fixed per person, so concurrent calls make one workspace and later calls none.\n */\n async ensurePersonal(user: { userId: string; name: string }): Promise<void> {\n if ((await listWorkspaces(database, user.userId)).length > 0) return\n const workspaceId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, user.userId, {\n id: workspaceId,\n name: personalWorkspaceName(user.name),\n slug: `personal-${user.userId}`\n })\n if (inserted) await insertWorkspaceMember(transaction, workspaceId, user.userId, 'admin')\n })\n }\n }\n}\n\nexport type WorkspaceService = ReturnType<typeof createWorkspaceService>\n","import {\n parseCreateWorkspace,\n parseCreateWorkspaceInvitation,\n parseUpdateWorkspace,\n parseUpdateWorkspaceMember\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON } from '#cloud/server/validation'\nimport {\n WorkspaceAlreadyMemberError,\n WorkspaceForbiddenError,\n WorkspaceLastAdminError,\n WorkspaceNotEmptyError,\n WorkspaceNotFoundError,\n type WorkspaceMemberService\n} from '#cloud/server/workspaces/members'\nimport type { WorkspaceService } from '#cloud/server/workspaces/service'\nimport { WorkspaceSlugConflictError } from '#cloud/server/workspaces/service'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type WorkspaceRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** Runs a membership action, answering its domain errors with their HTTP codes. */\nasync function memberRoute<T>(context: Context, action: () => Promise<T>): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n if (error instanceof WorkspaceNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof WorkspaceForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof WorkspaceLastAdminError) {\n return context.json({ error: { code: 'last_admin' as const } }, 409)\n }\n if (error instanceof WorkspaceNotEmptyError) {\n const code = error.reason === 'documents' ? 'not_empty' : 'cleanup_pending'\n return context.json({ error: { code } }, 409)\n }\n if (error instanceof WorkspaceAlreadyMemberError) {\n return context.json({ error: { code: 'already_member' as const } }, 409)\n }\n throw error\n }\n}\n\nexport function createWorkspaceRoutes(\n service: WorkspaceService,\n members: WorkspaceMemberService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<WorkspaceRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.workspaceCreation,\n (context) => context.req.method !== 'POST'\n )\n )\n // Resending mails the invitation again, so it counts against the same budget as sending.\n router.use(\n '/:workspaceId/invitations/:invitationId/resend',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n () => false,\n (context) => context.req.param('workspaceId') ?? 'unknown'\n )\n )\n router.use(\n '/:workspaceId/invitations',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n (context) => context.req.method !== 'POST',\n (context) => context.req.param('workspaceId') ?? 'unknown'\n )\n )\n }\n return router\n .get('/', async (context) => {\n const workspaces = await service.list(context.get('actor').userId)\n return context.json({ workspaces })\n })\n .post('/', validatedJSON(parseCreateWorkspace), async (context) => {\n try {\n const workspace = await service.create(\n context.get('actor').userId,\n context.req.valid('json')\n )\n return context.json({ workspace }, 201)\n } catch (error) {\n if (error instanceof WorkspaceSlugConflictError) {\n return context.json({ error: { code: 'slug_conflict' as const } }, 409)\n }\n throw error\n }\n })\n .get('/:workspaceId', async (context) => {\n const workspace = await service.get(\n context.get('actor').userId,\n context.req.param('workspaceId')\n )\n if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ workspace })\n })\n .patch('/:workspaceId', validatedJSON(parseUpdateWorkspace), (context) =>\n memberRoute(context, async () =>\n context.json({\n workspace: await members.rename(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.valid('json').name\n )\n })\n )\n )\n .delete('/:workspaceId', (context) =>\n memberRoute(context, async () => {\n await members.delete(context.get('actor').userId, context.req.param('workspaceId'))\n return context.body(null, 204)\n })\n )\n .get('/:workspaceId/members', (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.list(context.get('actor').userId, context.req.param('workspaceId'))\n )\n )\n )\n .post('/:workspaceId/invitations', validatedJSON(parseCreateWorkspaceInvitation), (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.invite(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post('/:workspaceId/invitations/:invitationId/resend', (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.resendInvitation(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.param('invitationId')\n )\n )\n )\n )\n .delete('/:workspaceId/invitations/:invitationId', (context) =>\n memberRoute(context, async () => {\n await members.revokeInvitation(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.param('invitationId')\n )\n return context.body(null, 204)\n })\n )\n .patch('/:workspaceId/members/:userId', validatedJSON(parseUpdateWorkspaceMember), (context) =>\n memberRoute(context, async () => {\n await members.updateRole(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.param('userId'),\n context.req.valid('json').role\n )\n return context.body(null, 204)\n })\n )\n .delete('/:workspaceId/members/:userId', (context) =>\n memberRoute(context, async () => {\n await members.remove(\n context.get('actor').userId,\n context.req.param('workspaceId'),\n context.req.param('userId')\n )\n return context.body(null, 204)\n })\n )\n}\n","import { createAIRoutes, type AITokenService } from '#cloud/server/ai'\nimport type { CloudAPIEnvironment } from '#cloud/server/api/types'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration'\nimport {\n createCollaborationRoutes,\n createPublicCollaborationRoutes\n} from '#cloud/server/collaboration'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentService } from '#cloud/server/documents'\nimport { createDocumentRoutes } from '#cloud/server/documents'\nimport {\n createDocumentVersionRoutes,\n type DocumentVersionService\n} from '#cloud/server/documents/versions'\nimport type { EntitlementService } from '#cloud/server/policy'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport {\n createDocumentSharingRoutes,\n createPublicDocumentRoutes,\n createPublicSharingRoutes\n} from '#cloud/server/sharing'\nimport type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'\nimport { createWorkspaceRoutes } from '#cloud/server/workspaces'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CloudAPIServices = {\n database?: Kysely<CloudDatabase>\n rateLimitSecret?: string\n collaboration: CollaborationTicketService\n documents: DocumentService\n versions: DocumentVersionService\n sharing: DocumentSharingService\n resolveSession?: CloudSessionResolver\n entitlements?: EntitlementService\n /** Signs AI service tokens; without it the deployment has no AI service. */\n aiTokens?: AITokenService\n workspaces: WorkspaceService\n workspaceMembers: WorkspaceMemberService\n}\n\nexport function createPublicCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/', createPublicSharingRoutes(services.sharing, services.resolveSession))\n .route(\n '/',\n createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)\n )\n .route('/', createPublicCollaborationRoutes(services.collaboration, services.resolveSession))\n}\n\nexport function createCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/public', createPublicCloudAPIRouter(services))\n .get('/workspaces/:workspaceId/entitlements', async (context) => {\n if (!services.entitlements)\n return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({\n entitlements: await services.entitlements.workspace(\n context.get('actor').userId,\n context.req.param('workspaceId')\n )\n })\n })\n .get('/session', (context) => context.json({ user: context.get('actor') }))\n .route(\n '/',\n createAIRoutes(\n services.aiTokens,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createCollaborationRoutes(\n services.collaboration,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createDocumentRoutes(\n services.documents,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route('/', createDocumentVersionRoutes(services.versions))\n .route(\n '/',\n createDocumentSharingRoutes(\n services.sharing,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/workspaces',\n createWorkspaceRoutes(\n services.workspaces,\n services.workspaceMembers,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n}\n\nexport type CloudAPI = ReturnType<typeof createCloudAPIRouter>\nexport type PublicCloudAPI = ReturnType<typeof createPublicCloudAPIRouter>\n","import type { AccountSecurityErrorCode } from '#cloud/contract'\nimport type { CloudIdentityResolver, CloudSessionResolver } from '#cloud/server/auth'\nimport { APIError } from 'better-auth'\nimport type { Context } from 'hono'\n\nconst ACCOUNT_SECURITY_ERROR_CODES: Record<string, AccountSecurityErrorCode> = {\n INVALID_PASSWORD: 'current_password_invalid',\n PASSWORD_TOO_SHORT: 'password_too_short',\n PASSWORD_TOO_LONG: 'password_too_long',\n FAILED_TO_UNLINK_LAST_ACCOUNT: 'last_authentication_method',\n SESSION_NOT_FRESH: 'session_not_fresh',\n CHANGE_EMAIL_DISABLED: 'email_change_unavailable',\n CURRENT_SESSION: 'current_session',\n EMAIL_UNCHANGED: 'email_unchanged'\n}\n\nasync function accountAction<Value>(operation: () => Promise<Value>, context: Context) {\n try {\n return await operation()\n } catch (error) {\n if (!(error instanceof APIError)) throw error\n return context.json(\n {\n error: {\n code:\n ACCOUNT_SECURITY_ERROR_CODES[error.body?.code ?? ''] ?? 'authentication_method_failed'\n }\n },\n error.statusCode as 400 | 401 | 403 | 404 | 409 | 422 | 429 | 500\n )\n }\n}\n\nfunction completedMFAResponse(result: Response | undefined, context: Context): Response {\n if (!(result instanceof Response)) return context.json({ ok: true as const })\n if (!result.ok) return result\n const headers = new Headers(result.headers)\n headers.set('Content-Type', 'application/json')\n return new Response(JSON.stringify({ ok: true }), { status: 200, headers })\n}\n\nexport function createAccountActions(resolveSession: CloudSessionResolver) {\n return {\n accountAction,\n activeAccountAction: async <Value>(\n context: Context,\n operation: () => Promise<Value>\n ): Promise<Value | Response> => {\n if (!(await resolveSession(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return accountAction(operation, context)\n },\n verifiedMFAAction: async (\n context: Context,\n identityResolver: CloudIdentityResolver,\n verify: () => Promise<Response | undefined>\n ): Promise<Response> => {\n if (!(await identityResolver(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n const result = await accountAction(verify, context)\n return completedMFAResponse(result instanceof Response ? result : undefined, context)\n }\n }\n}\n","import type { EnrollmentService } from '#cloud/admin'\nimport {\n parseCloudPasswordChange,\n parseCloudMFAEnable,\n parseCloudMFAVerify,\n parseCloudPasskeyDelete,\n parseCloudSocialLink,\n parseCloudUnlinkAuthenticationMethod,\n parseCloudEmailChange,\n parseCloudProfileUpdate,\n parseCloudPictureUpload,\n CLOUD_PICTURE_MAX_BYTES,\n parseCloudSessionRevoke\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport {\n createAccountAuthenticationService,\n type CloudAuthAdapter,\n type CloudIdentityResolver,\n type CloudSessionResolver\n} from '#cloud/server/auth'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport { PictureInvalidError, type UserPictureService } from '#cloud/server/pictures'\nimport { validatedJSON } from '#cloud/server/validation'\nimport type { WorkspaceService } from '#cloud/server/workspaces'\nimport { Hono, type MiddlewareHandler } from 'hono'\nimport { bodyLimit } from 'hono/body-limit'\nimport { toUint8Array } from 'js-base64'\n\nimport { createAccountActions } from './actions'\n\n/** Room for a Base64 picture and the JSON around it. */\nconst PICTURE_BODY_BYTES = Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4 + 1024\n\nexport type AccountRouteDependencies = {\n auth: CloudAuthAdapter\n config: CloudServerConfig\n pictures: UserPictureService\n enrollment: EnrollmentService\n workspaces: WorkspaceService\n resolveIdentity: CloudIdentityResolver\n resolveSession: CloudSessionResolver\n requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>\n authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>\n}\n\nexport function createAccountRoutes(services: AccountRouteDependencies) {\n const {\n enrollment,\n workspaces,\n resolveIdentity,\n resolveSession,\n requireActiveSession,\n authenticatedMutationLimiter\n } = services\n const accountAuthentication = createAccountAuthenticationService(services.auth, services.config)\n const { accountAction, activeAccountAction, verifiedMFAAction } =\n createAccountActions(resolveSession)\n return new Hono<CloudAPIEnvironment>()\n .get('/api/account/status', async (context) => {\n const identity = await resolveIdentity(context.req.raw)\n if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n let enrollmentStatus = await enrollment.statusForEmail(identity.email)\n if (services.config.enrollmentMode === 'approval' && !enrollmentStatus) {\n await enrollment.request({ email: identity.email, name: identity.name })\n enrollmentStatus = 'pending'\n }\n const state =\n services.config.enrollmentMode !== 'approval' || enrollmentStatus === 'approved'\n ? ('active' as const)\n : (enrollmentStatus ?? 'pending')\n if (state === 'active') await workspaces.ensurePersonal(identity)\n return context.json({ user: identity, state })\n })\n .get('/api/account/mfa', async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const mfa = await services.auth.mfaStatus(context.req.raw.headers)\n return mfa\n ? context.json({ mfa })\n : context.json({ error: { code: 'unauthorized' as const } }, 401)\n })\n .post('/api/account/mfa/totp/enable', validatedJSON(parseCloudMFAEnable), async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.enableTOTP(context.req.raw.headers, context.req.valid('json').password)\n )\n return result instanceof Response ? result : context.json(result)\n })\n .post('/api/account/mfa/totp/verify', validatedJSON(parseCloudMFAVerify), (context) =>\n verifiedMFAAction(context, resolveSession, () =>\n services.auth.verifyTOTP(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post('/api/account/mfa/recovery/verify', validatedJSON(parseCloudMFAVerify), (context) =>\n verifiedMFAAction(context, resolveIdentity, () =>\n services.auth.verifyRecoveryCode(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post(\n '/api/account/mfa/recovery/regenerate',\n validatedJSON(parseCloudMFAEnable),\n async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.generateRecoveryCodes(\n context.req.raw.headers,\n context.req.valid('json').password\n )\n )\n return result instanceof Response ? result : context.json({ backupCodes: result })\n }\n )\n .post('/api/account/mfa/totp/disable', validatedJSON(parseCloudMFAEnable), async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n if (passkeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () =>\n services.auth.disableTOTP(context.req.raw.headers, context.req.valid('json').password),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/mfa/passkeys', async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ passkeys: await services.auth.listPasskeys(context.req.raw.headers) })\n })\n .post(\n '/api/account/mfa/passkeys/delete',\n validatedJSON(parseCloudPasskeyDelete),\n async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const { id } = context.req.valid('json')\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n // An administrator keeps at least one second factor: TOTP or another passkey.\n const status = await services.auth.mfaStatus(context.req.raw.headers)\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n const otherPasskeys = passkeys.filter((passkey) => passkey.id !== id)\n if (!status?.totpEnabled && otherPasskeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () => services.auth.deletePasskey(context.req.raw.headers, id),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/authentication/*', requireActiveSession)\n .use('/api/account/authentication/*', authenticatedMutationLimiter)\n .post(\n '/api/account/authentication/change-password',\n validatedJSON(parseCloudPasswordChange),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.changePassword(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post(\n '/api/account/authentication/link-social',\n validatedJSON(parseCloudSocialLink),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.startSocialLink(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n return result instanceof Response ? result : context.json({ url: result })\n }\n )\n .post(\n '/api/account/authentication/unlink',\n validatedJSON(parseCloudUnlinkAuthenticationMethod),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.unlink(\n context.req.raw.headers,\n context.req.valid('json').methodId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/profile', requireActiveSession)\n .use('/api/account/profile/*', requireActiveSession)\n .use('/api/account/sessions', requireActiveSession)\n .use('/api/account/sessions/*', requireActiveSession)\n .use('/api/account/sign-ins', requireActiveSession)\n .use('/api/account/profile', authenticatedMutationLimiter)\n .use('/api/account/profile/*', authenticatedMutationLimiter)\n .use('/api/account/sessions/*', authenticatedMutationLimiter)\n .get('/api/account/profile', async (context) => {\n const profile = await services.auth.profile(context.req.raw.headers)\n if (!profile) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({\n profile: {\n ...profile,\n createdAt: profile.createdAt.toISOString(),\n emailChangeAvailable: services.auth.emailChangeAvailable\n }\n })\n })\n .post('/api/account/profile', validatedJSON(parseCloudProfileUpdate), async (context) => {\n const result = await accountAction(\n () => services.auth.updateProfile(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .put(\n '/api/account/profile/picture',\n bodyLimit({\n maxSize: PICTURE_BODY_BYTES,\n onError: (context) => context.json({ error: { code: 'picture_invalid' as const } }, 413)\n }),\n validatedJSON(parseCloudPictureUpload),\n async (context) => {\n const bytes = toUint8Array(context.req.valid('json').data)\n try {\n const image = await services.pictures.upload(context.get('actor').userId, bytes)\n return context.json({ image })\n } catch (error) {\n if (!(error instanceof PictureInvalidError)) throw error\n return context.json({ error: { code: 'picture_invalid' as const } }, 400)\n }\n }\n )\n .delete('/api/account/profile/picture', async (context) => {\n await services.pictures.remove(context.get('actor').userId)\n return context.json({ ok: true as const })\n })\n .post('/api/account/profile/email', validatedJSON(parseCloudEmailChange), async (context) => {\n const result = await accountAction(\n () => accountAuthentication.changeEmail(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/sessions', async (context) => {\n const sessions = await services.auth.sessions(context.req.raw.headers)\n if (!sessions) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ sessions })\n })\n .post(\n '/api/account/sessions/revoke',\n validatedJSON(parseCloudSessionRevoke),\n async (context) => {\n const result = await accountAction(\n () =>\n services.auth.revokeSession(\n context.req.raw.headers,\n context.req.valid('json').sessionId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post('/api/account/sessions/revoke-others', async (context) => {\n const result = await accountAction(\n () => services.auth.revokeOtherSessions(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/sign-ins', async (context) => {\n const signIns = await services.auth.signIns(context.req.raw.headers)\n if (!signIns) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ signIns })\n })\n .get('/api/account/authentication', async (context) => {\n const result = await accountAction(\n () => accountAuthentication.methods(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json(result)\n })\n}\n\n/** The account routes' types, for the portal's typed client. */\nexport type CloudAccountRoutes = ReturnType<typeof createAccountRoutes>\n","import { staticEntitlementsSchema } from '#cloud/server/policy/schema'\nimport * as v from 'valibot'\n\nexport const setWorkspaceEntitlementsSchema = v.object({\n values: staticEntitlementsSchema,\n /** Who decided these values, such as `billing`; stored as the row's source. */\n source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),\n /** Increases with every decision the writer makes, such as a billing event's timestamp. */\n externalVersion: v.pipe(v.number(), v.safeInteger(), v.minValue(0))\n})\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { createWorkspaceEntitlementRepository } from '#cloud/server/policy'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport { setWorkspaceEntitlementsSchema } from './schema'\n\nexport type SetWorkspaceEntitlementsInput = v.InferInput<typeof setWorkspaceEntitlementsSchema>\n\nexport function parseSetWorkspaceEntitlements(input: unknown) {\n return v.parse(setWorkspaceEntitlementsSchema, input)\n}\n\n/**\n * What services beside Cloud, such as billing, may change. Runtimes expose it to them through\n * their own transport: an authenticated HTTP route on Node, a service binding on Workers.\n */\nexport function createInternalService(database: Kysely<CloudDatabase>) {\n const entitlements = createWorkspaceEntitlementRepository(database)\n return {\n /** `found` is false for an unknown workspace; `applied` is false for an outdated version. */\n async setWorkspaceEntitlements(\n workspaceId: string,\n input: SetWorkspaceEntitlementsInput\n ): Promise<{ found: boolean; applied: boolean }> {\n const { values, source, externalVersion } = parseSetWorkspaceEntitlements(input)\n const workspace = await database\n .selectFrom('workspace')\n .select('id')\n .where('id', '=', workspaceId)\n .executeTakeFirst()\n if (!workspace) return { found: false, applied: false }\n const { applied } = await entitlements.setVersioned(\n workspaceId,\n values,\n source,\n externalVersion\n )\n return { found: true, applied }\n }\n }\n}\n\nexport type InternalService = ReturnType<typeof createInternalService>\n","import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport { bearerAuth } from 'hono/bearer-auth'\nimport * as v from 'valibot'\n\nimport { parseSetWorkspaceEntitlements, type InternalService } from './service'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n\n/** The internal API on HTTP, for runtimes without a private transport to their services. */\nexport function createInternalRoutes(service: InternalService, serviceToken: string) {\n const digest = hashCapability(serviceToken)\n const unauthorized = { error: { code: 'unauthorized' as const } }\n return new Hono()\n .use(\n '*',\n bearerAuth({\n verifyToken: (token) => capabilityHashMatches(digest, token),\n noAuthenticationHeader: { message: unauthorized },\n invalidAuthenticationHeader: { message: unauthorized },\n invalidToken: { message: unauthorized }\n })\n )\n .put(\n '/workspaces/:workspaceId/entitlements',\n validatedJSON(parseSetWorkspaceEntitlements),\n async (context) => {\n const workspaceId = context.req.param('workspaceId')\n if (!v.is(uuidSchema, workspaceId)) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n const result = await service.setWorkspaceEntitlements(\n workspaceId,\n context.req.valid('json')\n )\n if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ applied: result.applied })\n }\n )\n}\n","import {\n createAdminAuditService,\n createAdminEmailService,\n createAdminOperationsService,\n createAdminUserService,\n createCloudAdminRoutes,\n createEnrollmentService,\n type EnrollmentService\n} from '#cloud/admin'\nimport {\n CLOUD_AI_JWKS_PATH,\n CLOUD_DISCOVERY_PATH,\n CLOUD_PROTOCOL_VERSION,\n type CloudDiscovery\n} from '#cloud/contract'\nimport { createAccountRoutes } from '#cloud/server/account/routes'\nimport { createAITokenService, type AISigningKey } from '#cloud/server/ai'\nimport {\n createCloudAPIRouter,\n createPublicCloudAPIRouter,\n type CloudAPIEnvironment\n} from '#cloud/server/api'\nimport {\n AUTH_BASE_PATH,\n createAuthenticationEmailService,\n createCloudIdentityResolver,\n createCloudSessionResolver,\n type CloudAuthAdapter,\n type CloudIdentityResolver,\n type CloudSessionResolver\n} from '#cloud/server/auth'\nimport { createCollaborationTicketService } from '#cloud/server/collaboration'\nimport {\n CloudConfigError,\n cloudDiscoveryFromConfig,\n type CloudServerConfig\n} from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createDocumentService } from '#cloud/server/documents'\nimport { createDocumentVersionService } from '#cloud/server/documents/versions'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { createInternalRoutes, createInternalService } from '#cloud/server/internal'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createPictureRoutes, createUserPictures } from '#cloud/server/pictures'\nimport {\n createConfiguredCloudPolicy,\n createDefaultCloudPolicy,\n createEntitlementService,\n EntitlementOpenFeatureProvider,\n type CloudPolicy,\n type EntitlementSource\n} from '#cloud/server/policy'\nimport {\n CLOUD_RATE_LIMITS,\n createActorRateLimiter,\n createTrustedIPRateLimiter,\n routeHasOwnBudget\n} from '#cloud/server/rate-limit'\nimport { createDocumentSharingService } from '#cloud/server/sharing'\nimport { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'\nimport { Hono, type Context } from 'hono'\nimport { cors } from 'hono/cors'\nimport type { Kysely } from 'kysely'\n\nexport type CloudServices = {\n config: CloudServerConfig\n database: Kysely<CloudDatabase>\n auth: CloudAuthAdapter\n objects: ObjectStore\n resolveIdentity?: CloudIdentityResolver\n resolveSession?: CloudSessionResolver\n invitationDelivery?: InvitationDelivery\n invitationOutbox?: InvitationOutbox\n transactionalEmail?: TransactionalEmailService\n enrollment?: EnrollmentService\n entitlementSource?: EntitlementSource\n policy?: CloudPolicy\n /** The imported `aiSigningKey`, required when the config names one. See `loadAISigningKey`. */\n aiSigningKey?: AISigningKey\n /**\n * Where clients reach this runtime's collaboration relay. Without one, Cloud rooms fall back to\n * peer-to-peer and writes are not enforced by the server.\n */\n relayURL?: string\n /** Ends a restored document's live rooms, on the relay this runtime runs, if any. */\n onDocumentRestored?: (documentId: string) => void\n /** Tells a document's live rooms its version history changed, on the relay this runtime runs. */\n onDocumentVersionsChanged?: (documentId: string) => void\n}\n\ntype CloudEnvironment = CloudAPIEnvironment\n\nfunction discoveryFromServices(services: CloudServices): CloudDiscovery {\n return cloudDiscoveryFromConfig(services.config)\n}\n\nexport function shouldPreventIndexing(path: string, policy: 'allow' | 'deny'): boolean {\n return (\n policy === 'deny' ||\n path.startsWith('/api/') ||\n path.startsWith('/admin') ||\n path.startsWith('/auth') ||\n path.startsWith('/account') ||\n path === '/app' ||\n path === '/sign-in' ||\n path === '/sign-up' ||\n path === '/join' ||\n path === CLOUD_DISCOVERY_PATH\n )\n}\n\nexport function withIndexingPolicy(\n response: Response,\n path: string,\n policy: 'allow' | 'deny'\n): Response {\n if (!shouldPreventIndexing(path, policy)) return response\n const headers = new Headers(response.headers)\n headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n}\n\nexport function createCloudApp(services: CloudServices) {\n const discovery = discoveryFromServices(services)\n const resolveIdentity = services.resolveIdentity ?? createCloudIdentityResolver(services.auth)\n const resolveSession = services.resolveSession ?? createCloudSessionResolver(services.auth)\n const allowedOrigins = new Set(\n [services.config.publicURL, ...services.config.trustedOrigins].map(\n (origin) => new URL(origin).origin\n )\n )\n const cloudCORS = cors({\n origin: (origin) => (allowedOrigins.has(origin) ? origin : null),\n allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],\n allowHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 600\n })\n const workspaces = createWorkspaceService(services.database)\n const pictures = createUserPictures(services.database, { publicURL: services.config.publicURL })\n const workspaceMembers = createWorkspaceMemberService(services.database, {\n email: services.transactionalEmail,\n publicURL: services.config.publicURL\n })\n const enrollment =\n services.enrollment ??\n createEnrollmentService(services.database, {\n publicURL: services.config.publicURL,\n adminRecipients: services.config.enrollmentAdminNotificationEmails,\n email: services.transactionalEmail\n })\n const admin = createCloudAdminRoutes(\n {\n email: createAdminEmailService(services.database, services.transactionalEmail, {\n publicURL: services.config.publicURL\n }),\n enrollment,\n users: createAdminUserService(services.database, services.auth, {\n requireMFA: services.config.deploymentAdminMFARequired,\n pictures,\n notify: services.transactionalEmail\n ? createAuthenticationEmailService(services.transactionalEmail, services.config.publicURL)\n : undefined\n }),\n audit: createAdminAuditService(services.database),\n operations: createAdminOperationsService(services.database, services.config)\n },\n allowedOrigins,\n {\n database: services.database,\n secret: services.config.authSecret,\n auth: services.auth,\n requireMFA: services.config.deploymentAdminMFARequired\n }\n )\n const policy =\n services.policy ??\n (services.entitlementSource\n ? createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(services.entitlementSource))\n : createConfiguredCloudPolicy(services.config, services.database))\n const documents = createDocumentService(services.database, services.objects, {\n policy,\n technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes,\n onVersionsChanged: services.onDocumentVersionsChanged\n })\n const versions = createDocumentVersionService(services.database, services.objects, {\n policy,\n deploymentMode: services.config.deployment,\n onRestored: services.onDocumentRestored,\n onVersionsChanged: services.onDocumentVersionsChanged\n })\n const entitlements = createEntitlementService(\n services.database,\n policy,\n services.config.technicalLimits.maximumUploadBytes,\n services.config.technicalLimits.maximumConnectionsPerRoom\n )\n const sharing = createDocumentSharingService(services.database, {\n delivery: services.invitationDelivery,\n outbox: services.invitationOutbox,\n continuationSecret: services.config.authSecret,\n publicURL: services.config.publicURL,\n policy,\n deploymentMode: services.config.deployment,\n workspaceInvitations: workspaceMembers\n })\n const collaboration = createCollaborationTicketService({\n database: services.database,\n sharing,\n authSecret: services.config.authSecret,\n relayURL: services.relayURL,\n policy,\n deploymentMode: services.config.deployment\n })\n if (services.config.aiSigningKey && !services.aiSigningKey) {\n throw new CloudConfigError('The AI service needs the signing key imported by loadAISigningKey')\n }\n const aiTokens = services.aiSigningKey\n ? createAITokenService({\n database: services.database,\n policy,\n deploymentMode: services.config.deployment,\n issuer: new URL(services.config.publicURL).origin,\n signingKey: services.aiSigningKey,\n lifetimeSeconds: services.config.aiTokenLifetimeSeconds\n })\n : undefined\n\n const requireActiveSession = async (context: Context, next: () => Promise<void>) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n }\n const publicRateLimiter = createTrustedIPRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.publicCapability,\n { trustedHeaders: services.config.authTrustedIPHeaders },\n (context) => context.json({ error: { code: 'not_found' as const } }, 404),\n {\n resource: (context) => context.req.path,\n // Guests refresh collaboration tickets on their own budget, `publicCollaborationLimiter`.\n skip: routeHasOwnBudget\n }\n )\n const publicCollaborationLimiter = createTrustedIPRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.collaborationTicket,\n { trustedHeaders: services.config.authTrustedIPHeaders },\n (context) => context.json({ error: { code: 'not_found' as const } }, 404),\n { resource: (context) => context.req.path, route: true }\n )\n const authenticatedMutationLimiter = createActorRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.authenticatedMutation,\n // Reads are free, and a route with a budget of its own, such as creating documents, counts\n // against that instead.\n (context) => context.req.method === 'GET' || routeHasOwnBudget(context)\n )\n\n const accountRoutes = createAccountRoutes({\n auth: services.auth,\n pictures,\n config: services.config,\n enrollment,\n workspaces,\n resolveIdentity,\n resolveSession,\n requireActiveSession,\n authenticatedMutationLimiter\n })\n const cloudAPI = createCloudAPIRouter({\n collaboration,\n database: services.database,\n rateLimitSecret: services.config.authSecret,\n documents,\n versions,\n entitlements,\n aiTokens,\n sharing,\n workspaces,\n workspaceMembers,\n resolveSession\n })\n const publicCloudAPI = createPublicCloudAPIRouter({\n collaboration,\n documents,\n versions,\n entitlements,\n sharing,\n workspaces,\n workspaceMembers,\n resolveSession\n })\n\n // Services such as billing authenticate with their own token, not a session.\n const internalAPI = services.config.internalServiceToken\n ? createInternalRoutes(\n createInternalService(services.database),\n services.config.internalServiceToken\n )\n : new Hono()\n\n return new Hono<CloudEnvironment>()\n .use(CLOUD_DISCOVERY_PATH, cloudCORS)\n .use('/api/*', cloudCORS)\n .use('*', async (context, next) => {\n await next()\n if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) {\n context.header('X-Robots-Tag', 'noindex, nofollow, noarchive')\n }\n })\n .get('/robots.txt', (context) => {\n context.header('Content-Type', 'text/plain; charset=utf-8')\n return context.body(\n services.config.indexingPolicy === 'deny'\n ? 'User-agent: *\\nDisallow: /\\n'\n : 'User-agent: *\\nDisallow: /admin\\nDisallow: /account\\nDisallow: /app\\nDisallow: /api\\nDisallow: /auth\\nDisallow: /sign-in\\nDisallow: /sign-up\\nDisallow: /join\\nDisallow: /.well-known\\n'\n )\n })\n .get('/health', (context) =>\n context.json({\n status: 'ok' as const,\n protocolVersion: CLOUD_PROTOCOL_VERSION\n })\n )\n .get('/ready', async (context) => {\n try {\n await services.database.selectFrom('workspace').select('id').limit(1).execute()\n const objects = await services.objects.checkReadiness()\n if (!objects.ok) {\n return context.json(\n { status: 'unavailable' as const, dependency: 'object_storage' as const },\n 503\n )\n }\n return context.json({\n status: 'ready' as const,\n objectStorage: {\n checksumVerification: objects.checksumVerification,\n multipartUpload: services.objects.capabilities.multipartUpload\n }\n })\n } catch {\n return context.json({ status: 'unavailable' as const }, 503)\n }\n })\n .get(CLOUD_DISCOVERY_PATH, (context) => context.json(discovery))\n .get(CLOUD_AI_JWKS_PATH, async (context) =>\n aiTokens ? context.json(aiTokens.jwks()) : context.notFound()\n )\n .on(['GET', 'POST'], `${AUTH_BASE_PATH}/*`, (context) => services.auth.handler(context.req.raw))\n .route('/', accountRoutes)\n .route('/', createPictureRoutes(pictures))\n .use('/api/shares/:shareId/collaboration-ticket', publicCollaborationLimiter)\n .use('/api/public/*', publicRateLimiter)\n .use('/api/shares/*', publicRateLimiter)\n .use('/api/invitations/*', publicRateLimiter)\n .route('/api', publicCloudAPI)\n .route('/api/internal', internalAPI)\n .use('/api/*', requireActiveSession)\n .route('/api/admin', admin)\n .use('/api/*', authenticatedMutationLimiter)\n .route('/api', cloudAPI)\n}\n\nexport type CloudApp = ReturnType<typeof createCloudApp>\n","import type { Dialect } from 'kysely'\nimport { CamelCasePlugin, Kysely } from 'kysely'\n\nimport type { CloudDatabase } from './tables'\n\nexport type CloudDatabaseOptions = {\n dialect: Dialect\n}\n\nexport function createCloudDatabase(options: CloudDatabaseOptions): Kysely<CloudDatabase> {\n return new Kysely<CloudDatabase>({\n dialect: options.dialect,\n plugins: [new CamelCasePlugin()]\n })\n}\n","import {\n Body,\n Button,\n Container,\n Head,\n Heading,\n // eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.\n Html as HTML,\n Img,\n Link,\n Preview,\n Section,\n Text\n} from '@vue-email/components'\nimport { h, type VNode } from 'vue'\n\n/** The ivory app-icon tile, served as PNG because mail clients do not draw SVG. */\nconst LOGO_URL = 'https://openpencil.dev/brand/app-icon-1024.png'\nconst SITE_URL = 'https://openpencil.dev'\n\nconst FONT = '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif'\nconst INK = '#171717'\nconst MUTED = '#6B6B6B'\n/** Deep teal from the mark; white text on it passes WCAG AA. */\nconst TEAL = '#0A6C65'\n\nconst styles = {\n body: { backgroundColor: '#F5F5EF', fontFamily: FONT, margin: '0', padding: '40px 16px' },\n card: {\n maxWidth: '480px',\n margin: '0 auto',\n padding: '40px',\n backgroundColor: '#FFFFFF',\n borderRadius: '16px',\n border: '1px solid #E7E5DC'\n },\n logo: { borderRadius: '10px', margin: '0 0 28px' },\n heading: {\n color: INK,\n fontSize: '22px',\n fontWeight: '600',\n lineHeight: '1.3',\n margin: '0 0 12px'\n },\n text: { color: '#404040', fontSize: '15px', lineHeight: '1.6', margin: '0 0 24px' },\n button: {\n backgroundColor: TEAL,\n borderRadius: '10px',\n color: '#FFFFFF',\n fontSize: '15px',\n fontWeight: '600',\n padding: '12px 22px',\n textDecoration: 'none'\n },\n note: { color: MUTED, fontSize: '13px', lineHeight: '1.6', margin: '28px 0 0' },\n link: { color: TEAL, textDecoration: 'underline' },\n footer: {\n color: MUTED,\n fontSize: '12px',\n lineHeight: '1.6',\n textAlign: 'center' as const,\n margin: '24px 0 0'\n }\n}\n\nexport type EmailLayoutProps = {\n /** The line mail clients show beside the subject. */\n preview: string\n heading: string\n message: string\n actionLabel: string\n actionURL: string\n /** Small print under the button, with an optional link at its end. */\n note?: { text: string; link?: { label: string; url: string } }\n}\n\nfunction noteContent(note: NonNullable<EmailLayoutProps['note']>) {\n if (!note.link) return note.text\n const { label, url } = note.link\n return [`${note.text} `, h(Link, { href: url, style: styles.link }, () => label), '.']\n}\n\n/** The branded email every OpenPencil service sends: the waitlist and Cloud alike. */\nexport function emailLayout(props: EmailLayoutProps): VNode {\n const { note } = props\n return h(HTML, { lang: 'en' }, () => [\n h(Head),\n h(Preview, () => props.preview),\n h(Body, { style: styles.body }, () => [\n h(Container, { style: styles.card }, () => [\n h(Img, { src: LOGO_URL, width: 44, height: 44, alt: 'OpenPencil', style: styles.logo }),\n h(Heading, { as: 'h1', style: styles.heading }, () => props.heading),\n h(Text, { style: styles.text }, () => props.message),\n h(Section, () =>\n h(Button, { href: props.actionURL, style: styles.button }, () => props.actionLabel)\n ),\n note ? h(Text, { style: styles.note }, () => noteContent(note)) : null\n ]),\n h(Text, { style: styles.footer }, () => [\n 'OpenPencil, the open-source design editor · ',\n h(Link, { href: SITE_URL, style: { color: MUTED } }, () => 'openpencil.dev')\n ])\n ])\n ])\n}\n","import type { VNode } from 'vue'\n\nimport { emailLayout } from './brand'\n\nexport type TransactionalEmailLayout = {\n preview: string\n heading: string\n message: string\n actionLabel: string\n actionURL: string\n footer?: string\n}\n\n/** Cloud's mail in the same branded layout as the waitlist's, so people know who wrote. */\nexport function transactionalEmailLayout(props: TransactionalEmailLayout): VNode {\n const { footer, ...content } = props\n return emailLayout({ ...content, note: footer ? { text: footer } : undefined })\n}\n","import { defineComponent, type PropType } from 'vue'\n\nimport { transactionalEmailLayout } from './layout'\n\nexport type DocumentInvitationEmailProps = {\n inviterName: string\n documentName: string\n permissionLabel: string\n expiresAt: string\n acceptanceURL: string\n}\n\nexport const DocumentInvitationEmail = defineComponent({\n props: {\n inviterName: { type: String, required: true },\n documentName: { type: String, required: true },\n permissionLabel: { type: String, required: true },\n expiresAt: { type: String, required: true },\n acceptanceURL: { type: String, required: true }\n } satisfies Record<\n keyof DocumentInvitationEmailProps,\n { type: PropType<string>; required: true }\n >,\n setup(props) {\n return () =>\n transactionalEmailLayout({\n preview: `${props.inviterName} invited you to ${props.permissionLabel} a document`,\n heading: 'OpenPencil invitation',\n message: `${props.inviterName} invited you to ${props.permissionLabel} “${props.documentName}”.`,\n actionLabel: 'Open document',\n actionURL: props.acceptanceURL,\n footer: `This invitation expires ${props.expiresAt}.`\n })\n }\n})\n","import { defineComponent, type PropType } from 'vue'\n\nimport { transactionalEmailLayout } from './layout'\n\nexport type EnrollmentEmailProps = {\n heading: string\n preview: string\n message: string\n actionLabel: string\n actionURL: string\n /** Small print under the button. */\n footer?: string\n}\n\nexport const EnrollmentEmail = defineComponent({\n props: {\n heading: { type: String, required: true },\n preview: { type: String, required: true },\n message: { type: String, required: true },\n actionLabel: { type: String, required: true },\n actionURL: { type: String, required: true },\n footer: { type: String, required: false }\n } satisfies Record<keyof EnrollmentEmailProps, { type: PropType<string>; required: boolean }>,\n setup(props) {\n return () => transactionalEmailLayout(props)\n }\n})\n","import { render } from '@vue-email/render'\nimport { compact } from 'es-toolkit'\n\nimport type {\n AdminEnrollmentNotificationPayload,\n AuthenticationEmailPayload,\n DocumentInvitationEmailPayload,\n EmailChangeRequestedPayload,\n EnrollmentEmailPayload,\n NewSignInPayload,\n RenderedTransactionalEmail,\n TransactionalEmailContent,\n TransactionalEmailKind,\n TwoStepChange,\n TwoStepChangedPayload,\n WorkspaceInvitationEmailPayload\n} from './schema'\nimport { DocumentInvitationEmail } from './templates/document-invitation'\nimport { EnrollmentEmail } from './templates/enrollment'\n\nasync function rendered(\n component: Parameters<typeof render>[0],\n props: Record<string, string | undefined>,\n subject: string\n): Promise<RenderedTransactionalEmail> {\n const [html, text] = await Promise.all([\n render(component, props),\n render(component, props, { plainText: true })\n ])\n return { subject, html, text }\n}\n\nasync function renderDocumentInvitation(payload: DocumentInvitationEmailPayload) {\n const permissionLabel = payload.permission === 'edit' ? 'edit' : 'view'\n return rendered(\n DocumentInvitationEmail,\n {\n inviterName: payload.inviterName,\n documentName: payload.documentName,\n permissionLabel,\n expiresAt: new Date(payload.expiresAt).toUTCString(),\n acceptanceURL: payload.acceptanceURL\n },\n `${payload.inviterName} invited you to ${permissionLabel} ${payload.documentName}`\n )\n}\n\nconst WORKSPACE_ROLE_LABELS = { admin: 'manage', editor: 'edit in', viewer: 'view' } as const\n\nasync function renderWorkspaceInvitation(payload: WorkspaceInvitationEmailPayload) {\n const action = WORKSPACE_ROLE_LABELS[payload.role]\n return rendered(\n EnrollmentEmail,\n {\n heading: `Join ${payload.workspaceName}`,\n preview: `${payload.inviterName} invited you to ${payload.workspaceName}`,\n message: `${payload.inviterName} invited you to ${action} the workspace “${payload.workspaceName}” on OpenPencil Cloud. You will see its documents on Home once you join.`,\n actionLabel: 'Join workspace',\n actionURL: payload.acceptanceURL,\n footer: `This invitation expires ${new Date(payload.expiresAt).toUTCString()}.`\n },\n `${payload.inviterName} invited you to ${payload.workspaceName}`\n )\n}\n\ntype EnrollmentMessageKind = Exclude<\n TransactionalEmailKind,\n | 'document-invitation'\n | 'workspace-invitation'\n | 'admin-enrollment-notification'\n | 'email-verification'\n | 'password-reset'\n | 'password-changed'\n | 'email-change-requested'\n | 'new-sign-in'\n | 'two-step-changed'\n>\n\ntype EnrollmentCopy = {\n subject: string\n heading: string\n preview: string\n message: string\n actionLabel: string\n}\n\nconst ENROLLMENT_COPY: Record<EnrollmentMessageKind, Omit<EnrollmentCopy, 'message'>> = {\n 'enrollment-requested': {\n subject: 'We received your OpenPencil Cloud request',\n heading: 'Request received',\n preview: 'Your OpenPencil Cloud access request is awaiting review.',\n actionLabel: 'Open OpenPencil Cloud'\n },\n 'enrollment-approved': {\n subject: 'Your OpenPencil Cloud access is ready',\n heading: 'Access approved',\n preview: 'You can now sign in to OpenPencil Cloud.',\n actionLabel: 'Sign in'\n },\n 'enrollment-rejected': {\n subject: 'Your OpenPencil Cloud request was reviewed',\n heading: 'Request reviewed',\n preview: 'Your current access request was not approved.',\n actionLabel: 'Request access again'\n },\n 'enrollment-revoked': {\n subject: 'Your OpenPencil Cloud access has changed',\n heading: 'Access changed',\n preview: 'Your OpenPencil Cloud access is no longer active.',\n actionLabel: 'Open OpenPencil'\n }\n}\n\nfunction enrollmentCopy(kind: EnrollmentMessageKind, name: string): EnrollmentCopy {\n const copy = ENROLLMENT_COPY[kind]\n const messages: Record<EnrollmentMessageKind, string> = {\n 'enrollment-requested': `Hi ${name}, your request is awaiting manual review.`,\n 'enrollment-approved': `Hi ${name}, your access request was approved.`,\n 'enrollment-rejected': `Hi ${name}, your current access request was not approved.`,\n 'enrollment-revoked': `Hi ${name}, your Cloud access is no longer active.`\n }\n return { ...copy, message: messages[kind] }\n}\n\nasync function renderEnrollment(kind: EnrollmentMessageKind, payload: EnrollmentEmailPayload) {\n const copy = enrollmentCopy(kind, payload.name)\n return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL }, copy.subject)\n}\n\nasync function renderAdminNotification(payload: AdminEnrollmentNotificationPayload) {\n return rendered(\n EnrollmentEmail,\n {\n heading: 'New Cloud access request',\n preview: `${payload.requesterEmail} requested OpenPencil Cloud access.`,\n message: `${payload.requesterName} (${payload.requesterEmail}) requested access. ${payload.reason}`,\n actionLabel: 'Review request',\n actionURL: payload.actionURL\n },\n 'New OpenPencil Cloud access request'\n )\n}\n\nasync function renderAuthentication(\n kind: 'email-verification' | 'password-reset' | 'password-changed',\n payload: AuthenticationEmailPayload\n) {\n const copy = {\n 'email-verification':\n payload.purpose === 'change'\n ? {\n subject: 'Confirm your new OpenPencil Cloud email',\n heading: 'Confirm your new email',\n preview: 'One click to move your OpenPencil Cloud account to this address.',\n message: `Hi ${payload.name}, confirm this address to make it your OpenPencil Cloud account’s email. Your old address stays until you do.`,\n actionLabel: 'Confirm email',\n footer: 'Didn’t ask for this? Ignore this email and nothing changes.'\n }\n : {\n subject: 'Confirm your OpenPencil Cloud email',\n heading: 'Confirm your email',\n preview: 'One click to finish creating your OpenPencil Cloud account.',\n message: `Hi ${payload.name}, confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.`,\n actionLabel: 'Confirm email',\n footer: 'Didn’t create an account? Ignore this email and nothing happens.'\n },\n 'password-reset': {\n subject: 'Reset your OpenPencil Cloud password',\n heading: 'Reset your password',\n preview: 'Use this secure link to choose a new password.',\n message: `Hi ${payload.name}, use the link below to choose a new password.`,\n actionLabel: 'Reset password',\n footer: 'Didn’t ask for this? Ignore this email and your password stays the same.'\n },\n 'password-changed': {\n subject: 'Your OpenPencil Cloud password changed',\n heading: 'Password changed',\n preview: 'Your OpenPencil Cloud password was changed.',\n message: `Hi ${payload.name}, your password was changed. If this was not you, contact your administrator.`,\n actionLabel: 'Open OpenPencil Cloud'\n }\n }[kind]\n return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL ?? '#' }, copy.subject)\n}\n\nasync function renderEmailChangeRequested(payload: EmailChangeRequestedPayload) {\n return rendered(\n EnrollmentEmail,\n {\n heading: 'Your email is changing',\n preview: `Your OpenPencil Cloud email is changing to ${payload.newEmail}.`,\n message: `Hi ${payload.name}, someone signed in to your account asked to change its email to ${payload.newEmail}. It changes once that address confirms it. If this wasn’t you, change your password and sign out of your other sessions.`,\n actionLabel: 'Review your account',\n actionURL: payload.actionURL\n },\n 'Your OpenPencil Cloud email is changing'\n )\n}\n\nasync function renderNewSignIn(payload: NewSignInPayload) {\n const device = payload.desktop\n ? 'the OpenPencil app'\n : compact([payload.browser, payload.system]).join(' on ') || 'an unknown browser'\n const place = payload.ipAddress ? ` from ${payload.ipAddress}` : ''\n return rendered(\n EnrollmentEmail,\n {\n heading: 'New sign-in to your account',\n preview: `Your OpenPencil Cloud account was signed in to with ${device}.`,\n message: `Hi ${payload.name}, your account was signed in to with ${device}${place} on ${new Date(payload.signedInAt).toUTCString()}. If this was you, there’s nothing to do. If it wasn’t, sign that session out and change your password.`,\n actionLabel: 'Review sessions',\n actionURL: payload.actionURL\n },\n 'New sign-in to your OpenPencil Cloud account'\n )\n}\n\nconst TWO_STEP_COPY: Record<TwoStepChange, { heading: string; message: string }> = {\n 'authenticator-on': {\n heading: 'Authenticator app turned on',\n message: 'an authenticator app now confirms your sign-ins.'\n },\n 'authenticator-off': {\n heading: 'Authenticator app turned off',\n message: 'your sign-ins no longer ask for a code from an authenticator app.'\n },\n 'passkey-added': {\n heading: 'Passkey added',\n message: 'a passkey was added to your account.'\n },\n 'passkey-removed': {\n heading: 'Passkey removed',\n message: 'a passkey was removed from your account.'\n },\n 'reset-by-administrator': {\n heading: 'Two-step sign-in was reset',\n message:\n 'an administrator removed your authenticator app, recovery codes, and passkeys, so you can set them up again.'\n }\n}\n\nasync function renderTwoStepChanged(payload: TwoStepChangedPayload) {\n const copy = TWO_STEP_COPY[payload.change]\n return rendered(\n EnrollmentEmail,\n {\n heading: copy.heading,\n preview: `${copy.heading} on your OpenPencil Cloud account.`,\n message: `Hi ${payload.name}, ${copy.message} If this wasn’t you, change your password and contact your administrator.`,\n actionLabel: 'Review security',\n actionURL: payload.actionURL\n },\n `${copy.heading} on your OpenPencil Cloud account`\n )\n}\n\nexport async function renderTransactionalEmail(\n content: TransactionalEmailContent\n): Promise<RenderedTransactionalEmail> {\n if (content.kind === 'document-invitation') return renderDocumentInvitation(content.payload)\n if (content.kind === 'workspace-invitation') return renderWorkspaceInvitation(content.payload)\n if (content.kind === 'admin-enrollment-notification') {\n return renderAdminNotification(content.payload)\n }\n if (\n content.kind === 'email-verification' ||\n content.kind === 'password-reset' ||\n content.kind === 'password-changed'\n ) {\n return renderAuthentication(content.kind, content.payload)\n }\n if (content.kind === 'email-change-requested') return renderEmailChangeRequested(content.payload)\n if (content.kind === 'new-sign-in') return renderNewSignIn(content.payload)\n if (content.kind === 'two-step-changed') return renderTwoStepChanged(content.payload)\n return renderEnrollment(content.kind, content.payload)\n}\n","import { documentPermissionSchema, workspaceRoleSchema } from '#cloud/contract'\nimport * as v from 'valibot'\n\nexport type TransactionalEmailKind =\n | 'document-invitation'\n | 'workspace-invitation'\n | 'enrollment-requested'\n | 'admin-enrollment-notification'\n | 'enrollment-approved'\n | 'enrollment-rejected'\n | 'enrollment-revoked'\n | 'email-verification'\n | 'password-reset'\n | 'password-changed'\n | 'email-change-requested'\n | 'new-sign-in'\n | 'two-step-changed'\n\nconst documentInvitationEmailPayloadSchema = v.object({\n inviterName: v.string(),\n documentName: v.string(),\n permission: documentPermissionSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst workspaceInvitationEmailPayloadSchema = v.object({\n inviterName: v.string(),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst enrollmentEmailPayloadSchema = v.object({\n name: v.string(),\n actionURL: v.string()\n})\n\nconst adminEnrollmentNotificationPayloadSchema = v.object({\n requesterEmail: v.string(),\n requesterName: v.string(),\n reason: v.string(),\n actionURL: v.string()\n})\n\nconst authenticationEmailPayloadSchema = v.object({\n name: v.string(),\n actionURL: v.optional(v.string()),\n /** What a verification link confirms: a new account, or a new address for one. */\n purpose: v.optional(v.picklist(['account', 'change']))\n})\n\nconst emailChangeRequestedPayloadSchema = v.object({\n name: v.string(),\n newEmail: v.string(),\n actionURL: v.string()\n})\n\nconst newSignInPayloadSchema = v.object({\n name: v.string(),\n signedInAt: v.string(),\n ipAddress: v.nullable(v.string()),\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n desktop: v.boolean(),\n actionURL: v.string()\n})\n\n/** What changed about how an account proves it is its owner's. */\nexport const twoStepChangeSchema = v.picklist([\n 'authenticator-on',\n 'authenticator-off',\n 'passkey-added',\n 'passkey-removed',\n 'reset-by-administrator'\n])\n\nconst twoStepChangedPayloadSchema = v.object({\n name: v.string(),\n change: twoStepChangeSchema,\n actionURL: v.string()\n})\n\nfunction content<const Kind extends TransactionalEmailKind, Payload extends v.GenericSchema>(\n kind: Kind,\n payload: Payload\n) {\n return v.object({ kind: v.literal(kind), payload })\n}\n\nexport const transactionalEmailContentSchema = v.variant('kind', [\n content('document-invitation', documentInvitationEmailPayloadSchema),\n content('workspace-invitation', workspaceInvitationEmailPayloadSchema),\n content('enrollment-requested', enrollmentEmailPayloadSchema),\n content('admin-enrollment-notification', adminEnrollmentNotificationPayloadSchema),\n content('enrollment-approved', enrollmentEmailPayloadSchema),\n content('enrollment-rejected', enrollmentEmailPayloadSchema),\n content('enrollment-revoked', enrollmentEmailPayloadSchema),\n content('email-verification', authenticationEmailPayloadSchema),\n content('password-reset', authenticationEmailPayloadSchema),\n content('password-changed', authenticationEmailPayloadSchema),\n content('email-change-requested', emailChangeRequestedPayloadSchema),\n content('new-sign-in', newSignInPayloadSchema),\n content('two-step-changed', twoStepChangedPayloadSchema)\n])\n\n/** A transactional email's kind with the payload that kind renders. */\nexport type TransactionalEmailContent = v.InferOutput<typeof transactionalEmailContentSchema>\n\nexport type DocumentInvitationEmailPayload = v.InferOutput<\n typeof documentInvitationEmailPayloadSchema\n>\nexport type WorkspaceInvitationEmailPayload = v.InferOutput<\n typeof workspaceInvitationEmailPayloadSchema\n>\nexport type EnrollmentEmailPayload = v.InferOutput<typeof enrollmentEmailPayloadSchema>\nexport type AdminEnrollmentNotificationPayload = v.InferOutput<\n typeof adminEnrollmentNotificationPayloadSchema\n>\nexport type AuthenticationEmailPayload = v.InferOutput<typeof authenticationEmailPayloadSchema>\nexport type EmailChangeRequestedPayload = v.InferOutput<typeof emailChangeRequestedPayloadSchema>\nexport type NewSignInPayload = v.InferOutput<typeof newSignInPayloadSchema>\nexport type TwoStepChange = v.InferOutput<typeof twoStepChangeSchema>\nexport type TwoStepChangedPayload = v.InferOutput<typeof twoStepChangedPayloadSchema>\n\nexport type TransactionalEmailPayloadByKind = {\n [Kind in TransactionalEmailKind]: Extract<TransactionalEmailContent, { kind: Kind }>['payload']\n}\n\nexport type TransactionalEmailMessage<\n Kind extends TransactionalEmailKind = TransactionalEmailKind\n> = {\n id: string\n kind: Kind\n recipientEmail: string\n payload: TransactionalEmailPayloadByKind[Kind]\n}\n\nexport type RenderedTransactionalEmail = {\n subject: string\n html: string\n text: string\n}\n","import {\n transactionalEmailContentSchema,\n type TransactionalEmailContent,\n type TransactionalEmailKind,\n type TransactionalEmailPayloadByKind\n} from '#cloud/email'\nimport { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\nimport * as v from 'valibot'\n\nconst EMAIL_PAYLOAD_SALT = utf8ToBytes('openpencil-cloud-transactional-email')\nconst EMAIL_PAYLOAD_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nfunction emailPayloadKey(secret: string, id: string, kind: TransactionalEmailKind): Uint8Array {\n return hkdf(\n sha256,\n utf8ToBytes(secret),\n EMAIL_PAYLOAD_SALT,\n encoder.encode(`openpencil-cloud-email:${kind}:${id}`),\n 32\n )\n}\n\nexport async function encryptTransactionalEmailPayload<Kind extends TransactionalEmailKind>(\n secret: string,\n id: string,\n kind: Kind,\n payload: TransactionalEmailPayloadByKind[Kind]\n): Promise<string> {\n return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))\n .setProtectedHeader(EMAIL_PAYLOAD_HEADER)\n .encrypt(emailPayloadKey(secret, id, kind))\n}\n\nexport async function decryptTransactionalEmailPayload(\n secret: string,\n id: string,\n kind: TransactionalEmailKind,\n value: string\n): Promise<TransactionalEmailContent> {\n const { plaintext, protectedHeader } = await compactDecrypt(\n value,\n emailPayloadKey(secret, id, kind)\n )\n if (\n protectedHeader.alg !== EMAIL_PAYLOAD_HEADER.alg ||\n protectedHeader.enc !== EMAIL_PAYLOAD_HEADER.enc\n ) {\n throw new Error('Unsupported transactional email payload encryption')\n }\n const payload = v.parse(v.pipe(v.string(), v.parseJson()), decoder.decode(plaintext))\n return v.parse(transactionalEmailContentSchema, { kind, payload })\n}\n","import { renderTransactionalEmail } from '#cloud/email'\nimport type { TransactionalEmailKind } from '#cloud/email'\nimport type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'\nimport type {\n EnqueueTransactionalEmailInput,\n TransactionalEmailDeliveryOptions,\n TransactionalEmailDeliveryResult,\n TransactionalEmailService,\n TransactionalEmailTransport\n} from './types'\n\nconst DEFAULT_MAXIMUM_ATTEMPTS = 5\nconst MAXIMUM_RETRY_DELAY_MS = 60 * 60_000\n\nexport type TransactionalEmailTransportErrorKind =\n | 'configuration'\n | 'suppressed'\n | 'permanent'\n | 'rate-limited'\n | 'transient'\n\nexport class TransactionalEmailTransportError extends Error {\n override readonly name = 'TransactionalEmailTransportError'\n\n constructor(\n readonly kind: TransactionalEmailTransportErrorKind,\n readonly code: string,\n message: string,\n options?: ErrorOptions\n ) {\n super(message, options)\n }\n}\n\ntype ClaimedTransactionalEmail = {\n id: string\n kind: TransactionalEmailKind\n recipientEmailNormalized: string\n payloadEncrypted: string\n attemptCount: number\n}\n\nfunction normalizedEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nfunction retryDelayMilliseconds(attemptCount: number): number {\n return Math.min(MAXIMUM_RETRY_DELAY_MS, 2 ** Math.max(0, attemptCount - 1) * 30_000)\n}\n\nfunction transportFailure(error: unknown): TransactionalEmailTransportError {\n return error instanceof TransactionalEmailTransportError\n ? error\n : new TransactionalEmailTransportError(\n 'transient',\n 'transport_error',\n 'Transactional email transport failed',\n { cause: error }\n )\n}\n\nfunction failureStatus(\n error: TransactionalEmailTransportError,\n attemptCount: number,\n maximumAttempts: number\n): TransactionalEmailStatus {\n if (error.kind === 'suppressed') return 'suppressed'\n if (error.kind === 'configuration' || error.kind === 'permanent') return 'failed'\n return attemptCount >= maximumAttempts ? 'failed' : 'pending'\n}\n\nexport function createTransactionalEmailService(\n database: Kysely<CloudDatabase>,\n options: {\n encryptionSecret: string\n from: string\n transport?: TransactionalEmailTransport\n }\n): TransactionalEmailService {\n return {\n async enqueue<Kind extends TransactionalEmailKind>(\n input: EnqueueTransactionalEmailInput<Kind>,\n transaction: Transaction<CloudDatabase> | undefined\n ): Promise<string> {\n const id = crypto.randomUUID()\n const payloadEncrypted = await encryptTransactionalEmailPayload(\n options.encryptionSecret,\n id,\n input.kind,\n input.payload\n )\n const executor = transaction ?? database\n const row = await executor\n .insertInto('transactionalEmail')\n .values({\n id,\n idempotencyKey: input.idempotencyKey,\n kind: input.kind,\n recipientEmailNormalized: normalizedEmail(input.recipientEmail),\n payloadEncrypted,\n status: 'pending',\n nextAttemptAt: new Date(),\n claimId: null,\n claimedAt: null,\n transport: null,\n transportMessageId: null,\n lastErrorCode: null,\n acceptedAt: null\n })\n .onConflict((conflict) => conflict.column('idempotencyKey').doNothing())\n .returning('id')\n .executeTakeFirst()\n if (row) return row.id\n return (\n await executor\n .selectFrom('transactionalEmail')\n .select('id')\n .where('idempotencyKey', '=', input.idempotencyKey)\n .executeTakeFirstOrThrow()\n ).id\n },\n\n async deliverPending(\n deliveryOptions: TransactionalEmailDeliveryOptions\n ): Promise<TransactionalEmailDeliveryResult> {\n if (!options.transport) {\n return { claimed: 0, accepted: 0, retrying: 0, failed: 0, suppressed: 0 }\n }\n const now = deliveryOptions.now ?? new Date()\n const maximumAttempts = deliveryOptions.maximumAttempts ?? DEFAULT_MAXIMUM_ATTEMPTS\n const staleBefore = new Date(now.getTime() - deliveryOptions.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const claimed = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('transactionalEmail')\n .select(['id', 'kind', 'recipientEmailNormalized', 'payloadEncrypted', 'attemptCount'])\n .where('payloadEncrypted', 'is not', null)\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('nextAttemptAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'sending'),\n expression('claimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('nextAttemptAt')\n .limit(deliveryOptions.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n await transaction\n .updateTable('transactionalEmail')\n .set({ status: 'sending', claimId, claimedAt: now, updatedAt: now })\n .where(\n 'id',\n 'in',\n candidates.map((candidate) => candidate.id)\n )\n .execute()\n return candidates.filter(\n (candidate): candidate is ClaimedTransactionalEmail => candidate.payloadEncrypted !== null\n )\n })\n\n const result: TransactionalEmailDeliveryResult = {\n claimed: claimed.length,\n accepted: 0,\n retrying: 0,\n failed: 0,\n suppressed: 0\n }\n for (const message of claimed) {\n const attemptCount = message.attemptCount + 1\n try {\n const content = await decryptTransactionalEmailPayload(\n options.encryptionSecret,\n message.id,\n message.kind,\n message.payloadEncrypted\n )\n const rendered = await renderTransactionalEmail(content)\n const sent = await options.transport.send({\n deliveryId: message.id,\n from: options.from,\n to: message.recipientEmailNormalized,\n subject: rendered.subject,\n html: rendered.html,\n text: rendered.text,\n headers: { 'X-OpenPencil-Delivery-ID': message.id }\n })\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: null,\n status: 'accepted',\n attemptCount,\n transport: options.transport.id,\n transportMessageId: sent.transportMessageId,\n lastErrorCode: null,\n acceptedAt: new Date(sent.acceptedAt),\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n result.accepted++\n } catch (unknownError) {\n const error = transportFailure(unknownError)\n const status = failureStatus(error, attemptCount, maximumAttempts)\n const terminal = status === 'failed' || status === 'suppressed'\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: terminal ? null : message.payloadEncrypted,\n status,\n attemptCount,\n nextAttemptAt: new Date(now.getTime() + retryDelayMilliseconds(attemptCount)),\n transport: options.transport.id,\n lastErrorCode: error.code,\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n if (status === 'suppressed') result.suppressed++\n else if (status === 'failed') result.failed++\n else result.retrying++\n }\n }\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentInvitationMessage, InvitationOutbox } from '#cloud/server/invitations'\nimport type { Transaction } from 'kysely'\n\nimport type { TransactionalEmailService } from './types'\n\nexport function createInvitationOutbox(email: TransactionalEmailService): InvitationOutbox {\n return {\n enqueueDocumentInvitation(\n message: DocumentInvitationMessage,\n transaction?: Transaction<CloudDatabase>\n ): Promise<string> {\n return email.enqueue(\n {\n idempotencyKey: `document-invitation/${message.deliveryId}`,\n kind: 'document-invitation',\n recipientEmail: message.recipientEmail,\n payload: {\n inviterName: message.inviterName,\n documentName: message.documentName,\n permission: message.permission,\n expiresAt: message.expiresAt,\n acceptanceURL: message.acceptanceURL\n }\n },\n transaction\n )\n }\n }\n}\n","import { startPeriodicWorker } from '../worker/periodic'\nimport type { TransactionalEmailDeliveryResult, TransactionalEmailService } from './types'\n\nexport type TransactionalEmailWorkerOptions = {\n batchSize: number\n intervalMs: number\n leaseDurationMs: number\n maximumAttempts: number\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type TransactionalEmailWorker = {\n runOnce(): Promise<TransactionalEmailDeliveryResult>\n stop(): Promise<void>\n}\n\nexport function startTransactionalEmailWorker(\n email: TransactionalEmailService,\n options: TransactionalEmailWorkerOptions\n): TransactionalEmailWorker {\n return startPeriodicWorker({\n intervalMs: options.intervalMs,\n signal: options.signal,\n onError: options.onError,\n run: () =>\n email.deliverPending({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs,\n maximumAttempts: options.maximumAttempts\n })\n })\n}\n","import { createCloudDatabase } from '#cloud/server'\nimport { PostgresDialect } from 'kysely'\nimport { Pool, type PoolConfig } from 'pg'\n\nexport type PostgresCloudDatabaseOptions = {\n connectionString: string\n pool?: Omit<PoolConfig, 'connectionString'>\n}\n\nexport function createPostgresCloudDatabase(options: PostgresCloudDatabaseOptions) {\n return createCloudDatabase({\n dialect: new PostgresDialect({\n pool: new Pool({\n ...options.pool,\n connectionString: options.connectionString\n })\n })\n })\n}\n","import { readFile } from 'node:fs/promises'\n\nimport {\n CloudConfigError,\n parseCloudDeploymentTOML,\n type CloudEnvironment,\n type CloudServerConfig\n} from '#cloud/server'\n\nexport async function loadNodeCloudServerConfig(\n environment: CloudEnvironment\n): Promise<CloudServerConfig> {\n const path = environment.OPENPENCIL_CLOUD_CONFIG\n if (!path) throw new CloudConfigError('OPENPENCIL_CLOUD_CONFIG must name a deployment TOML file')\n return parseCloudDeploymentTOML(await readFile(path, 'utf8'), environment)\n}\n","import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'\nimport {\n createBetterAuthAdapter,\n migrateCloudDatabase,\n type CloudServerConfig\n} from '#cloud/server'\n\nimport { loadNodeCloudServerConfig } from './config'\n\nexport async function createMigratedNodeCloudDatabase(\n environment: Readonly<Record<string, string | undefined>>\n): Promise<{\n config: CloudServerConfig\n database: ReturnType<typeof createPostgresCloudDatabase>\n auth: ReturnType<typeof createBetterAuthAdapter>\n}> {\n const config = await loadNodeCloudServerConfig(environment)\n const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })\n const auth = createBetterAuthAdapter(config, database)\n await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })\n return { config, database, auth }\n}\n","import type { CloudServerConfig } from '#cloud/server'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport {\n AbortMultipartUploadCommand,\n CompleteMultipartUploadCommand,\n CreateMultipartUploadCommand,\n DeleteObjectCommand,\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n S3Client,\n UploadPartCommand\n} from '@aws-sdk/client-s3'\n// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.\nimport { getSignedUrl as getSignedURL } from '@aws-sdk/s3-request-presigner'\n\nconst CHECKSUM_METADATA_KEY = 'openpencil-sha256'\nconst READINESS_BODY = new TextEncoder().encode('openpencil-ready')\nconst READINESS_CHECKSUM = 'Hq6g3mmWpyBNobXoWZIz/d0/d8KLjJyEKqNnJh6KXjA='\nconst MULTIPART_THRESHOLD = 32 * 1024 * 1024\nconst MULTIPART_PART_SIZE = 16 * 1024 * 1024\nconst MAX_MULTIPART_PARTS = 10_000\n\ntype S3ErrorMetadata = {\n $metadata?: {\n httpStatusCode?: number\n }\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n '$metadata' in error &&\n (error as S3ErrorMetadata).$metadata?.httpStatusCode === 404\n )\n}\n\nfunction encryption(config: CloudServerConfig) {\n return config.s3ServerSideEncryption\n ? {\n ServerSideEncryption: config.s3ServerSideEncryption,\n ...(config.s3KmsKeyId ? { SSEKMSKeyId: config.s3KmsKeyId } : {})\n }\n : {}\n}\n\nexport function createS3ObjectStore(config: CloudServerConfig): ObjectStore {\n const client = new S3Client({\n endpoint: config.s3Endpoint,\n region: config.s3Region,\n forcePathStyle: config.s3ForcePathStyle,\n requestChecksumCalculation: 'WHEN_REQUIRED',\n responseChecksumValidation: 'WHEN_REQUIRED',\n credentials: {\n accessKeyId: config.s3AccessKeyId,\n secretAccessKey: config.s3SecretAccessKey,\n ...(config.s3SessionToken ? { sessionToken: config.s3SessionToken } : {})\n }\n })\n const nativeSHA256 = config.s3ChecksumVerification === 'native'\n\n async function headObject(key: string) {\n return client.send(\n new HeadObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n ...(nativeSHA256 ? { ChecksumMode: 'ENABLED' as const } : {})\n })\n )\n }\n\n return {\n capabilities: {\n nativeSHA256,\n multipartUpload: true,\n conditionalWrites: false\n },\n\n async checkReadiness() {\n const key = `.openpencil/readiness/${crypto.randomUUID()}`\n try {\n await client.send(\n new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n Body: READINESS_BODY,\n ContentType: 'application/octet-stream',\n ChecksumSHA256: nativeSHA256 ? READINESS_CHECKSUM : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: READINESS_CHECKSUM },\n ...encryption(config)\n })\n )\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n return {\n ok: object.ContentLength === READINESS_BODY.byteLength && checksum === READINESS_CHECKSUM,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata'\n }\n } finally {\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n }\n },\n\n async createDownload(input) {\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const url = await getSignedURL(\n client,\n new GetObjectCommand({ Bucket: config.s3Bucket, Key: input.key }),\n { expiresIn }\n )\n return {\n url,\n method: 'GET',\n headers: {},\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async createUpload(input) {\n if (input.byteSize > MULTIPART_THRESHOLD) {\n const created = await client.send(\n new CreateMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n )\n if (!created.UploadId) throw new Error('S3 did not return a multipart upload ID')\n const partCount = Math.ceil(input.byteSize / MULTIPART_PART_SIZE)\n if (partCount > MAX_MULTIPART_PARTS) throw new Error('Object requires too many S3 parts')\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const parts = await Promise.all(\n Array.from({ length: partCount }, async (_, index) => {\n const partNumber = index + 1\n return {\n partNumber,\n url: await getSignedURL(\n client,\n new UploadPartCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: created.UploadId,\n PartNumber: partNumber\n }),\n { expiresIn }\n ),\n method: 'PUT' as const,\n headers: {}\n }\n })\n )\n return {\n kind: 'multipart',\n uploadId: created.UploadId,\n partSize: MULTIPART_PART_SIZE,\n parts,\n expiresAt: input.expiresAt.toISOString()\n }\n }\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const command = new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n const url = await getSignedURL(client, command, {\n expiresIn,\n unhoistableHeaders: new Set([\n ...(nativeSHA256 ? ['x-amz-checksum-sha256'] : []),\n `x-amz-meta-${CHECKSUM_METADATA_KEY}`\n ])\n })\n return {\n kind: 'single',\n url,\n method: 'PUT',\n headers: {\n 'Content-Type': input.contentType,\n ...(nativeSHA256 ? { 'x-amz-checksum-sha256': input.checksum } : {}),\n [`x-amz-meta-${CHECKSUM_METADATA_KEY}`]: input.checksum\n },\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async completeUpload(input) {\n await client.send(\n new CompleteMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId,\n MultipartUpload: {\n Parts: input.parts.map((part) => ({ ETag: part.etag, PartNumber: part.partNumber }))\n }\n })\n )\n },\n\n async abortUpload(input) {\n try {\n await client.send(\n new AbortMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId\n })\n )\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n },\n\n async head(key) {\n try {\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n if (object.ContentLength == null || !checksum || !object.ContentType) return null\n return {\n byteSize: object.ContentLength,\n checksum,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata',\n contentType: object.ContentType\n }\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n },\n\n async delete(key) {\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n }\n }\n}\n","import { renderTransactionalEmail } from '#cloud/email'\nimport type { TransactionalEmailTransport } from '#cloud/server/email'\nimport type { DocumentInvitationMessage, InvitationDelivery } from '#cloud/server/invitations'\nimport nodemailer, { type Transporter } from 'nodemailer'\nimport type Mail from 'nodemailer/lib/mailer/index.js'\n\nexport type NodemailerTransporter = {\n sendMail(mail: Mail.Options): Promise<unknown>\n}\n\nexport type NodemailerTransactionalEmailTransportOptions = {\n transporter: NodemailerTransporter\n}\n\nexport function createNodemailerTransactionalEmailTransport(\n options: NodemailerTransactionalEmailTransportOptions\n): TransactionalEmailTransport {\n return {\n id: 'smtp',\n async send(message) {\n const result = (await options.transporter.sendMail({\n from: message.from,\n to: message.to,\n subject: message.subject,\n html: message.html,\n text: message.text,\n headers: message.headers,\n messageId: `<${message.deliveryId}@openpencil.cloud>`\n })) as { messageId?: unknown }\n if (typeof result.messageId !== 'string') {\n throw new TypeError('SMTP transport returned no message ID')\n }\n return {\n transportMessageId: result.messageId,\n acceptedAt: new Date().toISOString()\n }\n }\n }\n}\n\nexport type SMTPTransactionalEmailTransportOptions = {\n host: string\n port: number\n secure: boolean\n user?: string\n password?: string\n}\n\nfunction createSMTPTransporter(options: SMTPTransactionalEmailTransportOptions): Transporter {\n return nodemailer.createTransport({\n host: options.host,\n port: options.port,\n secure: options.secure,\n connectionTimeout: 10_000,\n greetingTimeout: 10_000,\n socketTimeout: 30_000,\n auth:\n options.user && options.password ? { user: options.user, pass: options.password } : undefined\n })\n}\n\nexport function createSMTPTransactionalEmailTransport(\n options: SMTPTransactionalEmailTransportOptions\n): TransactionalEmailTransport {\n return createNodemailerTransactionalEmailTransport({\n transporter: createSMTPTransporter(options)\n })\n}\n\nexport type NodemailerInvitationDeliveryOptions = NodemailerTransactionalEmailTransportOptions & {\n from: string\n}\n\nexport function createNodemailerInvitationDelivery(\n options: NodemailerInvitationDeliveryOptions\n): InvitationDelivery {\n const transport = createNodemailerTransactionalEmailTransport(options)\n return {\n async sendDocumentInvitation(message: DocumentInvitationMessage): Promise<void> {\n const rendered = await renderTransactionalEmail({\n kind: 'document-invitation',\n payload: {\n inviterName: message.inviterName,\n documentName: message.documentName,\n permission: message.permission,\n expiresAt: message.expiresAt,\n acceptanceURL: message.acceptanceURL\n }\n })\n await transport.send({\n deliveryId: message.deliveryId,\n from: options.from,\n to: message.recipientEmail,\n ...rendered,\n headers: { 'X-OpenPencil-Delivery-ID': message.deliveryId }\n })\n }\n }\n}\n\nexport type SMTPInvitationDeliveryOptions = SMTPTransactionalEmailTransportOptions & {\n from: string\n}\n\nexport function createSMTPInvitationDelivery(\n options: SMTPInvitationDeliveryOptions\n): InvitationDelivery {\n return createNodemailerInvitationDelivery({\n transporter: createSMTPTransporter(options),\n from: options.from\n })\n}\n","import {\n createInvitationOutbox,\n createTransactionalEmailService,\n type CloudServerConfig,\n type TransactionalEmailService,\n type TransactionalEmailTransport\n} from '#cloud/server'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nimport { createSMTPTransactionalEmailTransport } from './transport'\n\nexport type NodeTransactionalEmailRuntime = {\n email: TransactionalEmailService\n transport?: TransactionalEmailTransport\n invitationOutbox?: ReturnType<typeof createInvitationOutbox>\n}\n\nexport function createNodeTransactionalEmailRuntime(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>\n): NodeTransactionalEmailRuntime {\n const transport =\n config.emailTransport === 'smtp' && config.smtpHost && config.smtpPort\n ? createSMTPTransactionalEmailTransport({\n host: config.smtpHost,\n port: config.smtpPort,\n secure: config.smtpSecure ?? config.smtpPort === 465,\n user: config.smtpUser,\n password: config.smtpPassword\n })\n : undefined\n const email = createTransactionalEmailService(database, {\n encryptionSecret: config.authSecret,\n from: config.emailFrom ?? '',\n transport\n })\n return {\n email,\n transport,\n invitationOutbox: transport ? createInvitationOutbox(email) : undefined\n }\n}\n","import type { IncomingMessage, Server } from 'node:http'\nimport type { Duplex } from 'node:stream'\n\nimport { RELAY_PATH } from '#cloud/contract'\nimport type { CollaborationRelay } from '#cloud/server'\nimport { WebSocketServer, type RawData } from 'ws'\n\nfunction bytes(data: RawData): Uint8Array {\n if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data))\n return data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data)\n}\n\n/**\n * Accepts WebSocket upgrades on the relay path of an HTTP server and hands each socket to the\n * relay. Other upgrade requests are refused.\n */\nexport function attachCollaborationRelay(\n server: Pick<Server, 'on' | 'off'>,\n relay: CollaborationRelay,\n maximumMessageBytes: number\n) {\n // ws enforces the limit before buffering; the relay checks again for other runtimes.\n const sockets = new WebSocketServer({ noServer: true, maxPayload: maximumMessageBytes })\n\n function upgrade(request: IncomingMessage, socket: Duplex, head: Buffer) {\n const path = new URL(request.url ?? '/', 'http://relay').pathname\n if (path !== RELAY_PATH) {\n socket.destroy()\n return\n }\n sockets.handleUpgrade(request, socket, head, (webSocket) => {\n webSocket.binaryType = 'nodebuffer'\n const connection = relay.connect({\n send: (data) => webSocket.send(data),\n close: (code, reason) => webSocket.close(code, reason)\n })\n webSocket.on('message', (data) => connection.receive(bytes(data)))\n webSocket.on('close', () => connection.closed())\n webSocket.on('error', () => webSocket.terminate())\n })\n }\n\n server.on('upgrade', upgrade)\n return {\n async close() {\n server.off('upgrade', upgrade)\n await relay.close()\n for (const client of sockets.clients) client.terminate()\n await new Promise<void>((resolve) => {\n sockets.close(() => resolve())\n })\n }\n }\n}\n","import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'\nimport { withIndexingPolicy } from '#cloud/server'\nimport { Hono } from 'hono'\n\n/** A file of the Cloud site (`bun run build:cloud`): the editor and the portal. */\nexport type SiteFile = {\n body: ReadableStream | Uint8Array<ArrayBuffer>\n type: string\n /** Overrides the cache policy built files get, for a site whose files change in place. */\n cacheControl?: string\n}\n\n/** Reads the built site's file at a URL path, or null when there is none. */\nexport type SiteFiles = (path: string, request: Request) => Promise<SiteFile | null>\n\nconst PORTAL_PAGE = '/cloud.html'\nconst EDITOR_PAGE = '/index.html'\n\nconst PAGE_HEADERS = {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-cache',\n // Desktop sign-in approval and the editor must never be framed by another site.\n 'Content-Security-Policy': \"frame-ancestors 'none'\",\n 'Referrer-Policy': 'no-referrer',\n 'X-Content-Type-Options': 'nosniff'\n}\n\nexport type CloudServerOptions = {\n /** The built site; without it, the server answers only its API. */\n site?: SiteFiles\n indexingPolicy: 'allow' | 'deny'\n}\n\nfunction cacheControl(path: string): string {\n if (path.startsWith('/assets/')) return 'public, max-age=31536000, immutable'\n return 'public, max-age=3600'\n}\n\n/**\n * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API\n * everywhere else, and, where the API has nothing, the site's files, or the editor's\n * `index.html` for any other page, whose router knows the editor's own addresses.\n */\nexport function createCloudServer(\n api: { fetch(request: Request): Response | Promise<Response> },\n { site, indexingPolicy }: CloudServerOptions\n) {\n const server = new Hono()\n server.use(async (c, next) => {\n await next()\n c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)\n })\n if (site) {\n const pages = CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])\n server.on(['GET', 'HEAD'], pages, async (c) => {\n const page = await site(PORTAL_PAGE, c.req.raw)\n return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()\n })\n server.on(['GET', 'HEAD'], '*', async (c, next) => {\n await next()\n if (c.res.status !== 404) return\n const file = await site(c.req.path, c.req.raw)\n if (file) {\n c.res = file.type.startsWith('text/html')\n ? new Response(file.body, { headers: PAGE_HEADERS })\n : new Response(file.body, {\n headers: {\n 'Content-Type': file.type,\n 'Cache-Control': file.cacheControl ?? cacheControl(c.req.path),\n 'X-Content-Type-Options': 'nosniff'\n }\n })\n return\n }\n if (!c.req.header('Accept')?.includes('text/html')) return\n const editor = await site(EDITOR_PAGE, c.req.raw)\n if (editor) c.res = new Response(editor.body, { headers: PAGE_HEADERS })\n })\n }\n server.all('*', (c) => api.fetch(c.req.raw))\n return server\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve, sep } from 'node:path'\n\nimport type { SiteFiles } from '#cloud/runtime/site/server'\nimport { getMimeType } from 'hono/utils/mime'\n\n/**\n * The only request headers Vite reads to pick a reply: which module, style, or page form to send.\n * Others stay behind, such as credentials, ranges, and validators that would get a partial or 304.\n */\nconst FORWARDED_HEADERS = ['accept', 'sec-fetch-dest']\n\n/** The built site's files in `directory`, never anything outside it. */\nexport function nodeSiteFiles(directory: string): SiteFiles {\n const root = resolve(directory)\n return async (path) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(path)\n } catch {\n return null\n }\n const file = resolve(root, `.${decoded}`)\n if (!file.startsWith(`${root}${sep}`)) return null\n try {\n return {\n body: new Uint8Array(await readFile(file)),\n // Documents such as the editor's demo `.fig` have no registered type.\n type: getMimeType(decoded) ?? 'application/octet-stream'\n }\n } catch {\n return null\n }\n }\n}\n\n/**\n * The site as the Vite development server at `origin` serves it, for `bun run cloud:dev`: pages,\n * modules, and styles come from source as they are now, so an edit shows without a build.\n */\nexport function developmentSiteFiles(origin: string): SiteFiles {\n return async (path, request) => {\n const url = new URL(path, origin)\n const requested = new URL(request.url)\n // Vite tells module requests apart by their query, such as `?import` or `?t=`.\n if (requested.pathname === path) url.search = requested.search\n const headers = new Headers()\n for (const name of FORWARDED_HEADERS) {\n const value = request.headers.get(name)\n if (value !== null) headers.set(name, value)\n }\n try {\n const response = await fetch(url, { headers })\n if (!response.ok || !response.body) return null\n return {\n body: response.body,\n type: response.headers.get('Content-Type') ?? 'application/octet-stream',\n cacheControl: 'no-cache'\n }\n } catch {\n return null\n }\n }\n}\n","import { defaultRelayURL } from '#cloud/contract'\nimport { createS3ObjectStore } from '#cloud/runtime/s3/objects'\nimport { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'\nimport {\n createCloudApp,\n loadAISigningKey,\n createCloudAuthenticationRuntime,\n createCollaborationRelay,\n createCollaborationStateStore,\n cleanupPassOptions,\n createCleanupServices,\n createConfiguredCloudPolicy,\n relayDocumentLookups,\n startCleanupWorker,\n startTransactionalEmailWorker\n} from '#cloud/server'\n\nimport { createMigratedNodeCloudDatabase } from './bootstrap'\nimport { createNodeTransactionalEmailRuntime } from './email/runtime'\nimport { listen } from './listen'\nimport { attachCollaborationRelay } from './relay'\nimport { developmentSiteFiles, nodeSiteFiles } from './site'\n\nexport type NodeCloudServerOptions = {\n environment?: Readonly<Record<string, string | undefined>>\n port?: number\n}\n\n/** The site the server serves: a build, or in `cloud:dev` a development server's source. */\nfunction siteFiles(\n environment: Readonly<Record<string, string | undefined>>\n): SiteFiles | undefined {\n const developmentSite = environment.OPENPENCIL_CLOUD_DEV_SITE_URL\n if (developmentSite) return developmentSiteFiles(developmentSite)\n const siteDirectory = environment.OPENPENCIL_CLOUD_SITE_DIR\n if (siteDirectory) return nodeSiteFiles(siteDirectory)\n console.warn(\n '[Cloud] OPENPENCIL_CLOUD_SITE_DIR is not set; the editor and sign-in pages are off.'\n )\n return undefined\n}\n\nexport async function startNodeCloudServer(options: NodeCloudServerOptions = {}) {\n const environment = options.environment ?? process.env\n const { config, database } = await createMigratedNodeCloudDatabase(environment)\n // Before any worker starts, so a key that cannot sign leaves nothing running.\n const aiSigningKey = await loadAISigningKey(config).catch(async (error: unknown) => {\n await database.destroy()\n throw error\n })\n const objects = createS3ObjectStore(config)\n const {\n email,\n invitationOutbox,\n transport: emailTransport\n } = createNodeTransactionalEmailRuntime(config, database)\n const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)\n const policy = createConfiguredCloudPolicy(config, database)\n const cleanup = config.cleanupEnabled\n ? startCleanupWorker(createCleanupServices(config, database, objects, policy), {\n ...cleanupPassOptions(config),\n intervalMs: config.cleanupIntervalMs,\n onError: (error) => console.error('[Cloud] Cleanup worker failed:', error)\n })\n : undefined\n const relay = createCollaborationRelay({\n authSecret: config.authSecret,\n store: createCollaborationStateStore(database),\n maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,\n maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,\n ...relayDocumentLookups(database, policy, config.deployment)\n })\n const app = createCloudApp({\n config,\n database,\n auth,\n objects,\n invitationOutbox,\n transactionalEmail: email,\n enrollment,\n aiSigningKey,\n relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),\n onDocumentRestored: (documentId) => relay.startOver(documentId),\n onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId)\n })\n const emailWorker = emailTransport\n ? startTransactionalEmailWorker(email, {\n batchSize: config.emailBatchSize,\n intervalMs: config.emailIntervalMs,\n leaseDurationMs: config.emailLeaseDurationMs,\n maximumAttempts: config.emailMaximumAttempts,\n onError: (error) => console.error('[Cloud] Email worker failed:', error)\n })\n : undefined\n const cloudServer = createCloudServer(app, {\n site: siteFiles(environment),\n indexingPolicy: config.indexingPolicy\n })\n const server = await listen(\n async (request) => cloudServer.fetch(request),\n options.port ?? Number(environment.PORT ?? 8787),\n environment.HOST ?? '0.0.0.0'\n )\n const relayListener = attachCollaborationRelay(\n server.http,\n relay,\n config.technicalLimits.maximumCollaborationMessageBytes\n )\n return {\n app,\n database,\n url: server.url,\n async stop() {\n await relayListener.close()\n await server.close()\n await cleanup?.stop()\n await emailWorker?.stop()\n await database.destroy()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAa,0BAA0B,EAAE,SAAS;CAAC;CAAU;CAAW;CAAY;AAAS,CAAC;AAC9F,MAAa,sBAAsB,EAAE,OAAO;CAC1C,QAAQ,EAAE,OAAO;CACjB,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,CAAC;CACnC,MAAM,EAAE,OAAO;;CAEf,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;CACxC,gBAAgB,EAAE,SAAS,EAAE,SAAS,CAAC,QAAQ,OAAO,CAAC,CAAC;AAC1D,CAAC;AAE+C,EAAE,OAAO;CACvD,MAAM;CACN,OAAO;AACT,CAAC;AAED,MAAa,oCAAoC,EAAE,SAAS;CAAC;CAAc;CAAU;AAAO,CAAC;AAC7F,MAAa,kCAAkC,EAAE,OAAO;CACtD,IAAI,EAAE,OAAO;CACb,UAAU;CACV,WAAW,EAAE,OAAO;CACpB,WAAW,EAAE,QAAQ;AACvB,CA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AAQ,OAAO,YAAY,QAAQ,IAAI,GAC/C,YAAY,QAAQ,SACtB;CACA,MAAM,gBAAgB,yBACpB,OAAO,MACP,OACA,OAAO,gBAAgB,gCACzB;CACA,OAAO;EACL;EACA;EACA,KAAK,OAAO;EACZ,MAAM,OAAO;GACX,MAAM,cAAc,MAAM;GAC1B,MAAM,OAAO,MAAM;GACnB,MAAM,SAAS,KAAK;GACpB,MAAM,aAAa,KAAK;GACxB,MAAM,SAAS,QAAQ;EACzB;CACF;AACF"}
1
+ {"version":3,"file":"server.mjs","names":["isBase64","countSchema","enrollmentStatusSchema","uuidSchema","FILTERS","searchCondition","FILTERS","FILTERS","dateString","enrollmentStatusSchema","parseTOML","invitationContract","providerPicture","toISOString","DOWNLOAD_LIFETIME_MS","WRITABLE_ROLES","INVITATION_SECRET_BYTES","INVITATION_LIFETIME_MS","invitationContract","HTML","getSignedURL"],"sources":["../src/contract/account.ts","../src/contract/workspaces.ts","../src/contract/admin/index.ts","../src/contract/collaboration.ts","../src/contract/sharing.ts","../src/contract/links.ts","../src/contract/portal.ts","../src/contract/versions.ts","../src/admin/errors.ts","../src/admin/api/security.ts","../src/admin/schema.ts","../src/server/rate-limit/cleanup.ts","../src/server/rate-limit/keys.ts","../src/server/rate-limit/postgres.ts","../src/server/rate-limit/middleware.ts","../src/admin/api/routes.ts","../src/admin/list.ts","../src/admin/audit/service.ts","../src/admin/email/service.ts","../src/admin/enrollment/email.ts","../src/admin/enrollment/service.ts","../src/admin/operations/service.ts","../src/server/policy/keys.ts","../src/server/policy/static.ts","../src/server/config/deployment.ts","../src/server/config/public.ts","../src/server/auth/account.ts","../src/server/sharing/contracts.ts","../src/server/auth/endpoints.ts","../src/server/auth/user-agent.ts","../src/server/auth/activity.ts","../src/server/auth/email.ts","../src/server/auth/mfa-assurance.ts","../src/server/pictures/provider.ts","../src/server/pictures/service.ts","../src/server/pictures/routes.ts","../src/server/auth/social-providers.ts","../src/server/auth/factory.ts","../src/server/auth/runtime.ts","../src/server/auth/session.ts","../src/admin/users/service.ts","../src/server/ai/errors.ts","../src/server/ai/keys.ts","../src/server/documents/access.ts","../src/server/documents/errors.ts","../src/server/quota/storage.ts","../src/server/documents/routes.ts","../src/server/cleanup/objects.ts","../src/server/cleanup/documents.ts","../src/server/documents/images.ts","../src/server/documents/versions/history.ts","../src/server/cleanup/revisions.ts","../src/server/cleanup/uploads.ts","../src/server/cleanup/configured.ts","../src/server/worker/interval.ts","../src/server/worker/periodic.ts","../src/server/cleanup/worker.ts","../src/server/documents/summary.ts","../src/server/documents/limits.ts","../src/server/documents/repository.ts","../src/server/documents/versions/checkpoint.ts","../src/server/documents/service.ts","../src/server/ai/routes.ts","../src/server/ai/service.ts","../src/server/sharing/access.ts","../src/server/sharing/crypto.ts","../src/server/sharing/errors.ts","../src/server/policy/database.ts","../src/server/policy/entitlements.ts","../src/server/policy/provider.ts","../src/server/policy/policy.ts","../src/server/policy/configured.ts","../src/server/policy/service.ts","../src/server/sharing/policy.ts","../src/server/sharing/capabilities/service.ts","../src/server/sharing/grants/service.ts","../src/server/sharing/continuation.ts","../src/server/workspaces/repository.ts","../src/server/workspaces/members.ts","../src/server/sharing/http.ts","../src/server/sharing/actor.ts","../src/server/sharing/document-routes.ts","../src/server/sharing/invitations/service.ts","../src/server/sharing/routes.ts","../src/server/sharing/service.ts","../src/server/collaboration/routes.ts","../src/server/collaboration/service.ts","../src/server/collaboration/relay/authorize.ts","../src/server/collaboration/relay/awareness.ts","../src/server/collaboration/relay/documents.ts","../src/server/collaboration/relay/connection.ts","../src/server/collaboration/relay/log.ts","../src/server/collaboration/relay/hub.ts","../src/server/collaboration/relay/persistence.ts","../src/server/documents/versions/routes.ts","../src/server/documents/versions/service.ts","../src/server/workspaces/service.ts","../src/server/workspaces/routes.ts","../src/server/api/router.ts","../src/server/account/actions.ts","../src/server/account/routes.ts","../src/server/errors/index.ts","../src/server/internal/schema.ts","../src/server/internal/service.ts","../src/server/internal/routes.ts","../src/server/app.ts","../src/server/db/database.ts","../src/email/templates/brand.ts","../src/email/templates/layout.ts","../src/email/templates/document-invitation.ts","../src/email/templates/enrollment.ts","../src/email/render.ts","../src/email/schema.ts","../src/server/email/crypto.ts","../src/server/email/service.ts","../src/server/email/invitations.ts","../src/server/email/worker.ts","../src/runtime/postgres/database.ts","../src/runtime/node/config.ts","../src/runtime/node/bootstrap.ts","../src/runtime/s3/objects.ts","../src/runtime/node/email/transport.ts","../src/runtime/node/email/runtime.ts","../src/runtime/node/relay.ts","../src/runtime/posthog/errors.ts","../src/runtime/site/server.ts","../src/runtime/node/site.ts","../src/runtime/node/server.ts"],"sourcesContent":["import { isValid as isBase64 } from 'js-base64'\nimport * as v from 'valibot'\n\nexport const cloudAccountStateSchema = v.picklist(['active', 'pending', 'rejected', 'revoked'])\nexport const cloudIdentitySchema = v.object({\n userId: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.string(),\n /** The account's picture, such as one a social provider gave it. */\n image: v.optional(v.nullable(v.string())),\n deploymentRole: v.optional(v.picklist(['user', 'admin']))\n})\n\nexport const cloudAccountStatusResponseSchema = v.object({\n user: cloudIdentitySchema,\n state: cloudAccountStateSchema\n})\n\nexport const cloudAuthenticationProviderSchema = v.picklist(['credential', 'google', 'apple'])\nexport const cloudAuthenticationMethodSchema = v.object({\n id: v.string(),\n provider: cloudAuthenticationProviderSchema,\n createdAt: v.string(),\n canUnlink: v.boolean()\n})\nexport const cloudAuthenticationMethodsResponseSchema = v.object({\n methods: v.array(cloudAuthenticationMethodSchema),\n availableSocialProviders: v.array(v.picklist(['google', 'apple']))\n})\nexport const cloudPasswordChangeSchema = v.object({\n currentPassword: v.string(),\n newPassword: v.string()\n})\nexport const cloudSocialLinkSchema = v.object({\n provider: v.picklist(['google', 'apple']),\n callbackURL: v.pipe(v.string(), v.url())\n})\nexport const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) })\nexport const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() })\nexport const accountSecurityErrorCodeSchema = v.picklist([\n 'current_password_invalid',\n 'password_too_short',\n 'password_too_long',\n 'last_authentication_method',\n 'session_not_fresh',\n 'authentication_method_failed',\n 'email_unchanged',\n 'email_change_unavailable',\n 'current_session',\n 'picture_invalid'\n])\nexport const accountSecurityErrorResponseSchema = v.object({\n error: v.object({ code: accountSecurityErrorCodeSchema })\n})\n\nexport const cloudMFAStatusSchema = v.object({\n required: v.boolean(),\n enabled: v.boolean(),\n totpEnabled: v.boolean(),\n assured: v.boolean(),\n totpAvailable: v.boolean(),\n passkeysAvailable: v.boolean(),\n recoveryCodesAvailable: v.boolean()\n})\nexport const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema })\nexport const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) })\nexport const cloudMFAEnableResponseSchema = v.object({\n totpURI: v.string(),\n backupCodes: v.array(v.string())\n})\nexport const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) })\nexport const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) })\nexport const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) })\nexport const cloudPasskeySchema = v.object({\n id: v.string(),\n name: v.nullish(v.string()),\n createdAt: v.string()\n})\nexport const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) })\nexport const cloudPasskeyDeleteSchema = v.object({ id: v.string() })\n\nexport function parseCloudMFAEnable(input: unknown) {\n return v.parse(cloudMFAEnableSchema, input)\n}\nexport function parseCloudMFAVerify(input: unknown) {\n return v.parse(cloudMFAVerifySchema, input)\n}\nexport function parseCloudPasskeyDelete(input: unknown) {\n return v.parse(cloudPasskeyDeleteSchema, input)\n}\nexport function parseCloudPasswordChange(input: unknown) {\n return v.parse(cloudPasswordChangeSchema, input)\n}\nexport function parseCloudSocialLink(input: unknown) {\n return v.parse(cloudSocialLinkSchema, input)\n}\nexport function parseCloudUnlinkAuthenticationMethod(input: unknown) {\n return v.parse(cloudUnlinkAuthenticationMethodSchema, input)\n}\n\nexport const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) })\n\n/** Who an account belongs to, as the portal shows it. */\nexport const cloudPersonSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n /** The address of the account's picture, which the server serves; null shows initials. */\n image: v.nullable(v.string())\n})\n/** What a person can see and change about themselves. */\nexport const cloudProfileSchema = v.object({\n ...cloudPersonSchema.entries,\n createdAt: v.string(),\n /** Whether the server can send the verification a new email address needs. */\n emailChangeAvailable: v.boolean()\n})\nexport const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema })\nexport const cloudProfileUpdateSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\n/** The largest picture an account may upload, once the page has cropped and shrunk it. */\nexport const CLOUD_PICTURE_MAX_BYTES = 256 * 1024\n/** The width and height a page shrinks a picture to before it uploads it. */\nexport const CLOUD_PICTURE_SIZE = 256\nexport const cloudPictureUploadSchema = v.object({\n /** The picture's PNG or JPEG bytes, in Base64. */\n data: v.pipe(\n v.string(),\n v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4),\n v.check((value) => isBase64(value))\n )\n})\n/** The address the account's picture is now served from. */\nexport const cloudPictureResponseSchema = v.object({ image: v.string() })\nexport const cloudEmailChangeSchema = v.object({\n newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n callbackURL: v.pipe(v.string(), v.url())\n})\n\n/** How a sign-in was made: the method it used, or the desktop app's approved code. */\nexport const cloudSignInMethodSchema = v.picklist([\n 'password',\n 'google',\n 'apple',\n 'passkey',\n 'two-step',\n 'email-link',\n 'desktop',\n 'other'\n])\nexport const cloudAccountSessionSchema = v.object({\n id: v.string(),\n /** The session this request was made with. */\n current: v.boolean(),\n method: v.nullable(cloudSignInMethodSchema),\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string(),\n lastActiveAt: v.string(),\n expiresAt: v.string()\n})\nexport const cloudAccountSessionsResponseSchema = v.object({\n sessions: v.array(cloudAccountSessionSchema)\n})\nexport const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) })\nexport const cloudSignInSchema = v.object({\n id: v.string(),\n method: cloudSignInMethodSchema,\n ipAddress: v.nullable(v.string()),\n /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n createdAt: v.string()\n})\nexport const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) })\n\nexport function parseCloudProfileUpdate(input: unknown) {\n return v.parse(cloudProfileUpdateSchema, input)\n}\nexport function parseCloudPictureUpload(input: unknown) {\n return v.parse(cloudPictureUploadSchema, input)\n}\nexport function parseCloudEmailChange(input: unknown) {\n return v.parse(cloudEmailChangeSchema, input)\n}\nexport function parseCloudSessionRevoke(input: unknown) {\n return v.parse(cloudSessionRevokeSchema, input)\n}\n\nexport type AccountSecurityErrorCode = v.InferOutput<typeof accountSecurityErrorCodeSchema>\nexport type CloudAuthenticationProvider = v.InferOutput<typeof cloudAuthenticationProviderSchema>\nexport type CloudAuthenticationMethod = v.InferOutput<typeof cloudAuthenticationMethodSchema>\nexport type CloudAuthenticationMethods = v.InferOutput<\n typeof cloudAuthenticationMethodsResponseSchema\n>\n\nexport type CloudAccountStatus = v.InferOutput<typeof cloudAccountStatusResponseSchema>\nexport type CloudProfile = v.InferOutput<typeof cloudProfileSchema>\nexport type CloudSignInMethod = v.InferOutput<typeof cloudSignInMethodSchema>\nexport type CloudAccountSession = v.InferOutput<typeof cloudAccountSessionSchema>\nexport type CloudSignIn = v.InferOutput<typeof cloudSignInSchema>\n","import * as v from 'valibot'\n\nexport const workspaceRoleSchema = v.picklist(['viewer', 'editor', 'admin'])\nexport type WorkspaceRole = v.InferOutput<typeof workspaceRoleSchema>\n\nexport const workspaceSummarySchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n name: v.string(),\n slug: v.string(),\n role: workspaceRoleSchema,\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type WorkspaceSummary = v.InferOutput<typeof workspaceSummarySchema>\n\nexport const createWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),\n slug: v.optional(\n v.pipe(\n v.string(),\n v.trim(),\n v.minLength(3),\n v.maxLength(63),\n v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)\n )\n )\n})\nexport type CreateWorkspaceInput = v.InferOutput<typeof createWorkspaceSchema>\n\nexport const workspaceListSchema = v.object({\n workspaces: v.array(workspaceSummarySchema)\n})\nexport type WorkspaceList = v.InferOutput<typeof workspaceListSchema>\n\nexport const updateWorkspaceSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))\n})\nexport type UpdateWorkspaceInput = v.InferOutput<typeof updateWorkspaceSchema>\n\n/** Someone who belongs to a workspace, and what they may do in it. */\nexport const workspaceMemberSchema = v.object({\n userId: v.string(),\n name: v.string(),\n email: v.string(),\n image: v.nullable(v.string()),\n role: workspaceRoleSchema,\n joinedAt: v.string()\n})\nexport type WorkspaceMember = v.InferOutput<typeof workspaceMemberSchema>\n\n/** An invitation to join a workspace that has not been accepted yet. */\nexport const workspaceInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n email: v.string(),\n role: workspaceRoleSchema,\n /** Who sent it; the name is null once their account is gone. */\n invitedBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n invitedAt: v.string(),\n expiresAt: v.string()\n})\nexport type WorkspaceInvitation = v.InferOutput<typeof workspaceInvitationSchema>\n\nexport const workspaceMembersSchema = v.object({\n members: v.array(workspaceMemberSchema),\n /** Only administrators see pending invitations. */\n invitations: v.array(workspaceInvitationSchema)\n})\nexport type WorkspaceMembers = v.InferOutput<typeof workspaceMembersSchema>\n\nexport const createWorkspaceInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n role: workspaceRoleSchema\n})\nexport type CreateWorkspaceInvitationInput = v.InferOutput<typeof createWorkspaceInvitationSchema>\n\n/** A new invitation and its link, for an administrator to pass on when email is off. */\nexport const createdWorkspaceInvitationSchema = v.object({\n invitation: workspaceInvitationSchema,\n acceptanceURL: v.string()\n})\nexport type CreatedWorkspaceInvitation = v.InferOutput<typeof createdWorkspaceInvitationSchema>\n\nexport const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema })\nexport type UpdateWorkspaceMemberInput = v.InferOutput<typeof updateWorkspaceMemberSchema>\n\nexport function parseCreateWorkspace(input: unknown): CreateWorkspaceInput {\n return v.parse(createWorkspaceSchema, input)\n}\n\nexport function parseUpdateWorkspace(input: unknown): UpdateWorkspaceInput {\n return v.parse(updateWorkspaceSchema, input)\n}\n\nexport function parseCreateWorkspaceInvitation(input: unknown): CreateWorkspaceInvitationInput {\n return v.parse(createWorkspaceInvitationSchema, input)\n}\n\nexport function parseUpdateWorkspaceMember(input: unknown): UpdateWorkspaceMemberInput {\n return v.parse(updateWorkspaceMemberSchema, input)\n}\n","import { zipObject } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport {\n cloudIdentitySchema,\n cloudAccountSessionSchema,\n cloudPersonSchema,\n cloudSignInSchema\n} from '../account'\nimport { workspaceRoleSchema } from '../workspaces'\n\nconst timestampSchema = v.pipe(v.string(), v.isoTimestamp())\nconst nullableTimestampSchema = v.nullable(timestampSchema)\nconst countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))\n\n/**\n * What every admin list answers besides its rows: how many rows match the search and filter\n * across every page, and how many match the search under each filter.\n */\nfunction listTotals<const Filter extends string>(filters: readonly Filter[]) {\n return {\n total: countSchema,\n counts: v.object(\n zipObject(\n filters,\n filters.map(() => countSchema)\n )\n )\n }\n}\n\nexport const adminErrorCodeSchema = v.picklist([\n 'bad_request',\n 'unauthorized',\n 'forbidden',\n 'not_found',\n 'rate_limited',\n 'invalid_enrollment_transition',\n 'last_admin_required',\n 'self_admin_action_forbidden',\n 'email_regeneration_unavailable',\n 'mfa_required'\n])\n\nexport const adminErrorResponseSchema = v.object({\n error: v.object({ code: adminErrorCodeSchema })\n})\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentSchema = v.object({\n id: v.string(),\n email: v.pipe(v.string(), v.email()),\n name: v.nullable(v.string()),\n reason: v.nullable(v.string()),\n status: enrollmentStatusSchema,\n requestedAt: timestampSchema,\n reviewedAt: nullableTimestampSchema,\n reviewedBy: v.nullable(v.string()),\n /** The reviewer's name, in lists, while the server still knows them. */\n reviewerName: v.optional(v.nullable(v.string())),\n reviewNote: v.nullable(v.string()),\n approvedUserId: v.nullable(v.string()),\n requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))\n})\n\nexport const enrollmentsResponseSchema = v.object({\n enrollments: v.array(enrollmentSchema),\n ...listTotals(enrollmentStatusSchema.options)\n})\nexport const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema })\n\nexport const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })\n\nexport const cloudAdminUserSchema = v.object({\n ...cloudPersonSchema.entries,\n role: v.optional(v.string()),\n banned: v.nullable(v.boolean()),\n banReason: v.optional(v.nullable(v.string())),\n createdAt: timestampSchema,\n /** An authenticator app or a passkey confirms this account's sign-ins. */\n twoStep: v.boolean(),\n /** When one of the account's sessions was last used, or null when none is left. */\n lastActiveAt: nullableTimestampSchema,\n workspaceCount: countSchema\n})\n\n/** Which accounts a list of people shows. */\nexport const cloudAdminUserFilterSchema = v.picklist([\n 'all',\n 'administrators',\n 'suspended',\n 'without-two-step'\n])\nexport const cloudAdminUsersResponseSchema = v.object({\n users: v.array(cloudAdminUserSchema),\n ...listTotals(cloudAdminUserFilterSchema.options)\n})\n\nexport const cloudAdminUserDetailSchema = v.object({\n user: v.object({\n ...cloudAdminUserSchema.entries,\n emailVerified: v.boolean()\n }),\n methods: v.array(v.object({ provider: v.string(), createdAt: timestampSchema })),\n authenticator: v.boolean(),\n passkeyCount: countSchema,\n sessions: v.array(cloudAccountSessionSchema),\n signIns: v.array(cloudSignInSchema),\n workspaces: v.array(\n v.object({\n id: v.string(),\n name: v.string(),\n role: workspaceRoleSchema,\n memberCount: countSchema,\n joinedAt: timestampSchema\n })\n )\n})\n\nexport const adminMutationResponseSchema = v.object({ ok: v.literal(true) })\n\nexport const transactionalEmailAdminSchema = v.object({\n id: v.string(),\n kind: v.string(),\n recipientEmailNormalized: v.pipe(v.string(), v.email()),\n status: v.string(),\n attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),\n nextAttemptAt: timestampSchema,\n transport: v.nullable(v.string()),\n transportMessageId: v.nullable(v.string()),\n lastErrorCode: v.nullable(v.string()),\n createdAt: timestampSchema,\n acceptedAt: nullableTimestampSchema,\n regeneratable: v.boolean()\n})\n/** Which messages a list of email shows, by how their delivery went. */\nexport const cloudAdminEmailFilterSchema = v.picklist(['all', 'sent', 'waiting', 'failed'])\nexport const adminEmailResponseSchema = v.object({\n messages: v.array(transactionalEmailAdminSchema),\n ...listTotals(cloudAdminEmailFilterSchema.options)\n})\n\n/** Who or what an event names; `name` is null once the server no longer knows it. */\nconst auditPartySchema = v.object({ id: v.string(), name: v.nullable(v.string()) })\n\nexport const adminAuditEventSchema = v.object({\n id: v.string(),\n actor: auditPartySchema,\n action: v.string(),\n /** What the event is about: an account, an access request, or an email. */\n subject: v.object({ ...auditPartySchema.entries, type: v.string() }),\n metadata: v.unknown(),\n createdAt: timestampSchema\n})\n/** Which events a list of activity shows, by what they are about. */\nexport const cloudAdminAuditFilterSchema = v.picklist(['all', 'accounts', 'requests', 'email'])\nexport const adminAuditResponseSchema = v.object({\n events: v.array(adminAuditEventSchema),\n ...listTotals(cloudAdminAuditFilterSchema.options)\n})\n\nexport const adminOperationsResponseSchema = v.object({\n deployment: v.picklist(['official', 'self-hosted']),\n enrollmentMode: v.picklist(['open', 'approval', 'closed']),\n emailTransport: v.picklist(['none', 'smtp', 'cloudflare']),\n pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),\n pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),\n accounts: countSchema,\n workspaces: countSchema,\n documents: countSchema,\n storedBytes: countSchema\n})\n\nexport type AdminErrorCode = v.InferOutput<typeof adminErrorCodeSchema>\nexport type Enrollment = v.InferOutput<typeof enrollmentSchema>\nexport type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>\nexport type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>\nexport type CloudAdminUserFilter = v.InferOutput<typeof cloudAdminUserFilterSchema>\nexport type CloudAdminEmailFilter = v.InferOutput<typeof cloudAdminEmailFilterSchema>\nexport type CloudAdminAuditFilter = v.InferOutput<typeof cloudAdminAuditFilterSchema>\nexport type EnrollmentStatus = v.InferOutput<typeof enrollmentStatusSchema>\nexport type CloudAdminUsers = v.InferOutput<typeof cloudAdminUsersResponseSchema>\nexport type CloudAdminUserDetail = v.InferOutput<typeof cloudAdminUserDetailSchema>\nexport type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>\nexport type AdminAuditEvent = v.InferOutput<typeof adminAuditEventSchema>\nexport type AdminOperations = v.InferOutput<typeof adminOperationsResponseSchema>\n","import * as v from 'valibot'\n\nimport { documentPermissionSchema } from './documents'\n\nexport const collaborationPrincipalSchema = v.variant('kind', [\n v.object({\n kind: v.literal('user'),\n userId: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email())\n }),\n v.object({\n kind: v.literal('guest'),\n guestId: v.string(),\n name: v.string()\n })\n])\nexport type CollaborationPrincipal = v.InferOutput<typeof collaborationPrincipalSchema>\n\n/**\n * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so\n * other peers can trust it over what the peer says of itself.\n */\nexport const cloudPresenceSchema = v.object({\n kind: v.picklist(['user', 'guest']),\n id: v.string(),\n name: v.string(),\n permission: documentPermissionSchema\n})\nexport type CloudPresence = v.InferOutput<typeof cloudPresenceSchema>\n\nexport const collaborationTicketSchema = v.object({\n token: v.string(),\n provider: v.optional(v.picklist(['trystero', 'relay'])),\n serverURL: v.optional(v.pipe(v.string(), v.url())),\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),\n principal: collaborationPrincipalSchema,\n permission: documentPermissionSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n expiresAt: v.string(),\n serverEnforcedWrites: v.boolean()\n})\nexport type CollaborationTicket = v.InferOutput<typeof collaborationTicketSchema>\n","import * as v from 'valibot'\n\nimport { collaborationPrincipalSchema } from './collaboration'\nimport { documentPermissionSchema, requestImageLinksSchema } from './documents'\nimport { workspaceRoleSchema } from './workspaces'\n\nexport const documentShareSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n permission: documentPermissionSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string(),\n expiresAt: v.nullable(v.string()),\n revokedAt: v.nullable(v.string()),\n lastUsedAt: v.nullable(v.string())\n})\nexport type DocumentShare = v.InferOutput<typeof documentShareSchema>\n\n/** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */\nconst shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())))\n\nexport const createDocumentShareSchema = v.object({\n permission: documentPermissionSchema,\n expiresAt: shareExpirySchema\n})\nexport type CreateDocumentShareInput = v.InferOutput<typeof createDocumentShareSchema>\n\nexport const updateDocumentShareSchema = v.object({\n permission: v.optional(documentPermissionSchema),\n expiresAt: shareExpirySchema\n})\nexport type UpdateDocumentShareInput = v.InferOutput<typeof updateDocumentShareSchema>\n\nexport const resolveDocumentShareSchema = v.object({\n secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),\n guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),\n guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))\n})\nexport type ResolveDocumentShareInput = v.InferOutput<typeof resolveDocumentShareSchema>\n\n/** A guest's request for the links of images a shared document's live room names. */\nexport const requestSharedImageLinksSchema = v.object({\n ...resolveDocumentShareSchema.entries,\n ...requestImageLinksSchema.entries\n})\nexport type RequestSharedImageLinksInput = v.InferOutput<typeof requestSharedImageLinksSchema>\n\nexport function parseRequestSharedImageLinks(input: unknown): RequestSharedImageLinksInput {\n return v.parse(requestSharedImageLinksSchema, input)\n}\n\nexport const resolvedDocumentShareSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n permission: documentPermissionSchema,\n principal: collaborationPrincipalSchema,\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))\n})\nexport type ResolvedDocumentShare = v.InferOutput<typeof resolvedDocumentShareSchema>\n\nexport const cloudUserProfileSchema = v.object({\n id: v.string(),\n name: v.string(),\n email: v.pipe(v.string(), v.email()),\n image: v.nullable(v.pipe(v.string(), v.url()))\n})\nexport type CloudUserProfile = v.InferOutput<typeof cloudUserProfileSchema>\n\nexport const documentGrantSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n userId: v.string(),\n permission: documentPermissionSchema,\n createdBy: v.string(),\n createdAt: v.string(),\n updatedAt: v.string()\n})\nexport type DocumentGrant = v.InferOutput<typeof documentGrantSchema>\n\n/** What accepting an invitation gave: access to a document, or a place in a workspace. */\nexport const acceptedInvitationSchema = v.variant('kind', [\n v.object({ kind: v.literal('document'), grant: documentGrantSchema }),\n v.object({\n kind: v.literal('workspace'),\n workspaceId: v.pipe(v.string(), v.uuid()),\n role: workspaceRoleSchema\n })\n])\nexport type AcceptedInvitation = v.InferOutput<typeof acceptedInvitationSchema>\n\nexport const lookupCloudUserSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email())\n})\nexport type LookupCloudUserInput = v.InferOutput<typeof lookupCloudUserSchema>\n\nexport const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema })\nexport type PutDocumentGrantInput = v.InferOutput<typeof putDocumentGrantSchema>\n\nexport const createDocumentInvitationSchema = v.object({\n email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),\n permission: documentPermissionSchema\n})\nexport type CreateDocumentInvitationInput = v.InferOutput<typeof createDocumentInvitationSchema>\n\nexport const acceptDocumentInvitationSchema = v.object({\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type AcceptDocumentInvitationInput = v.InferOutput<typeof acceptDocumentInvitationSchema>\n\nexport const createInvitationContinuationSchema = v.object({\n invitationId: v.pipe(v.string(), v.uuid()),\n token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))\n})\nexport type CreateInvitationContinuationInput = v.InferOutput<\n typeof createInvitationContinuationSchema\n>\n\nexport const invitationContinuationSchema = v.object({\n id: v.pipe(v.string(), v.minLength(16), v.maxLength(128))\n})\nexport type InvitationContinuation = v.InferOutput<typeof invitationContinuationSchema>\n\nconst invitationPreviewFields = {\n inviterName: v.string(),\n expiresAt: v.string(),\n recipientHint: v.string()\n}\n\n/** What an invitation link opens: one document, or a whole workspace. */\nexport const invitationPreviewSchema = v.variant('kind', [\n v.object({\n kind: v.literal('document'),\n documentName: v.string(),\n permission: documentPermissionSchema,\n ...invitationPreviewFields\n }),\n v.object({\n kind: v.literal('workspace'),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n ...invitationPreviewFields\n })\n])\nexport type InvitationPreview = v.InferOutput<typeof invitationPreviewSchema>\n\nexport const documentInvitationSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n documentId: v.pipe(v.string(), v.uuid()),\n email: v.pipe(v.string(), v.email()),\n permission: documentPermissionSchema,\n invitedBy: v.string(),\n invitedAt: v.string(),\n expiresAt: v.string(),\n acceptedAt: v.nullable(v.string())\n})\nexport type DocumentInvitation = v.InferOutput<typeof documentInvitationSchema>\n\nexport function parseCreateInvitationContinuation(\n input: unknown\n): CreateInvitationContinuationInput {\n return v.parse(createInvitationContinuationSchema, input)\n}\n\nexport function parseLookupCloudUser(input: unknown): LookupCloudUserInput {\n return v.parse(lookupCloudUserSchema, input)\n}\n\nexport function parseCreateDocumentShare(input: unknown): CreateDocumentShareInput {\n return v.parse(createDocumentShareSchema, input)\n}\n\nexport function parseUpdateDocumentShare(input: unknown): UpdateDocumentShareInput {\n return v.parse(updateDocumentShareSchema, input)\n}\n\nexport function parseResolveDocumentShare(input: unknown): ResolveDocumentShareInput {\n return v.parse(resolveDocumentShareSchema, input)\n}\n\nexport function parsePutDocumentGrant(input: unknown): PutDocumentGrantInput {\n return v.parse(putDocumentGrantSchema, input)\n}\n\nexport function parseCreateDocumentInvitation(input: unknown): CreateDocumentInvitationInput {\n return v.parse(createDocumentInvitationSchema, input)\n}\n\nexport function parseAcceptDocumentInvitation(input: unknown): AcceptDocumentInvitationInput {\n return v.parse(acceptDocumentInvitationSchema, input)\n}\n","import { encodeParam, parseURL, withFragment, withQuery } from 'ufo'\n\n/** The two kinds of Cloud link that carry a secret: invitations and documents shared by link. */\nexport type CloudLinkKind = 'invitations' | 'share'\n\n/** Every kind of Cloud link: those that carry a secret, and a document's address for members. */\nexport type CloudLinkPathKind = CloudLinkKind | 'documents'\n\nconst CLOUD_LINK_PATH = /^\\/(invitations|share|documents)\\/([^/]+)$/\n\n/**\n * A link on the server's own editor. The server is the link's own address, so the link needs\n * nothing else to name it; a secret travels in the fragment, so it never reaches access logs or\n * `Referer` headers.\n */\nfunction serverLink(\n serverURL: string,\n path: string,\n query: Record<string, string | undefined> = {},\n secret?: string\n): string {\n const { protocol, host } = parseURL(serverURL)\n if (protocol !== 'https:' && protocol !== 'http:') {\n throw new Error('A Cloud server address must use HTTP or HTTPS')\n }\n const link = withQuery(`${protocol}//${host}${path}`, query)\n return secret ? withFragment(link, secret) : link\n}\n\n/** An invitation to a document or a workspace, `/invitations/:id#token`. */\nexport function cloudInvitationURL(serverURL: string, invitationId: string, token: string): string {\n return serverLink(serverURL, `/invitations/${encodeParam(invitationId)}`, {}, token)\n}\n\n/** A document shared by link, `/share/:id#secret`. */\nexport function cloudShareURL(serverURL: string, shareId: string, secret: string): string {\n return serverLink(serverURL, `/share/${encodeParam(shareId)}`, {}, secret)\n}\n\n/**\n * A document's address for its members, `/documents/:id`, or one of its versions with\n * `?version=…`. It carries no secret: whoever opens it signs in, and the server decides.\n */\nexport function cloudDocumentURL(\n serverURL: string,\n documentId: string,\n versionId: string | null = null\n): string {\n return serverLink(serverURL, cloudDocumentPath(documentId), {\n version: versionId ?? undefined\n })\n}\n\nexport function cloudDocumentPath(documentId: string): string {\n return `/documents/${encodeParam(documentId)}`\n}\n\n/**\n * The kind and ID of a Cloud link's path, or null for any other path. The ID is decoded; a broken\n * escape such as `%E0` is no link.\n */\nexport function parseCloudLinkPath(\n pathname: string\n): { kind: CloudLinkPathKind; id: string } | null {\n const [, kind, id] = pathname.match(CLOUD_LINK_PATH) ?? []\n if ((kind !== 'invitations' && kind !== 'share' && kind !== 'documents') || !id) return null\n try {\n return { kind, id: decodeURIComponent(id) }\n } catch {\n return null\n }\n}\n\n/**\n * The desktop app's form of a Cloud link, `openpencil://cloud?url=<link>#secret`: the web link,\n * whose address names the server, with its secret kept in the fragment.\n * `desktop/src/launch/links.rs` validates it before the editor sees it.\n */\nexport function cloudDesktopLinkURL(\n kind: CloudLinkKind,\n id: string,\n serverURL: string,\n secret: string\n): string {\n const link = serverLink(serverURL, `/${kind}/${encodeParam(id)}`)\n return withFragment(withQuery('openpencil://cloud', { url: link }), secret)\n}\n","/**\n * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for\n * visitors who are not signed in, sign-in and desktop sign-in approval, account settings, and the\n * administration console. Every runtime serves the portal's `cloud.html` at and below these\n * paths, and the editor's `index.html` at the root and at any other page the API does not answer.\n */\nexport const CLOUD_PORTAL_PAGE_ROOTS = ['/welcome', '/auth', '/account', '/admin'] as const\n\nexport function isCloudPortalPage(path: string): boolean {\n return CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`))\n}\n","import * as v from 'valibot'\n\nimport { documentDownloadSchema, documentSummarySchema } from './documents'\n\n/** How long a version's name may be; the history list shows the start of longer ones. */\nexport const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100\nexport const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1000\n\n/** A checkpoint the server kept on its own, or a version someone named. */\nexport const documentVersionKindSchema = v.picklist(['checkpoint', 'named'])\nexport type DocumentVersionKind = v.InferOutput<typeof documentVersionKindSchema>\n\nexport const documentVersionSchema = v.object({\n id: v.pipe(v.string(), v.uuid()),\n revisionId: v.pipe(v.string(), v.uuid()),\n kind: documentVersionKindSchema,\n name: v.nullable(v.string()),\n description: v.nullable(v.string()),\n createdAt: v.string(),\n /** Who made the version: the author of a checkpoint's save, or who named or restored it. */\n createdBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),\n /** The version this one restored, while that version is still in the history. */\n restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),\n /** Whether the document holds this version now. */\n current: v.boolean()\n})\nexport type DocumentVersion = v.InferOutput<typeof documentVersionSchema>\n\nexport const documentVersionsSchema = v.object({\n versions: v.array(documentVersionSchema),\n /** Pass as `before` for the next, older page; null on the last one. */\n nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))\n})\nexport type DocumentVersions = v.InferOutput<typeof documentVersionsSchema>\n\nconst versionNameSchema = v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.maxLength(DOCUMENT_VERSION_NAME_MAX_LENGTH)\n)\nconst versionDescriptionSchema = v.pipe(\n v.string(),\n v.trim(),\n v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH)\n)\n\n/** Names the document as it is now, like Save to version history. */\nexport const saveDocumentVersionSchema = v.object({\n name: versionNameSchema,\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type SaveDocumentVersionInput = v.InferOutput<typeof saveDocumentVersionSchema>\n\n/** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */\nexport const updateDocumentVersionSchema = v.object({\n name: v.nullable(versionNameSchema),\n description: v.optional(versionDescriptionSchema, '')\n})\nexport type UpdateDocumentVersionInput = v.InferOutput<typeof updateDocumentVersionSchema>\n\nexport const duplicateDocumentVersionSchema = v.object({\n name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))\n})\nexport type DuplicateDocumentVersionInput = v.InferOutput<typeof duplicateDocumentVersionSchema>\n\nexport const documentVersionResponseSchema = v.object({ version: documentVersionSchema })\n/** A version with where to download it, so a link to it can show it without the history. */\nexport const documentVersionDownloadSchema = v.object({\n document: documentDownloadSchema,\n version: documentVersionSchema\n})\nexport type DocumentVersionDownload = v.InferOutput<typeof documentVersionDownloadSchema>\nexport const restoredDocumentSchema = v.object({\n document: documentSummarySchema,\n version: documentVersionSchema\n})\n\nexport function parseSaveDocumentVersion(input: unknown): SaveDocumentVersionInput {\n return v.parse(saveDocumentVersionSchema, input)\n}\nexport function parseUpdateDocumentVersion(input: unknown): UpdateDocumentVersionInput {\n return v.parse(updateDocumentVersionSchema, input)\n}\nexport function parseDuplicateDocumentVersion(input: unknown): DuplicateDocumentVersionInput {\n return v.parse(duplicateDocumentVersionSchema, input)\n}\n","export type AdminErrorCode =\n | 'invalid_enrollment_transition'\n | 'last_admin_required'\n | 'self_admin_action_forbidden'\n | 'email_regeneration_unavailable'\n | 'mfa_required'\n\nexport class AdminDomainError extends Error {\n override readonly name = 'AdminDomainError'\n constructor(\n readonly code: AdminErrorCode,\n message: string\n ) {\n super(message)\n }\n}\n\nexport function adminErrorStatus(error: AdminDomainError): 400 | 409 {\n return error.code === 'invalid_enrollment_transition' ? 409 : 400\n}\n","import type { Context, Next } from 'hono'\n\nexport function requireTrustedMutationOrigin(trustedOrigins: ReadonlySet<string>) {\n return async (context: Context, next: Next) => {\n if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(context.req.method)) return next()\n const origin = context.req.header('origin')\n if (!origin || !trustedOrigins.has(origin)) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return next()\n }\n}\n","import * as v from 'valibot'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n/** Accounts and access requests are named by UUID; anything else names no row. */\nexport const isUUID = (value: string) => v.is(uuidSchema, value)\n\n/** The most rows one admin list request returns. */\nexport const ADMIN_LIST_MAXIMUM = 500\n\nexport const enrollmentStatusSchema = v.picklist(['pending', 'approved', 'rejected', 'revoked'])\nexport const enrollmentReviewSchema = v.object({\n note: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(1000)))\n})\nexport const userRoleMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n enabled: v.boolean()\n})\n\nexport const userMutationSchema = v.object({\n userId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n reason: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(500)))\n})\n\nexport type EnrollmentReview = v.InferOutput<typeof enrollmentReviewSchema>\n\nexport const parseEnrollmentReview = (input: unknown) => v.parse(enrollmentReviewSchema, input)\nexport const parseUserMutation = (input: unknown) => v.parse(userMutationSchema, input)\nexport const parseUserRoleMutation = (input: unknown) => v.parse(userRoleMutationSchema, input)\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {\n return {\n async cleanupExpired(before: Date): Promise<number> {\n const result = await database\n .deleteFrom('apiRateLimit')\n .where('windowStartedAt', '<', before)\n .executeTakeFirst()\n return Number(result.numDeletedRows)\n }\n }\n}\n\nexport type RateLimitCleanupService = ReturnType<typeof createRateLimitCleanupService>\n","import type { CloudActor } from '#cloud/server/auth'\nimport type { Context } from 'hono'\n\nexport type ClientIdentityOptions = {\n trustedHeaders: string[]\n}\n\n/**\n * The client address a trusted proxy reported. List-valued headers such as `X-Forwarded-For` carry\n * whatever the client sent followed by what each proxy appended, so only the right-most entry,\n * the one the trusted proxy wrote, identifies the client.\n */\nexport function trustedClientIP(context: Context, options: ClientIdentityOptions): string | null {\n for (const header of options.trustedHeaders) {\n const value = context.req\n .header(header)\n ?.split(',')\n .map((entry) => entry.trim())\n .findLast((entry) => entry.length > 0)\n if (value) return value\n }\n return null\n}\n\nexport const rateLimitKey = {\n email(email: string): string {\n return `email:${email.trim().toLowerCase()}`\n },\n ip(ip: string): string {\n return `ip:${ip}`\n },\n actor(actor: CloudActor): string {\n return `actor:${actor.userId}`\n },\n resource(resourceId: string, identity: string): string {\n return `resource:${resourceId}:${identity}`\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport type { ClientRateLimitInfo, Store } from 'hono-rate-limiter'\nimport type { Kysely } from 'kysely'\n\nexport class PostgresRateLimitStore implements Store {\n readonly localKeys = false\n readonly prefix: string\n private windowMs = 60_000\n\n constructor(\n private readonly database: Kysely<CloudDatabase>,\n private readonly secret: string,\n namespace: string,\n options: { windowMs?: number } = {}\n ) {\n this.prefix = `${namespace}:`\n this.windowMs = options.windowMs ?? this.windowMs\n }\n\n init(options: { windowMs: number }): void {\n this.windowMs = options.windowMs\n }\n\n private hash(key: string): string {\n return bytesToHex(sha256(utf8ToBytes(`${this.secret}:${this.prefix}:${key}`)))\n }\n\n async increment(key: string): Promise<ClientRateLimitInfo> {\n const now = new Date()\n const resetTime = new Date(\n Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs\n )\n const row = await this.database\n .insertInto('apiRateLimit')\n .values({\n keyHash: this.hash(key),\n windowStartedAt: new Date(resetTime.getTime() - this.windowMs),\n requestCount: 1,\n updatedAt: now\n })\n .onConflict((conflict) =>\n conflict.column('keyHash').doUpdateSet((expression) => ({\n requestCount: expression\n .case()\n .whenRef('apiRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')\n .then(expression('apiRateLimit.requestCount', '+', 1))\n .else(1)\n .end(),\n windowStartedAt: expression.ref('excluded.windowStartedAt'),\n updatedAt: expression.ref('excluded.updatedAt')\n }))\n )\n .returning(['requestCount', 'windowStartedAt'])\n .executeTakeFirstOrThrow()\n return {\n totalHits: Number(row.requestCount),\n resetTime: new Date(new Date(row.windowStartedAt).getTime() + this.windowMs)\n }\n }\n\n async decrement(key: string): Promise<void> {\n await this.database\n .updateTable('apiRateLimit')\n .set((expression) => ({\n requestCount: expression.fn('greatest', [\n expression('requestCount', '-', 1),\n expression.val(0)\n ])\n }))\n .where('keyHash', '=', this.hash(key))\n .execute()\n }\n\n async resetKey(key: string): Promise<void> {\n await this.database.deleteFrom('apiRateLimit').where('keyHash', '=', this.hash(key)).execute()\n }\n}\n","import type { CloudAPIEnvironment, RateLimitUse } from '#cloud/server/api/types'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Context, Env, Input, MiddlewareHandler } from 'hono'\nimport { rateLimiter, type RateLimitExceededEventHandler } from 'hono-rate-limiter'\nimport { every } from 'hono/combine'\nimport { matchedRoutes } from 'hono/route'\nimport type { Kysely } from 'kysely'\n\nimport { trustedClientIP, type ClientIdentityOptions } from './keys'\nimport { PostgresRateLimitStore } from './postgres'\n\nexport type RateLimitPolicy = {\n namespace: string\n windowMs: number\n limit: number\n}\n\n/**\n * A budget counted per resource, such as a document, with `actorLimit` capping one actor across\n * every resource, so new resources do not add budget without end.\n */\nexport type ResourceRateLimitPolicy = RateLimitPolicy & { actorLimit: number }\n\nexport const CLOUD_RATE_LIMITS = {\n publicCapability: { namespace: 'public-capability', windowMs: 60_000, limit: 30 },\n collaborationTicket: {\n namespace: 'collaboration-ticket',\n windowMs: 60_000,\n limit: 60,\n actorLimit: 300\n },\n invitationMutation: {\n namespace: 'invitation-mutation',\n windowMs: 60_000,\n limit: 30,\n actorLimit: 60\n },\n workspaceCreation: { namespace: 'workspace-creation', windowMs: 60_000, limit: 30 },\n documentCreation: {\n namespace: 'document-creation',\n windowMs: 60_000,\n limit: 60,\n actorLimit: 120\n },\n uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120, actorLimit: 600 },\n authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },\n aiToken: { namespace: 'ai-token', windowMs: 60_000, limit: 30 },\n adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },\n adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }\n} as const satisfies Record<string, RateLimitPolicy | ResourceRateLimitPolicy>\n\n/**\n * The limiters routes mount for their own budget, each with which requests it counts. A general\n * limiter leaves those requests to it rather than counting them twice; the routes themselves say\n * which have one, so the general limiter never matches paths.\n */\nconst routeBudgets = new WeakMap<object, (context: Context) => boolean>()\n\n/** Whether a limiter the request's route mounts for its own budget counts this request. */\nexport function routeHasOwnBudget(context: Context): boolean {\n return matchedRoutes(context).some((route) => routeBudgets.get(route.handler)?.(context))\n}\n\nfunction ownBudget<Limiter extends object>(\n limiter: Limiter,\n skip?: (context: Context) => boolean\n): Limiter {\n routeBudgets.set(limiter, (context) => !skip?.(context))\n return limiter\n}\n\ntype RateLimitOptions<E extends Env, P extends string, I extends Input> = {\n database: Kysely<CloudDatabase>\n secret: string\n policy: RateLimitPolicy\n keyGenerator(context: Context<E, P, I>): string\n handler?: RateLimitExceededEventHandler<E, P, I>\n skip?: (context: Context<E, P, I>) => boolean\n standardHeaders?: boolean | 'draft-6' | 'draft-7'\n}\n\nexport function createCloudRateLimiter<\n E extends Env = Env,\n P extends string = string,\n I extends Input = Input\n>(options: RateLimitOptions<E, P, I>) {\n return rateLimiter<E, P, I>({\n windowMs: options.policy.windowMs,\n limit: options.policy.limit,\n standardHeaders: options.standardHeaders ?? 'draft-7',\n store: new PostgresRateLimitStore(options.database, options.secret, options.policy.namespace),\n keyGenerator: (context) => options.keyGenerator(context),\n handler: options.handler\n ? (context, next, used) => options.handler?.(context, next, used)\n : undefined,\n skip: options.skip\n })\n}\n\nexport function createTrustedIPRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n client: ClientIdentityOptions,\n handler?: RateLimitExceededEventHandler,\n options?: {\n resource?: (context: Context) => string\n skip?: (context: Context) => boolean\n /** The limiter is a route's own budget, which general limiters leave to it. */\n route?: boolean\n }\n) {\n const limiter = createCloudRateLimiter({\n database,\n secret,\n policy,\n keyGenerator: (context) => {\n const ip = trustedClientIP(context, client) ?? 'unavailable'\n return options?.resource ? `resource:${options.resource(context)}:ip:${ip}` : `ip:${ip}`\n },\n skip: (context) =>\n trustedClientIP(context, client) === null || Boolean(options?.skip?.(context)),\n handler\n })\n return options?.route ? ownBudget(limiter, options.skip) : limiter\n}\n\nexport function createActorRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean,\n resource?: (context: Context<CloudAPIEnvironment, '*'>) => string\n) {\n return createCloudRateLimiter<CloudAPIEnvironment, '*'>({\n database,\n secret,\n policy,\n keyGenerator: (context) =>\n resource\n ? `resource:${resource(context)}:actor:${context.get('actor').userId}`\n : `actor:${context.get('actor').userId}`,\n skip\n })\n}\n\n/**\n * A limiter a route mounts for its own budget, such as workspace creation; general limiters leave\n * the requests it counts to it.\n */\nexport function createRouteRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: RateLimitPolicy,\n skip?: (context: Context) => boolean\n) {\n return ownBudget(createActorRateLimiter(database, secret, policy, skip), skip)\n}\n\n/**\n * A route's own budget counted per resource, such as uploads per document, and capped per actor\n * across resources by `actorLimit`; general limiters leave the requests it counts to it.\n */\nexport function createResourceRateLimiter(\n database: Kysely<CloudDatabase>,\n secret: string,\n policy: ResourceRateLimitPolicy,\n resource: (context: Context<CloudAPIEnvironment, '*'>) => string,\n skip?: (context: Context) => boolean\n) {\n const perResource = createActorRateLimiter(database, secret, policy, skip, resource)\n const perActor = createActorRateLimiter(\n database,\n secret,\n { namespace: `${policy.namespace}-actor`, windowMs: policy.windowMs, limit: policy.actorLimit },\n skip\n )\n return ownBudget(\n every(perResource, keepResourceUse, perActor, reportTighterBudget(policy.windowMs)),\n skip\n )\n}\n\n/** Keeps the resource budget's use, which the actor-wide limiter would record over. */\nconst keepResourceUse: MiddlewareHandler<CloudAPIEnvironment> = async (context, next) => {\n context.set('resourceRateLimit', context.get('rateLimit'))\n await next()\n}\n\n/**\n * Reports whichever budget has fewer requests left in the `RateLimit` headers, as both limiters\n * write them and the last would otherwise win. A refused request keeps the headers of the budget\n * that refused it.\n */\nfunction reportTighterBudget(windowMs: number): MiddlewareHandler<CloudAPIEnvironment> {\n return async (context, next) => {\n const resource = context.get('resourceRateLimit')\n const actor = context.get('rateLimit')\n const tighter = resource && actor && resource.remaining < actor.remaining ? resource : actor\n if (tighter) setBudgetHeaders(context, tighter, windowMs)\n await next()\n }\n}\n\n/** The draft-7 `RateLimit` headers `hono-rate-limiter` writes, for one budget's use. */\nfunction setBudgetHeaders(context: Context, use: RateLimitUse, windowMs: number): void {\n const windowSeconds = Math.ceil(windowMs / 1000)\n const reset = use.resetTime\n ? Math.max(0, Math.ceil((use.resetTime.getTime() - Date.now()) / 1000))\n : windowSeconds\n context.header('RateLimit-Policy', `${use.limit};w=${windowSeconds}`)\n context.header('RateLimit', `limit=${use.limit}, remaining=${use.remaining}, reset=${reset}`)\n}\n\n/**\n * A limiter's resource named by a route parameter, such as the document a request uploads to. It\n * runs before the route's param validator, and the value only names the limiter's counter, which\n * `rateLimitKey` hashes; it never reaches a query.\n */\nexport function routeParamResource(name: string) {\n return (context: Context): string =>\n // Lowercased as validation lowercases UUIDs, so one row's spellings share a budget.\n // eslint-disable-next-line open-pencil/no-unvalidated-route-params -- a counter name, hashed, never queried.\n context.req.param(name)?.toLowerCase() ?? 'unknown'\n}\n","import { requireTrustedMutationOrigin } from '#cloud/admin/api/security'\nimport type { AdminAuditService } from '#cloud/admin/audit/service'\nimport type { AdminEmailService } from '#cloud/admin/email/service'\nimport type { EnrollmentService } from '#cloud/admin/enrollment/service'\nimport { adminErrorStatus, AdminDomainError } from '#cloud/admin/errors'\nimport type { AdminOperationsService } from '#cloud/admin/operations/service'\nimport {\n enrollmentStatusSchema,\n parseEnrollmentReview,\n parseUserMutation,\n parseUserRoleMutation\n} from '#cloud/admin/schema'\nimport type { AdminUserService } from '#cloud/admin/users/service'\nimport {\n cloudAdminAuditFilterSchema,\n cloudAdminEmailFilterSchema,\n cloudAdminUserFilterSchema\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport type { CloudAuthAdapter } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'\nimport { idParams, validatedJSON, validatedQuery } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport { NoResultError, type Kysely } from 'kysely'\nimport * as v from 'valibot'\n\n/**\n * A count from the query string; anything but digits, or a number too large to be exact, is a bad\n * request rather than a NaN or out-of-range query.\n */\nconst countSchema = v.optional(v.pipe(v.string(), v.digits(), v.toNumber(), v.safeInteger()))\n/** What an admin list reads from its query string: a search, one of `filters`, and a page. */\nfunction listQuery<const Filter extends string>(filters: v.PicklistSchema<Filter[], undefined>) {\n const schema = v.object({\n search: v.optional(v.string()),\n filter: v.optional(filters),\n limit: countSchema,\n offset: countSchema\n })\n return (input: unknown) => v.parse(schema, input)\n}\nconst parseEnrollmentQuery = listQuery(enrollmentStatusSchema)\nconst parseUserQuery = listQuery(cloudAdminUserFilterSchema)\nconst parseEmailQuery = listQuery(cloudAdminEmailFilterSchema)\nconst parseAuditQuery = listQuery(cloudAdminAuditFilterSchema)\n/** Accounts are named by UUID; anything else names no one, rather than failing the query. */\nconst accountIdSchema = v.pipe(v.string(), v.uuid())\n\n/** Does what an administrator asked to another account; one that is not an account is not found. */\nasync function accountMutation(\n context: Context<CloudAPIEnvironment>,\n userId: string,\n mutate: (actorId: string, userId: string) => Promise<void>\n) {\n if (!v.is(accountIdSchema, userId)) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n await mutate(context.get('actor').userId, userId)\n return context.json({ ok: true as const })\n}\n\nexport type CloudAdminServices = {\n email: AdminEmailService\n enrollment: EnrollmentService\n users: AdminUserService\n audit: AdminAuditService\n operations: AdminOperationsService\n}\n\nexport function createCloudAdminRoutes(\n services: CloudAdminServices,\n trustedOrigins: ReadonlySet<string>,\n security: {\n auth: CloudAuthAdapter\n database: Kysely<CloudDatabase>\n requireMFA: boolean\n secret: string\n }\n) {\n const adminRead = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminRead,\n (context) => context.req.method !== 'GET'\n )\n const adminMutation = createActorRateLimiter(\n security.database,\n security.secret,\n CLOUD_RATE_LIMITS.adminMutation,\n (context) => context.req.method === 'GET'\n )\n return new Hono<CloudAPIEnvironment>()\n .use('*', requireTrustedMutationOrigin(trustedOrigins))\n .use('*', async (context, next) => {\n const actor = context.get('actor')\n if (actor.deploymentRole !== 'admin') {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (security.requireMFA) {\n const status = await security.auth.mfaStatus(context.req.raw.headers)\n if (!status?.assured) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n return next()\n })\n .use('*', adminRead)\n .use('*', adminMutation)\n .onError((error, context) => {\n if (error instanceof AdminDomainError) {\n return context.json({ error: { code: error.code } }, adminErrorStatus(error))\n }\n if (error instanceof v.ValiError) {\n return context.json({ error: { code: 'invalid_request' as const } }, 400)\n }\n // An enrollment or message ID that names nothing.\n if (error instanceof NoResultError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n throw error\n })\n .get('/enrollments', validatedQuery(parseEnrollmentQuery), async (context) =>\n context.json(await services.enrollment.list(context.req.valid('query')))\n )\n .post(\n '/enrollments/:id/approve',\n idParams,\n validatedJSON(parseEnrollmentReview),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'approved',\n context.req.valid('json')\n )\n })\n )\n .post(\n '/enrollments/:id/reject',\n idParams,\n validatedJSON(parseEnrollmentReview),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'rejected',\n context.req.valid('json')\n )\n })\n )\n .post(\n '/enrollments/:id/revoke',\n idParams,\n validatedJSON(parseEnrollmentReview),\n async (context) =>\n context.json({\n enrollment: await services.enrollment.review(\n context.get('actor').userId,\n context.req.valid('param').id,\n 'revoked',\n context.req.valid('json')\n )\n })\n )\n .get('/users', validatedQuery(parseUserQuery), async (context) =>\n context.json(await services.users.list(context.req.valid('query')))\n )\n .get('/users/:id', idParams, async (context) => {\n const detail = await services.users.detail(context.req.valid('param').id)\n if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json(detail)\n })\n .post('/users/reset-two-step', validatedJSON(parseUserMutation), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.resetTwoStep(actorId, userId)\n )\n )\n .post('/users/remove-picture', validatedJSON(parseUserMutation), (context) =>\n accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>\n services.users.removePicture(actorId, userId)\n )\n )\n .post('/users/ban', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.ban(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.reason\n )\n return context.json({ ok: true as const })\n })\n .post('/users/unban', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.unban(context.req.raw.headers, context.get('actor').userId, input.userId)\n return context.json({ ok: true as const })\n })\n .post('/users/revoke-sessions', validatedJSON(parseUserMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.revokeSessions(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId\n )\n return context.json({ ok: true as const })\n })\n .post('/users/set-admin', validatedJSON(parseUserRoleMutation), async (context) => {\n const input = context.req.valid('json')\n await services.users.setAdmin(\n context.req.raw.headers,\n context.get('actor').userId,\n input.userId,\n input.enabled\n )\n return context.json({ ok: true as const })\n })\n .get('/email', validatedQuery(parseEmailQuery), async (context) =>\n context.json(await services.email.list(context.req.valid('query')))\n )\n .post('/email/:id/regenerate', idParams, async (context) => {\n await services.email.regenerate(context.get('actor').userId, context.req.valid('param').id)\n return context.json({ ok: true as const })\n })\n .get('/audit', validatedQuery(parseAuditQuery), async (context) =>\n context.json(await services.audit.list(context.req.valid('query')))\n )\n .get('/operations', async (context) => context.json(await services.operations.summary()))\n}\n\n/** The administration routes' types, for the portal's typed client. */\nexport type CloudAdminRoutes = ReturnType<typeof createCloudAdminRoutes>\n","import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { clamp, zipObject } from 'es-toolkit'\nimport type { Expression, ExpressionBuilder, SelectQueryBuilder, SqlBool } from 'kysely'\n\n/** The rows an admin list returns when the request does not say. */\nexport const ADMIN_PAGE_SIZE = 50\n\n/** What every admin list takes: words to search for, one of its filters, and a page. */\nexport type AdminListQuery<Filter extends string> = {\n search?: string\n filter?: Filter\n limit?: number\n offset?: number\n}\n\n/** A `like` pattern that finds `search` anywhere, matching `%`, `_`, and `\\` literally. */\nexport function containsPattern(search: string): string {\n return `%${search.replace(/[\\\\%_]/g, (character) => `\\\\${character}`)}%`\n}\n\n/** The search words, or undefined when there are none. */\nexport function listSearch(query: AdminListQuery<string>): string | undefined {\n return query.search?.trim() || undefined\n}\n\n/** The page a query asks for, kept within what one request may return. */\nexport function listWindow(query: AdminListQuery<string>) {\n return {\n limit: clamp(query.limit ?? ADMIN_PAGE_SIZE, 1, ADMIN_LIST_MAXIMUM),\n offset: Math.max(0, query.offset ?? 0)\n }\n}\n\n/** A list's filters, each the condition its rows meet; the same one counts them and pages them. */\nexport type ListFilters<Filter extends string, Table extends keyof CloudDatabase> = Record<\n Filter,\n (expression: ExpressionBuilder<CloudDatabase, Table>) => Expression<SqlBool>\n>\n\n/**\n * How many of `searched`'s rows meet each filter, in one query: each count is an aggregate with a\n * `filter (where …)` clause rather than a query of its own.\n */\nexport async function countEachFilter<Filter extends string, Table extends keyof CloudDatabase>(\n searched: SelectQueryBuilder<CloudDatabase, Table, object>,\n names: readonly Filter[],\n filters: ListFilters<Filter, Table>\n): Promise<Record<Filter, number>> {\n // Kysely names each column after its filter but cannot type a generic name, so the row is read\n // as counts by name.\n const row: Record<string, unknown> = await searched\n .select((expression) =>\n names.map((name) => expression.fn.countAll<number>().filterWhere(filters[name]).as(name))\n )\n .executeTakeFirstOrThrow()\n return zipObject(\n names,\n names.map((name) => Number(row[name]))\n )\n}\n","import {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { cloudAdminAuditFilterSchema, type CloudAdminAuditFilter } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { uniq } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\n/** Events by what they are about; every event is under `all`. */\nconst FILTERS: ListFilters<CloudAdminAuditFilter, 'adminAuditEvent'> = {\n all: (expression) => expression.lit(true),\n accounts: (expression) => expression('adminAuditEvent.subjectType', '=', 'user'),\n requests: (expression) => expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n email: (expression) => expression('adminAuditEvent.subjectType', '=', 'transactional-email')\n}\n\ntype AuditExpression = ExpressionBuilder<CloudDatabase, 'adminAuditEvent'>\n\n/** Events whose actor, or the account or request they are about, has `pattern` in a name or email. */\nfunction searchCondition(pattern: string) {\n return (expression: AuditExpression) => {\n const account = (column: 'adminAuditEvent.actorUserId' | 'adminAuditEvent.subjectId') =>\n expression.exists(\n expression\n .selectFrom('user')\n .select('user.id')\n .where((inner) => inner(inner.cast('user.id', 'text'), '=', inner.ref(column)))\n .where((inner) =>\n inner.or([inner('user.name', 'ilike', pattern), inner('user.email', 'ilike', pattern)])\n )\n )\n return expression.or([\n account('adminAuditEvent.actorUserId'),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'user'),\n account('adminAuditEvent.subjectId')\n ]),\n expression.and([\n expression('adminAuditEvent.subjectType', '=', 'enrollment'),\n expression.exists(\n expression\n .selectFrom('enrollment')\n .select('enrollment.id')\n .where((inner) =>\n inner(\n inner.cast('enrollment.id', 'text'),\n '=',\n inner.ref('adminAuditEvent.subjectId')\n )\n )\n .where((inner) =>\n inner.or([\n inner('enrollment.name', 'ilike', pattern),\n inner('enrollment.emailNormalized', 'ilike', pattern)\n ])\n )\n )\n ])\n ])\n }\n}\n\nexport function createAdminAuditService(database: Kysely<CloudDatabase>) {\n return {\n /**\n * A page of events, newest first, each with its actor's and subject's names while the server\n * knows them, and how many match the search under each filter.\n */\n async list(query: AdminListQuery<CloudAdminAuditFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('adminAuditEvent')\n if (search) searched = searched.where(searchCondition(containsPattern(search)))\n const counts = await countEachFilter(searched, cloudAdminAuditFilterSchema.options, FILTERS)\n const events = await searched\n .where(FILTERS[filter])\n .selectAll()\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Accounts and requests are named by UUID; anything else is not looked up.\n const userIds = uniq(\n events.flatMap((event) =>\n event.subjectType === 'user' ? [event.actorUserId, event.subjectId] : [event.actorUserId]\n )\n ).filter(isUUID)\n const enrollmentIds = uniq(\n events.flatMap((event) => (event.subjectType === 'enrollment' ? [event.subjectId] : []))\n ).filter(isUUID)\n const [users, enrollments] = await Promise.all([\n userIds.length\n ? database.selectFrom('user').select(['id', 'name']).where('id', 'in', userIds).execute()\n : [],\n enrollmentIds.length\n ? database\n .selectFrom('enrollment')\n .select(['id', 'name', 'emailNormalized'])\n .where('id', 'in', enrollmentIds)\n .execute()\n : []\n ])\n const names = new Map(users.map((user) => [user.id, user.name]))\n const requesters = new Map(\n enrollments.map((enrollment) => [\n enrollment.id,\n enrollment.name ?? enrollment.emailNormalized\n ])\n )\n const rows = events.map((event) => ({\n id: event.id,\n actor: { id: event.actorUserId, name: names.get(event.actorUserId) ?? null },\n action: event.action,\n subject: {\n type: event.subjectType,\n id: event.subjectId,\n name:\n (event.subjectType === 'enrollment'\n ? requesters.get(event.subjectId)\n : names.get(event.subjectId)) ?? null\n },\n metadata: event.metadata,\n createdAt: event.createdAt\n }))\n return { events: rows, total: counts[filter], counts }\n }\n }\n}\n\nexport type AdminAuditService = ReturnType<typeof createAdminAuditService>\n","import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'\nimport { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { cloudAdminEmailFilterSchema, type CloudAdminEmailFilter } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\n/** The enrollment status each message describes; a message is resent only while it still holds. */\nconst ENROLLMENT_MESSAGE_STATUS: Partial<Record<string, EnrollmentStatus>> = {\n 'enrollment-requested': 'pending',\n 'enrollment-approved': 'approved',\n 'enrollment-rejected': 'rejected',\n 'enrollment-revoked': 'revoked'\n}\n\n/** Messages by how their delivery went; every message is under `all`. */\nconst FILTERS: ListFilters<CloudAdminEmailFilter, 'transactionalEmail'> = {\n all: (expression) => expression.lit(true),\n sent: (expression) => expression('status', '=', 'accepted'),\n waiting: (expression) => expression('status', 'in', ['pending', 'sending']),\n failed: (expression) => expression('status', '=', 'failed')\n}\n\nexport function createAdminEmailService(\n database: Kysely<CloudDatabase>,\n email?: TransactionalEmailService,\n links: { publicURL: string } = { publicURL: '' }\n) {\n return {\n /** A page of messages, newest first, with how many match the search under each filter. */\n async list(query: AdminListQuery<CloudAdminEmailFilter> = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('transactionalEmail')\n if (search) {\n searched = searched.where('recipientEmailNormalized', 'ilike', containsPattern(search))\n }\n const counts = await countEachFilter(searched, cloudAdminEmailFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select([\n 'id',\n 'kind',\n 'recipientEmailNormalized',\n 'status',\n 'attemptCount',\n 'nextAttemptAt',\n 'transport',\n 'transportMessageId',\n 'lastErrorCode',\n 'createdAt',\n 'acceptedAt'\n ])\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n return {\n messages: rows.map((row) => ({\n ...row,\n regeneratable: row.kind.startsWith('enrollment-')\n })),\n total: counts[filter],\n counts\n }\n },\n async regenerate(actorId: string, messageId: string): Promise<void> {\n if (!email)\n throw new AdminDomainError('email_regeneration_unavailable', 'Email delivery is disabled')\n await database.transaction().execute(async (transaction) => {\n const original = await transaction\n .selectFrom('transactionalEmail')\n .select(['id', 'kind', 'recipientEmailNormalized'])\n .where('id', '=', messageId)\n .executeTakeFirstOrThrow()\n if (\n !original.kind.startsWith('enrollment-') ||\n original.kind === 'admin-enrollment-notification'\n ) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'This message cannot be regenerated'\n )\n }\n const kind = original.kind\n const enrollment = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', original.recipientEmailNormalized)\n .executeTakeFirst()\n if (!enrollment)\n throw new AdminDomainError('email_regeneration_unavailable', 'Enrollment is unavailable')\n if (ENROLLMENT_MESSAGE_STATUS[kind] !== enrollment.status) {\n throw new AdminDomainError(\n 'email_regeneration_unavailable',\n 'The enrollment no longer matches this message'\n )\n }\n await email.enqueue(\n {\n idempotencyKey: `admin-regeneration/${messageId}/${crypto.randomUUID()}`,\n kind,\n recipientEmail: enrollment.emailNormalized,\n payload: {\n name: enrollment.name ?? 'there',\n actionURL:\n kind === 'enrollment-approved'\n ? links.publicURL\n : new URL('/auth/sign-in', links.publicURL).href\n }\n },\n transaction\n )\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'email.regenerated',\n subjectType: 'transactional-email',\n subjectId: messageId,\n metadata: { replacementKind: kind }\n })\n .execute()\n })\n }\n }\n}\n\nexport type AdminEmailService = ReturnType<typeof createAdminEmailService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Transaction } from 'kysely'\n\nimport type { EnrollmentStatus } from './service'\n\nexport type EnrollmentEmailOptions = {\n /**\n * The server's address: its editor, where an approved account goes next, and its own pages,\n * where people sign in and administrators review requests.\n */\n publicURL: string\n adminRecipients: string[]\n email?: TransactionalEmailService\n}\n\nexport async function enqueueEnrollmentRequested(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: { enrollmentId: string; email: string; name: string; reason: string; revision: number }\n): Promise<void> {\n if (!options.email) return\n await options.email.enqueue(\n {\n idempotencyKey: `enrollment-requested/${input.enrollmentId}/${input.revision}`,\n kind: 'enrollment-requested',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', options.publicURL).href }\n },\n transaction\n )\n for (const recipientEmail of options.adminRecipients) {\n await options.email.enqueue(\n {\n idempotencyKey: `admin-enrollment-notification/${input.enrollmentId}/${input.revision}/${recipientEmail}`,\n kind: 'admin-enrollment-notification',\n recipientEmail,\n payload: {\n requesterEmail: input.email,\n requesterName: input.name,\n reason: input.reason,\n actionURL: new URL('/admin/requests', options.publicURL).href\n }\n },\n transaction\n )\n }\n}\n\nexport async function enqueueEnrollmentReview(\n transaction: Transaction<CloudDatabase>,\n options: EnrollmentEmailOptions,\n input: {\n enrollmentId: string\n recipientEmail: string\n name: string\n status: Exclude<EnrollmentStatus, 'pending'>\n reviewedAt: Date\n }\n): Promise<void> {\n if (!options.email) return\n await options.email.enqueue(\n {\n idempotencyKey: `enrollment-${input.status}/${input.enrollmentId}/${input.reviewedAt.toISOString()}`,\n kind: `enrollment-${input.status}`,\n recipientEmail: input.recipientEmail,\n payload: {\n name: input.name,\n actionURL:\n input.status === 'approved'\n ? options.publicURL\n : new URL('/auth/sign-in', options.publicURL).href\n }\n },\n transaction\n )\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport { isUUID } from '#cloud/admin/schema'\nimport { enrollmentStatusSchema } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { compact, uniq } from 'es-toolkit'\nimport type { Kysely } from 'kysely'\n\nimport {\n enqueueEnrollmentRequested,\n enqueueEnrollmentReview,\n type EnrollmentEmailOptions\n} from './email'\n\nexport type EnrollmentStatus = 'pending' | 'approved' | 'rejected' | 'revoked'\nexport type EnrollmentMode = 'open' | 'approval' | 'closed'\n\nexport type EnrollmentRequestInput = { email: string; name?: string; reason?: string }\nexport type EnrollmentReviewInput = { note?: string }\nexport type EnrollmentRecord = {\n id: string\n email: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: string\n reviewedAt: string | null\n reviewedBy: string | null\n reviewerName?: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\ntype EnrollmentRow = {\n id: string\n emailNormalized: string\n name: string | null\n reason: string | null\n status: EnrollmentStatus\n requestedAt: Date | string\n reviewedAt: Date | string | null\n reviewedBy: string | null\n reviewNote: string | null\n approvedUserId: string | null\n requestRevision: number\n}\n\nconst ALLOWED_TRANSITIONS: Record<EnrollmentStatus, ReadonlySet<EnrollmentStatus>> = {\n pending: new Set(['approved', 'rejected']),\n approved: new Set(['revoked']),\n rejected: new Set(['pending', 'approved']),\n revoked: new Set(['pending', 'approved'])\n}\n\n/** Requests by their status; each is in exactly one. */\nconst FILTERS: ListFilters<EnrollmentStatus, 'enrollment'> = {\n pending: (expression) => expression('status', '=', 'pending'),\n approved: (expression) => expression('status', '=', 'approved'),\n rejected: (expression) => expression('status', '=', 'rejected'),\n revoked: (expression) => expression('status', '=', 'revoked')\n}\n\nfunction dateString(value: Date | string | null): string | null {\n return value ? new Date(value).toISOString() : null\n}\nfunction enrollmentRecord(row: EnrollmentRow): EnrollmentRecord {\n return {\n id: row.id,\n email: row.emailNormalized,\n name: row.name,\n reason: row.reason,\n status: row.status,\n requestedAt: dateString(row.requestedAt) ?? '',\n reviewedAt: dateString(row.reviewedAt),\n reviewedBy: row.reviewedBy,\n reviewNote: row.reviewNote,\n approvedUserId: row.approvedUserId,\n requestRevision: row.requestRevision\n }\n}\nexport function normalizeEnrollmentEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nexport function createEnrollmentService(\n database: Kysely<CloudDatabase>,\n emailOptions: EnrollmentEmailOptions = { publicURL: '', adminRecipients: [] }\n) {\n const statusForEmail = async (email: string): Promise<EnrollmentStatus | null> => {\n const row = await database\n .selectFrom('enrollment')\n .select('status')\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .executeTakeFirst()\n return row?.status ?? null\n }\n return {\n async request(input: EnrollmentRequestInput): Promise<void> {\n const emailNormalized = normalizeEnrollmentEmail(input.email)\n await database.transaction().execute(async (transaction) => {\n const existing = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('emailNormalized', '=', emailNormalized)\n .forUpdate()\n .executeTakeFirst()\n if (existing?.status === 'approved' || existing?.status === 'pending') return\n const revision = (existing?.requestRevision ?? 0) + 1\n const values = {\n name: input.name?.trim() || existing?.name || null,\n reason: input.reason?.trim() || null,\n status: 'pending' as const,\n reviewedAt: null,\n reviewedBy: null,\n reviewNote: null,\n requestRevision: revision\n }\n let row: EnrollmentRow\n if (existing) {\n row = await transaction\n .updateTable('enrollment')\n .set(values)\n .where('id', '=', existing.id)\n .returningAll()\n .executeTakeFirstOrThrow()\n } else {\n row = await transaction\n .insertInto('enrollment')\n .values({\n id: crypto.randomUUID(),\n emailNormalized,\n ...values,\n approvedUserId: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n }\n await enqueueEnrollmentRequested(transaction, emailOptions, {\n enrollmentId: row.id,\n email: row.emailNormalized,\n name: row.name ?? 'there',\n reason: row.reason ?? 'No reason provided.',\n revision\n })\n })\n },\n statusForEmail,\n async isApproved(email: string): Promise<boolean> {\n return (await statusForEmail(email)) === 'approved'\n },\n /** A page of requests in one status, newest first, with how many match the search in each. */\n async list(query: AdminListQuery<EnrollmentStatus> = {}) {\n const search = listSearch(query)\n const status = query.filter ?? 'pending'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('enrollment')\n if (search) {\n const pattern = containsPattern(search)\n searched = searched.where((expression) =>\n expression.or([\n expression('name', 'ilike', pattern),\n expression('emailNormalized', 'ilike', pattern)\n ])\n )\n }\n const counts = await countEachFilter(searched, enrollmentStatusSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[status])\n .selectAll()\n .orderBy('requestedAt', 'desc')\n .orderBy('id', 'desc')\n .limit(limit)\n .offset(offset)\n .execute()\n // Reviewers are named by account ID; anything else names no one.\n const reviewerIds = uniq(compact(rows.map((row) => row.reviewedBy))).filter(isUUID)\n const reviewers = reviewerIds.length\n ? await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', reviewerIds)\n .execute()\n : []\n const names = new Map(reviewers.map((reviewer) => [reviewer.id, reviewer.name]))\n const enrollments = rows.map((row) => ({\n ...enrollmentRecord(row),\n reviewerName: row.reviewedBy ? (names.get(row.reviewedBy) ?? null) : null\n }))\n return { enrollments, total: counts[status], counts }\n },\n async review(\n actorId: string,\n enrollmentId: string,\n status: Exclude<EnrollmentStatus, 'pending'>,\n input: EnrollmentReviewInput\n ): Promise<EnrollmentRecord> {\n return database.transaction().execute(async (transaction) => {\n const current = await transaction\n .selectFrom('enrollment')\n .selectAll()\n .where('id', '=', enrollmentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (!ALLOWED_TRANSITIONS[current.status].has(status)) {\n throw new AdminDomainError(\n 'invalid_enrollment_transition',\n `Enrollment cannot transition from ${current.status} to ${status}`\n )\n }\n const now = new Date()\n const approvedUser =\n status === 'approved'\n ? await transaction\n .selectFrom('user')\n .select('id')\n .where('email', '=', current.emailNormalized)\n .executeTakeFirst()\n : undefined\n const row = await transaction\n .updateTable('enrollment')\n .set({\n status,\n reviewedAt: now,\n reviewedBy: actorId,\n reviewNote: input.note?.trim() || null,\n approvedUserId: approvedUser?.id ?? current.approvedUserId\n })\n .where('id', '=', enrollmentId)\n .where('status', '=', current.status)\n .returningAll()\n .executeTakeFirstOrThrow()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: `enrollment.${status}`,\n subjectType: 'enrollment',\n subjectId: enrollmentId,\n metadata: { email: row.emailNormalized },\n createdAt: now\n })\n .execute()\n await enqueueEnrollmentReview(transaction, emailOptions, {\n enrollmentId,\n recipientEmail: row.emailNormalized,\n name: row.name ?? 'there',\n status,\n reviewedAt: now\n })\n return enrollmentRecord(row)\n })\n },\n async bindApprovedUser(email: string, userId: string): Promise<void> {\n await database\n .updateTable('enrollment')\n .set({ approvedUserId: userId })\n .where('emailNormalized', '=', normalizeEnrollmentEmail(email))\n .where('status', '=', 'approved')\n .execute()\n },\n /**\n * Moves an approved account's enrollment to the address it changed to, so the approval stays\n * with the account rather than with an address it no longer uses. Any other request from the\n * new address gives way to it.\n */\n async followEmailChange(userId: string, email: string): Promise<void> {\n const emailNormalized = normalizeEnrollmentEmail(email)\n await database.transaction().execute(async (transaction) => {\n const approved = await transaction\n .selectFrom('enrollment')\n .select(['id', 'emailNormalized'])\n .where('approvedUserId', '=', userId)\n .where('status', '=', 'approved')\n .forUpdate()\n .executeTakeFirst()\n if (!approved || approved.emailNormalized === emailNormalized) return\n await transaction\n .deleteFrom('enrollment')\n .where('emailNormalized', '=', emailNormalized)\n .where('id', '!=', approved.id)\n .execute()\n await transaction\n .updateTable('enrollment')\n .set({ emailNormalized })\n .where('id', '=', approved.id)\n .execute()\n })\n },\n async pendingCount(): Promise<number> {\n const row = await database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n }\n}\nexport type EnrollmentService = ReturnType<typeof createEnrollmentService>\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nexport function createAdminOperationsService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n async function emailCount(status: 'pending' | 'failed'): Promise<number> {\n const row = await database\n .selectFrom('transactionalEmail')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', status)\n .executeTakeFirstOrThrow()\n return Number(row.count)\n }\n\n return {\n async summary() {\n const [\n pendingEnrollment,\n pendingEmail,\n failedEmail,\n accounts,\n workspaces,\n documents,\n stored\n ] = await Promise.all([\n database\n .selectFrom('enrollment')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('status', '=', 'pending')\n .executeTakeFirstOrThrow(),\n emailCount('pending'),\n emailCount('failed'),\n database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspace')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('document')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('deletedAt', 'is', null)\n .executeTakeFirstOrThrow(),\n database\n .selectFrom('workspaceStorageUsage')\n .select(({ fn }) => fn.sum<number | null>('committedBytes').as('bytes'))\n .executeTakeFirstOrThrow()\n ])\n return {\n deployment: config.deployment,\n enrollmentMode: config.enrollmentMode,\n emailTransport: config.emailTransport,\n pendingEnrollment: Number(pendingEnrollment.count),\n pendingEmail,\n failedEmail,\n accounts: Number(accounts.count),\n workspaces: Number(workspaces.count),\n documents: Number(documents.count),\n storedBytes: Number(stored.bytes ?? 0)\n }\n }\n }\n}\n\nexport type AdminOperationsService = ReturnType<typeof createAdminOperationsService>\n","export const CLOUD_FEATURE_KEYS = {\n links: 'cloud.sharing.links',\n guestView: 'cloud.sharing.guest-view',\n guestEdit: 'cloud.sharing.guest-edit',\n guestPresence: 'cloud.sharing.guest-presence',\n collaboration: 'cloud.collaboration.enabled',\n serverEnforcedWrites: 'cloud.collaboration.server-enforced-writes',\n revisionHistory: 'cloud.documents.revision-history',\n maximumFileBytes: 'cloud.documents.maximum-file-bytes',\n maximumStorageBytes: 'cloud.storage.maximum-bytes',\n maximumParticipants: 'cloud.collaboration.maximum-participants',\n cloudAI: 'cloud.ai.enabled',\n monthlyCreditAllowance: 'cloud.ai.monthly-credit-allowance'\n} as const\n\nexport type CloudPolicyContext = {\n targetingKey: string\n actorId?: string\n workspaceId?: string\n organizationId?: string\n documentId?: string\n deploymentMode: 'official' | 'self-hosted'\n}\n","import { pickBy } from 'es-toolkit/object'\nimport { isNotNil } from 'es-toolkit/predicate'\nimport * as v from 'valibot'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport {\n staticEntitlementsSchema,\n staticEntitlementsTOMLSchema,\n type StaticEntitlements\n} from './schema'\n\n/** Entitlements as a writer sends them, with any group left out. */\nexport type StaticEntitlementsInput = v.InferInput<typeof staticEntitlementsSchema>\n\n/** Entitlements as the deployment TOML spells them, renamed to their structured form. */\nexport function staticEntitlementsFromTOML(\n value: v.InferOutput<typeof staticEntitlementsTOMLSchema>\n): StaticEntitlements {\n return v.parse(staticEntitlementsSchema, {\n documents: {\n maximumFileBytes: value.documents?.maximum_file_bytes,\n revisionHistory: value.documents?.revision_history\n },\n storage: { maximumBytes: value.storage?.maximum_bytes },\n sharing: {\n links: value.sharing?.links,\n guestView: value.sharing?.guest_view,\n guestEdit: value.sharing?.guest_edit,\n guestPresence: value.sharing?.guest_presence\n },\n collaboration: {\n enabled: value.collaboration?.enabled,\n maximumParticipants: value.collaboration?.maximum_participants\n },\n ai: {\n enabled: value.ai?.enabled,\n monthlyCreditAllowance: value.ai?.monthly_credit_allowance\n }\n })\n}\n\nexport function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {\n return staticEntitlementsFromTOML(v.parse(staticEntitlementsTOMLSchema, input))\n}\n\nexport function staticEntitlementValues(input: unknown): Record<string, boolean | number> {\n const entitlements = v.parse(staticEntitlementsSchema, input)\n const values: Record<string, boolean | number | undefined> = {\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: entitlements.documents.maximumFileBytes,\n [CLOUD_FEATURE_KEYS.revisionHistory]: entitlements.documents.revisionHistory,\n [CLOUD_FEATURE_KEYS.maximumStorageBytes]: entitlements.storage.maximumBytes,\n [CLOUD_FEATURE_KEYS.links]: entitlements.sharing.links,\n [CLOUD_FEATURE_KEYS.guestView]: entitlements.sharing.guestView,\n [CLOUD_FEATURE_KEYS.guestEdit]: entitlements.sharing.guestEdit,\n [CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,\n [CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,\n [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,\n [CLOUD_FEATURE_KEYS.cloudAI]: entitlements.ai.enabled,\n [CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.ai.monthlyCreditAllowance\n }\n return pickBy(values, isNotNil) as Record<string, boolean | number>\n}\n","import { staticEntitlementsFromTOML } from '#cloud/server/policy/static'\nimport { parse as parseTOML } from 'smol-toml'\nimport * as v from 'valibot'\n\nimport {\n cloudDeploymentConfigSchema,\n parseCloudServerConfig,\n type CloudDeploymentConfig,\n type CloudSecretReference,\n type CloudServerConfig\n} from './schema'\n\nexport type CloudEnvironment = Readonly<Record<string, string | undefined>>\n\nexport function parseCloudDeploymentSource(source: string): CloudDeploymentConfig {\n return v.parse(cloudDeploymentConfigSchema, parseTOML(source))\n}\n\nfunction requiredSecret(environment: CloudEnvironment, reference: CloudSecretReference): string {\n const value = environment[reference.from_env]\n if (!value) throw new Error(`Required secret binding is unavailable: ${reference.from_env}`)\n return value\n}\n\nfunction configuredText(\n environment: CloudEnvironment,\n value: string | CloudSecretReference\n): string {\n return typeof value === 'string' ? value : requiredSecret(environment, value)\n}\n\nfunction optionalSecret(\n environment: CloudEnvironment,\n reference?: CloudSecretReference\n): string | undefined {\n return reference ? environment[reference.from_env] : undefined\n}\n\nfunction staticEntitlements(config: CloudDeploymentConfig) {\n if (config.entitlements?.source !== 'static') return undefined\n return staticEntitlementsFromTOML(config.entitlements)\n}\n\nfunction emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n if (config.email.transport === 'none') return { emailTransport: 'none' as const }\n if (config.email.transport === 'cloudflare') {\n return { emailTransport: 'cloudflare' as const, emailFrom: config.email.from }\n }\n return {\n emailTransport: 'smtp' as const,\n emailFrom: config.email.from,\n smtpHost: config.email.smtp.host,\n smtpPort: config.email.smtp.port,\n smtpSecure: config.email.smtp.secure,\n smtpUser: optionalSecret(environment, config.email.smtp.user),\n smtpPassword: optionalSecret(environment, config.email.smtp.password)\n }\n}\n\nfunction authenticationConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n const google = config.authentication.providers.google\n const apple = config.authentication.providers.apple\n return {\n googleClientId: google ? configuredText(environment, google.client_id) : undefined,\n googleClientSecret: google ? requiredSecret(environment, google.client_secret) : undefined,\n appleClientId: apple?.client_id,\n appleTeamId: apple?.team_id,\n appleKeyId: apple?.key_id,\n applePrivateKey: apple ? requiredSecret(environment, apple.private_key) : undefined,\n appleAppBundleIdentifier: apple?.app_bundle_identifier\n }\n}\n\nfunction workerConfig(config: CloudDeploymentConfig) {\n const email = config.workers?.email\n const cleanup = config.workers?.cleanup\n return {\n emailBatchSize: email?.batch_size,\n emailIntervalMs: email?.interval_ms,\n emailLeaseDurationMs: email?.lease_ms,\n emailMaximumAttempts: email?.maximum_attempts,\n cleanupEnabled: cleanup?.enabled,\n cleanupBatchSize: cleanup?.batch_size,\n cleanupIntervalMs: cleanup?.interval_ms,\n cleanupLeaseDurationMs: cleanup?.lease_ms,\n documentRetentionMs: config.documents.retention_days * 86_400_000\n }\n}\n\nfunction serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n return {\n aiEndpoint: config.ai?.endpoint,\n aiSigningKey: config.ai ? requiredSecret(environment, config.ai.signing_key) : undefined,\n aiTokenLifetimeSeconds: config.ai ? config.ai.token_lifetime_minutes * 60 : undefined,\n billingPortalURL: config.billing?.portal_url,\n internalServiceToken: config.internal_api\n ? requiredSecret(environment, config.internal_api.service_token)\n : undefined\n }\n}\n\nfunction errorTrackingConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {\n const tracking = config.error_tracking\n if (!tracking) return undefined\n return {\n provider: tracking.provider,\n host: tracking.host,\n projectAPIKey: configuredText(environment, tracking.project_api_key)\n }\n}\n\n/** Hard limits, whatever a plan allows; each lives in the section it limits. */\nfunction technicalLimits(config: CloudDeploymentConfig) {\n return {\n maximumUploadBytes: config.object_storage.maximum_upload_bytes,\n maximumCollaborationMessageBytes: config.collaboration.maximum_message_bytes,\n maximumConnectionsPerRoom: config.collaboration.maximum_connections_per_room\n }\n}\n\nexport function parseCloudDeploymentConfig(\n input: unknown,\n environment: CloudEnvironment\n): CloudServerConfig {\n const config = v.parse(cloudDeploymentConfigSchema, input)\n return parseCloudServerConfig({\n deployment: config.deployment.mode,\n publicURL: config.deployment.public_url,\n indexingPolicy: config.deployment.indexing,\n trustedOrigins: config.deployment.trusted_origins,\n localEditor: config.deployment.local_editor,\n listingMinimumEditorVersion: config.deployment.listing?.minimum_editor_version,\n databaseURL: requiredSecret(environment, config.database.url),\n authSecret: requiredSecret(environment, config.authentication.secret),\n enrollmentMode: config.authentication.enrollment.mode,\n enrollmentAdminNotificationEmails: config.authentication.enrollment.notification_emails,\n emailPasswordEnabled: config.authentication.email_password.enabled,\n emailPasswordSignUpEnabled: config.authentication.email_password.sign_up,\n emailPasswordMinimumLength: config.authentication.email_password.minimum_password_length,\n emailPasswordMaximumLength: config.authentication.email_password.maximum_password_length,\n emailVerificationExpiresIn:\n config.authentication.email_password.verification_link_lifetime_minutes * 60,\n passwordResetExpiresIn:\n config.authentication.email_password.password_reset_link_lifetime_minutes * 60,\n compromisedPasswordCheck: config.authentication.email_password.compromised_password_check,\n deploymentAdminMFARequired: config.authentication.mfa.required_for_admins,\n totpEnabled: config.authentication.mfa.totp,\n recoveryCodesEnabled: config.authentication.mfa.recovery_codes,\n mfaTrustedDeviceDays: config.authentication.mfa.trusted_device_lifetime_days,\n passkeysEnabled: config.authentication.passkeys.enabled,\n passkeyRPName: config.authentication.passkeys.rp_name,\n captchaProvider: config.authentication.captcha?.provider,\n captchaSiteKey: config.authentication.captcha?.site_key,\n captchaSecretKey: config.authentication.captcha\n ? requiredSecret(environment, config.authentication.captcha.secret_key)\n : undefined,\n captchaAllowedHostnames: config.authentication.captcha?.allowed_hostnames,\n authTrustedIPHeaders: config.authentication.trusted_proxies.headers,\n authTrustedProxies: config.authentication.trusted_proxies.addresses,\n ...authenticationConfig(config, environment),\n s3Endpoint: config.object_storage.endpoint,\n s3Region: config.object_storage.region,\n s3Bucket: config.object_storage.bucket,\n s3AccessKeyId: requiredSecret(environment, config.object_storage.credentials.access_key_id),\n s3SecretAccessKey: requiredSecret(\n environment,\n config.object_storage.credentials.secret_access_key\n ),\n s3SessionToken: environment[config.object_storage.credentials.session_token.from_env],\n s3ForcePathStyle: config.object_storage.force_path_style,\n s3ChecksumVerification: config.object_storage.checksum_verification,\n s3ServerSideEncryption: config.object_storage.server_side_encryption,\n s3KmsKeyId: config.object_storage.kms_key_id,\n relayURL: config.collaboration.relay_url,\n staticEntitlements: staticEntitlements(config),\n ...emailConfig(config, environment),\n ...workerConfig(config),\n ...serviceConfig(config, environment),\n errorTracking: errorTrackingConfig(config, environment),\n technicalLimits: technicalLimits(config)\n })\n}\n\nexport function parseCloudDeploymentTOML(\n source: string,\n environment: CloudEnvironment\n): CloudServerConfig {\n return parseCloudDeploymentConfig(parseCloudDeploymentSource(source), environment)\n}\n","import {\n CLOUD_AI_CONTRACT_VERSION,\n CLOUD_PROTOCOL_VERSION,\n parseCloudDiscovery,\n type CloudDiscovery\n} from '#cloud/contract'\nimport { withoutTrailingSlash } from 'ufo'\n\nimport type { CloudServerConfig } from './schema'\n\nexport function configuredSocialProviders(config: CloudServerConfig): Array<'apple' | 'google'> {\n return [\n ...(config.appleClientId ? (['apple'] as const) : []),\n ...(config.googleClientId ? (['google'] as const) : [])\n ]\n}\n\nexport function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscovery {\n const authentication: CloudDiscovery['authentication'] = {\n socialProviders: configuredSocialProviders(config),\n enterpriseSSO: false,\n enrollmentMode: config.enrollmentMode\n }\n if (config.emailPasswordEnabled) {\n authentication.emailPassword = {\n signIn: true,\n signUp: config.emailPasswordSignUpEnabled,\n minimumPasswordLength: config.emailPasswordMinimumLength\n }\n if (config.captchaProvider && config.captchaSiteKey) {\n authentication.emailPassword.captcha = {\n provider: config.captchaProvider,\n siteKey: config.captchaSiteKey\n }\n }\n }\n if (config.totpEnabled || config.passkeysEnabled) {\n authentication.mfa = {\n deploymentAdminRequired: config.deploymentAdminMFARequired,\n totp: config.totpEnabled,\n passkeys: config.passkeysEnabled,\n recoveryCodes: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n\n return parseCloudDiscovery({\n protocolVersion: CLOUD_PROTOCOL_VERSION,\n deployment: config.deployment,\n apiURL: withoutTrailingSlash(new URL('/api', config.publicURL).href),\n authURL: withoutTrailingSlash(new URL('/api/auth', config.publicURL).href),\n localEditor: config.localEditor,\n authentication,\n capabilities: {\n documents: true,\n workspaces: true,\n collaboration: true\n },\n listing: config.listingMinimumEditorVersion\n ? { minimumEditorVersion: config.listingMinimumEditorVersion }\n : undefined,\n ai: config.aiEndpoint\n ? { endpoint: config.aiEndpoint, contractVersion: CLOUD_AI_CONTRACT_VERSION }\n : undefined,\n billing: config.billingPortalURL ? { portalURL: config.billingPortalURL } : undefined\n })\n}\n","import type {\n CloudAuthenticationMethod,\n CloudAuthenticationProvider\n} from '#cloud/contract/account'\nimport { configuredSocialProviders, type CloudServerConfig } from '#cloud/server/config'\n\nimport type { CloudAuthAdapter } from './adapter'\n\nconst supportedProvider = (provider: string): provider is CloudAuthenticationProvider =>\n provider === 'credential' || provider === 'google' || provider === 'apple'\n\nexport function createAccountAuthenticationService(\n auth: CloudAuthAdapter,\n config: CloudServerConfig\n) {\n return {\n async methods(headers: Headers) {\n const accounts = await auth.listAuthenticationMethods(headers)\n const methods = accounts.flatMap((account): CloudAuthenticationMethod[] => {\n if (!supportedProvider(account.providerId)) return []\n return [\n {\n id: account.id,\n provider: account.providerId,\n createdAt: account.createdAt.toISOString(),\n canUnlink: accounts.length > 1\n }\n ]\n })\n return {\n methods,\n availableSocialProviders: configuredSocialProviders(config).filter(\n (provider) => !methods.some((method) => method.provider === provider)\n )\n }\n },\n async changePassword(\n headers: Headers,\n input: { currentPassword: string; newPassword: string }\n ): Promise<void> {\n await auth.changePassword(headers, input)\n },\n async startSocialLink(\n headers: Headers,\n input: { provider: 'google' | 'apple'; callbackURL: string }\n ): Promise<string> {\n if (!configuredSocialProviders(config).includes(input.provider)) {\n throw new Error('Authentication provider is unavailable')\n }\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Authentication callback origin is unavailable')\n }\n return auth.startSocialLink(headers, { ...input, callbackURL: callback.href })\n },\n async unlink(headers: Headers, methodId: string): Promise<void> {\n await auth.unlinkAuthenticationMethod(headers, methodId)\n },\n /** Asks for a new address; the link that confirms it comes back to this server's pages. */\n async changeEmail(\n headers: Headers,\n input: { newEmail: string; callbackURL: string }\n ): Promise<void> {\n const callback = new URL(input.callbackURL)\n if (callback.origin !== new URL(config.publicURL).origin) {\n throw new Error('Email change callback origin is unavailable')\n }\n await auth.changeEmail(headers, { ...input, callbackURL: callback.href })\n }\n }\n}\n\nexport type AccountAuthenticationService = ReturnType<typeof createAccountAuthenticationService>\n","import type {\n DocumentGrant,\n DocumentInvitation,\n DocumentPermission,\n DocumentShare\n} from '#cloud/contract'\n\nexport function dateString(value: Date | string | null): string | null {\n if (value === null) return null\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function shareContract(row: {\n id: string\n documentId: string\n permission: DocumentPermission\n roomEpoch: number\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n expiresAt: Date | string | null\n revokedAt: Date | string | null\n lastUsedAt: Date | string | null\n}): DocumentShare {\n // Rows carry the secret's hash; responses name each field so it never goes out.\n return {\n id: row.id,\n documentId: row.documentId,\n permission: row.permission,\n roomEpoch: row.roomEpoch,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt),\n revokedAt: dateString(row.revokedAt),\n lastUsedAt: dateString(row.lastUsedAt)\n }\n}\n\nexport function grantContract(row: {\n id: string\n documentId: string\n userId: string\n permission: DocumentPermission\n createdBy: string\n createdAt: Date | string\n updatedAt: Date | string\n}): DocumentGrant {\n return {\n id: row.id,\n documentId: row.documentId,\n userId: row.userId,\n permission: row.permission,\n createdBy: row.createdBy,\n createdAt: dateString(row.createdAt) ?? '',\n updatedAt: dateString(row.updatedAt) ?? ''\n }\n}\n\nexport function invitationContract(row: {\n id: string\n documentId: string\n emailNormalized: string\n permission: DocumentPermission\n invitedBy: string\n invitedAt: Date | string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n}): DocumentInvitation {\n return {\n id: row.id,\n documentId: row.documentId,\n email: row.emailNormalized,\n permission: row.permission,\n invitedBy: row.invitedBy,\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? '',\n acceptedAt: dateString(row.acceptedAt)\n }\n}\n","import type * as BetterAuthEndpoints from 'better-auth/api'\n\n/** Where Better Auth answers under the Cloud server. */\nexport const AUTH_BASE_PATH = '/api/auth'\n\n/** The path an endpoint declares, whether the library exports it built or as a factory. */\ntype PathOf<Endpoint> = Endpoint extends { path: infer Path extends string }\n ? Path\n : Endpoint extends (...args: never) => { path: infer Path extends string }\n ? Path\n : never\ntype CorePaths<Names extends keyof typeof BetterAuthEndpoints> = {\n readonly [Name in Names]: PathOf<(typeof BetterAuthEndpoints)[Name]>\n}\n\n/**\n * The core endpoints whose paths Better Auth's own options need before it is built: rate limits,\n * captcha, and the hooks that record sign-ins. Plugin endpoints come from the plugin objects and\n * the rest from `auth.api`; these few are written out, and the type check holds each to the path\n * the library declares, so a renamed endpoint fails to compile.\n */\nexport const CORE_AUTH_PATHS: CorePaths<\n | 'callbackOAuth'\n | 'requestPasswordReset'\n | 'sendVerificationEmail'\n | 'signInEmail'\n | 'signUpEmail'\n | 'verifyEmail'\n> = {\n callbackOAuth: '/callback/:id',\n requestPasswordReset: '/request-password-reset',\n sendVerificationEmail: '/send-verification-email',\n signInEmail: '/sign-in/email',\n signUpEmail: '/sign-up/email',\n verifyEmail: '/verify-email'\n}\n\n/**\n * Whether `path`, as a hook context or request has it, is the endpoint at `endpoint`. Hooks see the\n * declared pattern or the concrete path, so a `:param` segment matches any one segment.\n */\nexport function isAuthEndpoint(path: string | undefined, endpoint: string): boolean {\n if (!path) return false\n const actual = path.split('/')\n const expected = endpoint.split('/')\n return (\n actual.length === expected.length &&\n expected.every((segment, index) =>\n segment.startsWith(':') ? Boolean(actual[index]) : segment === actual[index]\n )\n )\n}\n\n/** The path a request for the endpoint at `endpoint` arrives at on the Cloud server. */\nexport function authRequestPath(endpoint: string): string {\n return `${AUTH_BASE_PATH}${endpoint}`\n}\n","import Bowser from 'bowser'\nimport { compact } from 'es-toolkit'\n\n/** The browser and system a user agent names, as words for a person: `Chrome 141`, `macOS`. */\nexport function describeUserAgent(userAgent: string | null | undefined): {\n browser: string | null\n system: string | null\n} {\n if (!userAgent) return { browser: null, system: null }\n const { browser, os } = Bowser.parse(userAgent)\n const version = browser.version?.split('.', 1)[0]\n return {\n browser: browser.name ? compact([browser.name, version]).join(' ') : null,\n system: os.name || null\n }\n}\n","import type { CloudAccountSession, CloudSignIn, CloudSignInMethod } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport type { BetterAuthPlugin } from 'better-auth'\nimport { createAuthMiddleware, isAPIError } from 'better-auth/api'\nimport type { Kysely } from 'kysely'\n\nimport type { AuthenticationEmailService } from './email'\nimport { CORE_AUTH_PATHS, isAuthEndpoint } from './endpoints'\nimport { describeUserAgent } from './user-agent'\n\n/** The newest sign-ins an account's history shows. */\nconst SIGN_IN_HISTORY_LIMIT = 50\n\ntype Endpoint = { path: string }\n\n/** The plugin endpoints that sign someone in, as the server's plugins declare them. */\nexport type SignInPluginEndpoints = {\n twoStep: { verifyTOTP: Endpoint; verifyBackupCode: Endpoint }\n passkeys: { verifyPasskeyAuthentication: Endpoint; verifyPasskeyRegistration: Endpoint }\n devices: { deviceToken: Endpoint }\n}\n\n/** The Better Auth endpoints that sign someone in, and the method each one is. */\nexport type SignInEndpoints = readonly (readonly [path: string, method: CloudSignInMethod])[]\n\n/** The sign-in endpoints of the core and of the server's plugins, from their own paths. */\nexport function signInEndpoints(plugins: SignInPluginEndpoints): SignInEndpoints {\n return [\n [CORE_AUTH_PATHS.signInEmail, 'password'],\n [plugins.passkeys.verifyPasskeyAuthentication.path, 'passkey'],\n [plugins.twoStep.verifyTOTP.path, 'two-step'],\n [plugins.twoStep.verifyBackupCode.path, 'two-step'],\n [CORE_AUTH_PATHS.verifyEmail, 'email-link'],\n [plugins.devices.deviceToken.path, 'desktop']\n ]\n}\n\n/**\n * How an endpoint signed someone in, or null when it signs nobody in, such as one that refreshes\n * a session. A provider's callback names the provider, as Better Auth's own `lastLoginMethod`\n * reads it.\n */\nexport function signInMethod(\n endpoint: { path?: string; params?: Record<string, string | undefined> },\n methods: SignInEndpoints\n): CloudSignInMethod | null {\n if (isAuthEndpoint(endpoint.path, CORE_AUTH_PATHS.callbackOAuth)) {\n const provider = endpoint.params?.id\n return provider === 'google' || provider === 'apple' ? provider : 'other'\n }\n return methods.find(([path]) => isAuthEndpoint(endpoint.path, path))?.[1] ?? null\n}\n\n/**\n * Where an account signs in from. Each new session is written down with how it was made, so the\n * account's owner can read its sign-ins and sessions, and a sign-in from an address the account\n * never used before is told to its email; the first sign-in an account makes is not.\n */\nexport function createSignInActivity(\n database: Kysely<CloudDatabase>,\n email?: AuthenticationEmailService\n) {\n return {\n /** Writes down a session an endpoint just issued, and mails a sign-in from a new address. */\n async record(\n issued: {\n session: {\n id: string\n userId: string\n ipAddress?: string | null\n userAgent?: string | null\n }\n user: { email: string; name: string }\n },\n method: CloudSignInMethod\n ): Promise<void> {\n const { session, user } = issued\n // Confirming a new email address issues the session it was confirmed in again.\n const recorded = await database\n .selectFrom('signIn')\n .select('id')\n .where('sessionId', '=', session.id)\n .executeTakeFirst()\n if (recorded) return\n const ipAddress = session.ipAddress || null\n const [known, earlier] = await Promise.all([\n ipAddress\n ? database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .where('ipAddress', '=', ipAddress)\n .executeTakeFirst()\n : undefined,\n database\n .selectFrom('signIn')\n .select('id')\n .where('userId', '=', session.userId)\n .executeTakeFirst()\n ])\n const id = crypto.randomUUID()\n const signedInAt = new Date()\n await database\n .insertInto('signIn')\n .values({\n id,\n userId: session.userId,\n sessionId: session.id,\n method,\n ipAddress,\n userAgent: session.userAgent || null,\n createdAt: signedInAt\n })\n .execute()\n if (!email || !earlier || known || !ipAddress) return\n await email.sendNewSignIn({\n email: user.email,\n name: user.name,\n signInId: id,\n signedInAt,\n ipAddress,\n ...describeUserAgent(session.userAgent),\n desktop: method === 'desktop'\n })\n },\n\n /** The account's sessions that have not expired, newest activity first. */\n async sessions(userId: string, currentSessionId: string): Promise<CloudAccountSession[]> {\n const rows = await database\n .selectFrom('session')\n .leftJoin('signIn', 'signIn.sessionId', 'session.id')\n .select([\n 'session.id',\n 'session.ipAddress',\n 'session.userAgent',\n 'session.createdAt',\n 'session.updatedAt',\n 'session.expiresAt',\n 'signIn.method'\n ])\n .where('session.userId', '=', userId)\n .where('session.expiresAt', '>', new Date())\n .orderBy('session.updatedAt', 'desc')\n .execute()\n return rows.map((row) => ({\n id: row.id,\n current: row.id === currentSessionId,\n method: row.method ?? null,\n ipAddress: row.ipAddress || null,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? '',\n lastActiveAt: dateString(row.updatedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }))\n },\n\n async signIns(userId: string, limit = SIGN_IN_HISTORY_LIMIT): Promise<CloudSignIn[]> {\n const rows = await database\n .selectFrom('signIn')\n .select(['id', 'method', 'ipAddress', 'userAgent', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt', 'desc')\n .limit(limit)\n .execute()\n return rows.map((row) => ({\n id: row.id,\n method: row.method,\n ipAddress: row.ipAddress,\n ...describeUserAgent(row.userAgent),\n createdAt: dateString(row.createdAt) ?? ''\n }))\n }\n }\n}\n\nexport type SignInActivity = ReturnType<typeof createSignInActivity>\n\n/**\n * Better Auth's side of account activity. After an endpoint issues a session, Better Auth hands\n * it to hooks as `newSession`; two-step sign-in clears it until the second step, so only\n * sessions someone can use are written down. Adding a passkey is told to its owner.\n */\nexport function accountActivity(\n activity: SignInActivity,\n plugins: SignInPluginEndpoints,\n onPasskeyAdded: (user: { id: string; email: string; name: string }) => Promise<void>\n): BetterAuthPlugin {\n const methods = signInEndpoints(plugins)\n return {\n id: 'openpencil-account-activity',\n hooks: {\n after: [\n {\n matcher: (context) => signInMethod(context, methods) !== null,\n handler: createAuthMiddleware(async (context) => {\n const issued = context.context.newSession\n const method = signInMethod(context, methods)\n if (issued && method) await activity.record(issued, method)\n })\n },\n {\n matcher: (context) =>\n isAuthEndpoint(context.path, plugins.passkeys.verifyPasskeyRegistration.path),\n handler: createAuthMiddleware(async (context) => {\n const user = context.context.session?.user\n if (user && !isAPIError(context.context.returned)) await onPasskeyAdded(user)\n })\n }\n ]\n }\n }\n}\n","import type { TwoStepChange } from '#cloud/email'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\n\nexport type AuthenticationEmailService = {\n sendVerification(input: {\n email: string\n name: string\n url: string\n token: string\n purpose?: 'account' | 'change'\n }): Promise<void>\n sendPasswordReset(input: {\n email: string\n name: string\n url: string\n token: string\n }): Promise<void>\n sendPasswordChanged(input: {\n email: string\n name: string\n userId: string\n url: string\n }): Promise<void>\n /** Tells the address being replaced which address is taking over, before it confirms. */\n sendEmailChangeRequested(input: {\n email: string\n name: string\n userId: string\n newEmail: string\n }): Promise<void>\n sendNewSignIn(input: {\n email: string\n name: string\n signInId: string\n signedInAt: Date\n ipAddress: string | null\n browser: string | null\n system: string | null\n desktop: boolean\n }): Promise<void>\n sendTwoStepChanged(input: {\n email: string\n name: string\n userId: string\n change: TwoStepChange\n }): Promise<void>\n}\n\nfunction tokenHash(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function createAuthenticationEmailService(\n email: TransactionalEmailService,\n publicURL: string\n): AuthenticationEmailService {\n return {\n async sendVerification(input) {\n await email.enqueue({\n idempotencyKey: `email-verification/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'email-verification',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: input.url, purpose: input.purpose }\n })\n },\n async sendPasswordReset(input) {\n await email.enqueue({\n idempotencyKey: `password-reset/${input.email.toLowerCase()}/${tokenHash(input.token)}`,\n kind: 'password-reset',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: input.url }\n })\n },\n async sendPasswordChanged(input) {\n await email.enqueue({\n idempotencyKey: `password-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'password-changed',\n recipientEmail: input.email,\n payload: { name: input.name, actionURL: new URL('/auth/sign-in', publicURL).href }\n })\n },\n async sendEmailChangeRequested(input) {\n await email.enqueue({\n idempotencyKey: `email-change-requested/${input.userId}/${crypto.randomUUID()}`,\n kind: 'email-change-requested',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n newEmail: input.newEmail,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n async sendNewSignIn(input) {\n await email.enqueue({\n idempotencyKey: `new-sign-in/${input.signInId}`,\n kind: 'new-sign-in',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n signedInAt: input.signedInAt.toISOString(),\n ipAddress: input.ipAddress,\n browser: input.browser,\n system: input.system,\n desktop: input.desktop,\n actionURL: new URL('/account/sessions', publicURL).href\n }\n })\n },\n async sendTwoStepChanged(input) {\n await email.enqueue({\n idempotencyKey: `two-step-changed/${input.userId}/${crypto.randomUUID()}`,\n kind: 'two-step-changed',\n recipientEmail: input.email,\n payload: {\n name: input.name,\n change: input.change,\n actionURL: new URL('/account/security', publicURL).href\n }\n })\n }\n }\n}\n","import type { CloudMFAStatus } from '#cloud/server/auth/adapter'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nconst ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000\n\nexport function createMFAAssuranceService(\n database: Kysely<CloudDatabase>,\n config: CloudServerConfig\n) {\n return {\n async record(input: {\n sessionId: string\n userId: string\n method: 'totp' | 'recovery-code' | 'passkey'\n }): Promise<void> {\n await database\n .insertInto('mfaAssurance')\n .values({ ...input, verifiedAt: new Date() })\n .onConflict((conflict) =>\n conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })\n )\n .execute()\n },\n async status(input: {\n sessionId: string\n userId: string\n deploymentRole?: 'user' | 'admin'\n twoFactorEnabled: boolean\n passkeyCount: number\n }): Promise<CloudMFAStatus> {\n const assurance = await database\n .selectFrom('mfaAssurance')\n .select('verifiedAt')\n .where('sessionId', '=', input.sessionId)\n .where('userId', '=', input.userId)\n .executeTakeFirst()\n const assured = Boolean(\n assurance && new Date(assurance.verifiedAt).getTime() > Date.now() - ASSURANCE_MAX_AGE_MS\n )\n return {\n required: config.deploymentAdminMFARequired && input.deploymentRole === 'admin' && !assured,\n enabled: input.twoFactorEnabled || input.passkeyCount > 0,\n totpEnabled: input.twoFactorEnabled,\n assured,\n totpAvailable: config.totpEnabled,\n passkeysAvailable: config.passkeysEnabled,\n recoveryCodesAvailable: config.totpEnabled && config.recoveryCodesEnabled\n }\n }\n }\n}\n\nexport type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>\n","import type { BetterAuthPlugin } from 'better-auth'\nimport { decodeJwt } from 'jose'\nimport * as v from 'valibot'\n\nimport type { UserPictureService } from './service'\n\n/** The providers whose ID token names the person's picture. */\nconst PICTURE_PROVIDERS = new Set(['google'])\nconst pictureClaimSchema = v.object({ picture: v.pipe(v.string(), v.url()) })\n\n/**\n * The picture a linked account's provider names in the ID token Better Auth keeps on its account\n * row, or null. The token came to Better Auth from the provider during its sign-in flow, which no\n * client can write to the row.\n */\nexport function providerPicture(account: { providerId: string; idToken?: string | null }) {\n if (!PICTURE_PROVIDERS.has(account.providerId) || !account.idToken) return null\n try {\n const claims = v.safeParse(pictureClaimSchema, decodeJwt(account.idToken))\n return claims.success ? claims.output.picture : null\n } catch {\n return null\n }\n}\n\n/**\n * Keeps the picture a Google account names, so pages show the server's copy and never load it\n * from Google. Better Auth writes the account's ID token when it is linked and at each sign-in\n * with it, so accounts made before the server kept pictures move over the next time they sign in\n * this way. Better Auth also takes an `image` on sign-up and user updates; none of those reach the\n * account, since the server writes the addresses of the pictures it keeps itself.\n */\nexport function providerPictures(pictures: UserPictureService): BetterAuthPlugin {\n const keep = async (account: { userId: string; providerId: string; idToken?: string | null }) => {\n const picture = providerPicture(account)\n if (picture) await pictures.copyFromProvider(account.userId, picture)\n }\n return {\n id: 'openpencil-provider-pictures',\n init: () => ({\n options: {\n databaseHooks: {\n user: {\n create: {\n before: async (user) => ({ data: { ...user, image: null } })\n },\n update: {\n // Better Auth merges what a hook returns into the update, so `image` is unset.\n before: async (user) =>\n user.image === undefined ? true : { data: { image: undefined } }\n }\n },\n account: {\n create: { after: keep },\n update: { after: keep }\n }\n }\n }\n })\n }\n}\n","import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'\nimport type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\nimport { imageSize } from 'image-size'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\n/** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */\nexport const PICTURE_PATH = '/api/pictures'\n/** The longest side a stored picture may have; pages send 256 pixels. */\nconst PICTURE_MAX_SIDE = 1024\n/** How many hex digits of the checksum name a picture in its address. */\nconst PICTURE_VERSION_LENGTH = 16\n/** How long a linked account's picture may take to fetch before sign-in goes on without it. */\nconst PROVIDER_PICTURE_TIMEOUT_MS = 5000\n/** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */\nconst PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']\nconst PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }\nconst userIdSchema = v.pipe(v.string(), v.uuid())\n\n/** The bytes are not a PNG or JPEG picture the server keeps. */\nexport class PictureInvalidError extends Error {\n constructor() {\n super('The picture must be a PNG or JPEG image of at most 1024 by 1024 pixels')\n this.name = 'PictureInvalidError'\n }\n}\n\n/** The format of a picture the server keeps, read from its bytes; anything else is null. */\nexport function pictureFormat(bytes: Uint8Array): UserPictureFormat | null {\n if (bytes.byteLength === 0 || bytes.byteLength > CLOUD_PICTURE_MAX_BYTES) return null\n try {\n const size = imageSize(bytes)\n const format = size.type ? PICTURE_FORMATS[size.type] : undefined\n if (!format || size.width < 1 || size.height < 1) return null\n if (size.width > PICTURE_MAX_SIDE || size.height > PICTURE_MAX_SIDE) return null\n return format\n } catch {\n return null\n }\n}\n\n/** Whether `url` is an HTTPS address on a host a linked account's picture comes from. */\nfunction providerPicture(url: URL): boolean {\n return (\n url.protocol === 'https:' &&\n PROVIDER_PICTURE_HOSTS.some(\n (host) => url.hostname === host || url.hostname.endsWith(`.${host}`)\n )\n )\n}\n\n/** Reads at most `limit` bytes of a response body, or null when it holds more. */\nasync function boundedBody(response: Response, limit: number): Promise<Uint8Array | null> {\n if (!response.body) return null\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n length += value.byteLength\n if (length > limit) {\n await reader.cancel()\n return null\n }\n chunks.push(value)\n }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n return bytes\n}\n\ntype AccountPicture = { image: string | null; updatedAt: Date }\n\nfunction samePicture(current: AccountPicture | undefined, seen: AccountPicture | undefined) {\n return (\n current?.image === seen?.image && current?.updatedAt.getTime() === seen?.updatedAt.getTime()\n )\n}\n\nexport type UserPictureOptions = {\n publicURL: string\n /** Fetches a linked account's picture; tests pass their own. */\n fetch?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * The picture each account shows. The server keeps the bytes and serves them itself, so a page\n * that shows a person never asks another service for them; `user.image` holds their address.\n */\nexport function createUserPictures(database: Kysely<CloudDatabase>, options: UserPictureOptions) {\n const fetchPicture = options.fetch ?? ((url, init) => fetch(url, init))\n const origin = new URL(options.publicURL).origin\n\n function address(userId: string, checksum: string): string {\n return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`\n }\n\n /** The address `bytes` are served from as the account's picture. */\n function pictureAddress(userId: string, bytes: Uint8Array): string {\n return address(userId, bytesToHex(sha256(bytes)))\n }\n\n /** Whether `image` is a picture this server serves, rather than another service's. */\n function served(image: string): boolean {\n return image.startsWith(`${origin}${PICTURE_PATH}/`)\n }\n\n /**\n * Keeps `bytes` as the account's picture. A provider's picture is kept only while the account is\n * unchanged since `seen`, read before the picture was fetched: every upload and removal moves\n * `updatedAt`, so one made meanwhile stands, even one that left the image as it was. Returns\n * whether the picture was kept.\n */\n async function save(\n userId: string,\n bytes: Uint8Array,\n source: { from: 'upload' } | { from: 'provider'; seen: AccountPicture | undefined }\n ): Promise<boolean> {\n const format = pictureFormat(bytes)\n if (!format) throw new PictureInvalidError()\n const checksum = bytesToHex(sha256(bytes))\n const image = pictureAddress(userId, bytes)\n const createdAt = new Date()\n return database.transaction().execute(async (transaction) => {\n // Saves and removals lock the account first, so they take turns.\n const current = await transaction\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirst()\n if (source.from === 'provider' && !samePicture(current, source.seen)) return false\n await transaction\n .insertInto('userPicture')\n .values({ userId, bytes, format, checksum, source: source.from, createdAt })\n .onConflict((conflict) =>\n conflict\n .column('userId')\n .doUpdateSet({ bytes, format, checksum, source: source.from, createdAt })\n )\n .execute()\n await transaction\n .updateTable('user')\n .set({ image, updatedAt: createdAt })\n .where('id', '=', userId)\n .execute()\n return true\n })\n }\n\n async function remove(userId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n // The account first, in the same order saves lock, so the two never wait on each other.\n await transaction\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .forUpdate()\n .execute()\n await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n })\n }\n\n return {\n served,\n\n /** Keeps a picture the account's owner uploaded and shows it from now on. */\n async upload(userId: string, bytes: Uint8Array): Promise<string> {\n await save(userId, bytes, { from: 'upload' })\n return pictureAddress(userId, bytes)\n },\n\n /** Goes back to initials. */\n remove,\n\n /** The picture at `/api/pictures/:userId/:version`, or null for any other address. */\n async read(userId: string, version: string) {\n if (!v.is(userIdSchema, userId) || version.length !== PICTURE_VERSION_LENGTH) return null\n const picture = await database\n .selectFrom('userPicture')\n .select(['bytes', 'format', 'checksum'])\n .where('userId', '=', userId)\n .executeTakeFirst()\n return picture?.checksum.startsWith(version) ? picture : null\n },\n\n /**\n * Keeps the picture a linked account named in `image` and shows it instead, so pages never\n * load it from that service. A picture that cannot be fetched or is not one the server keeps\n * leaves initials in its place. An uploaded picture stays.\n */\n async copyFromProvider(userId: string, image: string): Promise<void> {\n if (served(image)) return\n // A picture the account already shows from this server, uploaded or kept before, stays.\n const current = await database\n .selectFrom('user')\n .select(['image', 'updatedAt'])\n .where('id', '=', userId)\n .executeTakeFirst()\n if (current?.image && served(current.image)) return\n try {\n if (!providerPicture(new URL(image))) throw new PictureInvalidError()\n const response = await fetchPicture(image, {\n redirect: 'error',\n signal: AbortSignal.timeout(PROVIDER_PICTURE_TIMEOUT_MS)\n })\n const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null\n if (!bytes) throw new PictureInvalidError()\n await save(userId, bytes, { from: 'provider', seen: current })\n } catch (error) {\n console.warn('Keeping a linked account picture failed', error)\n await database\n .updateTable('user')\n .set({ image: null, updatedAt: new Date() })\n .where('id', '=', userId)\n .where('image', '=', image)\n .execute()\n }\n }\n }\n}\n\nexport type UserPictureService = ReturnType<typeof createUserPictures>\n","import { pictureParams } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { PICTURE_PATH, type UserPictureService } from './service'\n\n/**\n * Account pictures, for anyone with a picture's address: pages show people to those they share\n * documents and workspaces with, and the desktop app shows them from another origin.\n */\nexport function createPictureRoutes(pictures: UserPictureService) {\n return new Hono().get(`${PICTURE_PATH}/:userId/:version`, pictureParams, async (context) => {\n const { userId, version } = context.req.valid('param')\n const picture = await pictures.read(userId, version)\n if (!picture) return context.json({ error: { code: 'not_found' as const } }, 404)\n // The address changes with the picture, but a removed one must stop showing within a day.\n context.header('Cache-Control', 'public, max-age=86400')\n context.header('Content-Type', `image/${picture.format}`)\n context.header('X-Content-Type-Options', 'nosniff')\n context.header('Content-Security-Policy', \"default-src 'none'; sandbox\")\n context.header('Cross-Origin-Resource-Policy', 'cross-origin')\n return context.body(new Uint8Array(picture.bytes))\n })\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { BetterAuthOptions } from 'better-auth'\nimport { importPKCS8, SignJWT } from 'jose'\n\n/** The audience Apple's sign-in tokens carry, which the server also trusts as an origin. */\nexport const APPLE_AUDIENCE = 'https://appleid.apple.com'\nconst APPLE_SECRET_LIFETIME_SECONDS = 180 * 24 * 60 * 60\nasync function generateAppleClientSecret(config: CloudServerConfig): Promise<string> {\n if (\n !config.appleClientId ||\n !config.appleTeamId ||\n !config.appleKeyId ||\n !config.applePrivateKey\n ) {\n throw new Error('Apple authentication is not configured')\n }\n const privateKey = await importPKCS8(config.applePrivateKey.replaceAll('\\\\n', '\\n'), 'ES256')\n const issuedAt = Math.floor(Date.now() / 1000)\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: config.appleKeyId })\n .setIssuer(config.appleTeamId)\n .setSubject(config.appleClientId)\n .setAudience(APPLE_AUDIENCE)\n .setIssuedAt(issuedAt)\n .setExpirationTime(issuedAt + APPLE_SECRET_LIFETIME_SECONDS)\n .sign(privateKey)\n}\n\n/** The sign-in providers the deployment configures; Apple's secret is signed when it is needed. */\nexport function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {\n const providers: BetterAuthOptions['socialProviders'] = {}\n if (config.googleClientId && config.googleClientSecret) {\n providers.google = {\n clientId: config.googleClientId,\n clientSecret: config.googleClientSecret\n }\n }\n if (config.appleClientId) {\n providers.apple = async () => {\n const provider: {\n clientId: string\n clientSecret: string\n appBundleIdentifier?: string\n } = {\n clientId: config.appleClientId ?? '',\n clientSecret: await generateAppleClientSecret(config)\n }\n if (config.appleAppBundleIdentifier) {\n provider.appBundleIdentifier = config.appleAppBundleIdentifier\n }\n return provider\n }\n }\n return providers\n}\n","import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createUserPictures, providerPictures } from '#cloud/server/pictures'\nimport { passkey } from '@better-auth/passkey'\nimport { APIError, betterAuth } from 'better-auth'\nimport { getMigrations } from 'better-auth/db/migration'\nimport {\n admin,\n bearer,\n captcha,\n deviceAuthorization,\n haveIBeenPwned,\n twoFactor\n} from 'better-auth/plugins'\nimport type { Kysely } from 'kysely'\n\nimport { accountActivity, createSignInActivity } from './activity'\nimport type { CloudAuthAdapter } from './adapter'\nimport type { AuthenticationEmailService } from './email'\nimport { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'\nimport { createMFAAssuranceService } from './mfa-assurance'\nimport { APPLE_AUDIENCE, socialProviders } from './social-providers'\n\nconst BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'\nconst ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60\n\nasync function recordResponseAssurance(\n response: Response,\n method: 'totp' | 'recovery-code' | 'passkey',\n database: Kysely<CloudDatabase>,\n assurance: ReturnType<typeof createMFAAssuranceService>\n): Promise<void> {\n const signedToken = response.headers.get('set-auth-token')\n const token = signedToken?.split('.', 1)[0]\n if (!token) return\n const session = await database\n .selectFrom('session')\n .select(['id', 'userId'])\n .where('token', '=', token)\n .executeTakeFirst()\n if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })\n}\n\nasync function verifySecondFactor(\n auth: { handler(request: Request): Promise<Response> },\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n assurance: ReturnType<typeof createMFAAssuranceService>,\n headers: Headers,\n code: string,\n method: 'totp' | 'recovery-code',\n /** The two-step plugin's endpoint that checks this kind of code. */\n endpoint: { path: string }\n): Promise<Response> {\n const response = await auth.handler(\n new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {\n method: 'POST',\n headers: new Headers({\n ...Object.fromEntries(headers),\n 'Content-Type': 'application/json'\n }),\n body: JSON.stringify({ code, trustDevice: false })\n })\n )\n if (!response.ok) throw APIError.fromStatus(response.status as 401)\n await recordResponseAssurance(response, method, database, assurance)\n return response\n}\n\nexport type CloudAuthRuntimeOptions = {\n email?: AuthenticationEmailService\n runInBackground?: (promise: Promise<unknown>) => void\n /**\n * Whether Better Auth checks the database schema when it starts. Runtimes that start it for\n * every request turn this off; `migrateCloudDatabase` has already checked the recorded version.\n */\n validateSchema?: boolean\n}\n\nexport function createBetterAuthAdapter(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n enrollment: EnrollmentService = createEnrollmentService(database),\n runtime: CloudAuthRuntimeOptions = {}\n): CloudAuthAdapter {\n const authenticationEmail = runtime.email\n const assurance = createMFAAssuranceService(database, config)\n const activity = createSignInActivity(database, authenticationEmail)\n // A new address is confirmed through a link sent to it, so changing one needs email delivery.\n const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)\n // The plugins are built first, so the options below name their endpoints by the paths they declare.\n const twoStep = twoFactor({\n issuer: 'OpenPencil Cloud',\n trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,\n allowPasswordless: true,\n totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },\n backupCodeOptions: {\n disable: !config.totpEnabled || !config.recoveryCodesEnabled,\n storeBackupCodes: 'encrypted'\n }\n })\n const passkeys = passkey({\n rpID: new URL(config.publicURL).hostname,\n rpName: config.passkeyRPName,\n origin: new URL(config.publicURL).origin\n })\n const devices = deviceAuthorization({\n verificationUri: new URL('/auth/device', config.publicURL).href,\n validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')\n })\n const administration = admin()\n const auth = betterAuth({\n appName: 'OpenPencil Cloud',\n baseURL: config.publicURL,\n basePath: AUTH_BASE_PATH,\n // Clients never reach Better Auth's own administration, which `/api/admin` replaces with MFA,\n // origin, last-administrator, and audit checks, nor the two endpoints Cloud's policy manages\n // through its account routes; the server still calls them itself.\n disabledPaths: [\n ...Object.values(administration.endpoints).map((endpoint) => endpoint.path),\n passkeys.endpoints.deletePasskey.path,\n twoStep.endpoints.disableTwoFactor.path\n ],\n secret: config.authSecret,\n database: {\n db: database,\n type: 'postgres',\n casing: 'camel',\n transaction: true\n },\n account: {\n accountLinking: {\n enabled: true,\n disableImplicitLinking: false,\n trustedProviders: ['google', 'apple'],\n allowDifferentEmails: false,\n allowUnlinkingAll: false,\n requireLocalEmailVerified: true\n }\n },\n session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },\n advanced: {\n database: { generateId: 'uuid', validateSchema: runtime.validateSchema },\n ipAddress: {\n ipAddressHeaders: config.authTrustedIPHeaders,\n trustedProxies: config.authTrustedProxies\n },\n ...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})\n },\n rateLimit: {\n enabled: true,\n storage: 'database',\n window: 60,\n max: 100,\n customRules: {\n [devices.endpoints.deviceCode.path]: { window: 60, max: 10 },\n [devices.endpoints.deviceToken.path]: { window: 60, max: 60 },\n [devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },\n [devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },\n [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },\n [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },\n [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }\n }\n },\n emailAndPassword: config.emailPasswordEnabled\n ? {\n enabled: true,\n disableSignUp: !config.emailPasswordSignUpEnabled,\n requireEmailVerification: true,\n minPasswordLength: config.emailPasswordMinimumLength,\n maxPasswordLength: config.emailPasswordMaximumLength,\n autoSignIn: false,\n resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,\n revokeSessionsOnPasswordReset: true,\n sendResetPassword: authenticationEmail\n ? ({ user, url, token }) =>\n authenticationEmail.sendPasswordReset({\n email: user.email,\n name: user.name,\n url,\n token\n })\n : undefined,\n onPasswordReset: authenticationEmail\n ? ({ user }) =>\n authenticationEmail.sendPasswordChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n url: config.publicURL\n })\n : undefined\n }\n : undefined,\n emailVerification:\n config.emailPasswordEnabled && authenticationEmail\n ? {\n expiresIn: config.emailVerificationExpiresIn,\n sendOnSignUp: true,\n // Signing in unverified only says so; people ask for another link with Send again.\n sendOnSignIn: false,\n autoSignInAfterVerification: true,\n // A change of address sends the link to the new address as `user.email`, on the\n // account it already confirmed; a new account has not confirmed one yet. This runs\n // inside sign-up's transaction, so it must not query the database itself.\n sendVerificationEmail: ({ user, url, token }) =>\n authenticationEmail.sendVerification({\n email: user.email,\n name: user.name,\n url,\n token,\n purpose: user.emailVerified ? 'change' : 'account'\n }),\n afterEmailVerification: async (user) => {\n await enrollment.followEmailChange(user.id, user.email)\n if (config.enrollmentMode === 'approval') {\n await enrollment.request({ email: user.email, name: user.name })\n }\n await enrollment.bindApprovedUser(user.email, user.id)\n }\n }\n : undefined,\n user: {\n changeEmail: { enabled: emailChangeAvailable },\n validateUserInfo: ({ source }) => {\n if (source.action === 'create-user' && config.enrollmentMode === 'closed') {\n return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }\n }\n return undefined\n }\n },\n databaseHooks: {\n user: {\n create: {\n after: async (user) => {\n if (!user.emailVerified) return\n if (config.enrollmentMode === 'approval') {\n await enrollment.request({ email: user.email, name: user.name })\n }\n await enrollment.bindApprovedUser(user.email, user.id)\n }\n }\n }\n },\n plugins: [\n ...(config.captchaProvider && config.captchaSecretKey\n ? [\n captcha({\n provider: config.captchaProvider,\n secretKey: config.captchaSecretKey,\n allowedHostnames: config.captchaAllowedHostnames,\n endpoints: [\n CORE_AUTH_PATHS.signUpEmail,\n CORE_AUTH_PATHS.signInEmail,\n CORE_AUTH_PATHS.requestPasswordReset\n ]\n })\n ]\n : []),\n ...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),\n twoStep,\n passkeys,\n administration,\n // Device authorization returns opaque database session tokens, not signed cookies.\n bearer(),\n devices,\n // After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.\n accountActivity(\n activity,\n { twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },\n (user) => notifyTwoStep(user, 'passkey-added')\n ),\n providerPictures(createUserPictures(database, { publicURL: config.publicURL }))\n ],\n socialProviders: socialProviders(config),\n trustedOrigins: [\n config.publicURL,\n ...config.trustedOrigins,\n ...(config.appleClientId ? [APPLE_AUDIENCE] : [])\n ]\n })\n\n // Administrators are granted only through the `admin` command or by another administrator.\n const deploymentRole = (user: { id: string; role?: string | null }) =>\n user.role === 'admin' ? ('admin' as const) : ('user' as const)\n\n const resolveIdentity = async (headers: Headers) => {\n const session = await auth.api.getSession({ headers })\n if (!session) return null\n return {\n userId: session.user.id,\n email: session.user.email,\n name: session.user.name,\n image: session.user.image ?? null,\n deploymentRole: deploymentRole(session.user)\n }\n }\n\n /** The signed-in person, read past the cookie cache, for changes about their own account. */\n const currentSession = (headers: Headers) =>\n auth.api.getSession({ headers, query: { disableCookieCache: true } })\n\n /** The current session when it signed in recently enough to change how the account is reached. */\n async function freshSession(headers: Headers) {\n const session = await currentSession(headers)\n const createdAt = session?.session.createdAt\n if (\n !session ||\n !createdAt ||\n Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000\n ) {\n throw APIError.from('FORBIDDEN', {\n code: 'SESSION_NOT_FRESH',\n message: 'Session is not fresh'\n })\n }\n return session\n }\n\n async function notifyTwoStep(\n user: { id: string; email: string; name: string },\n change: Parameters<AuthenticationEmailService['sendTwoStepChanged']>[0]['change']\n ): Promise<void> {\n await authenticationEmail?.sendTwoStepChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n change\n })\n }\n\n /** The signed-in person while their account may use the server, which awaiting approval it may not. */\n async function resolveSession(headers: Headers) {\n const identity = await resolveIdentity(headers)\n if (!identity) return null\n if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {\n return null\n }\n return identity\n }\n\n /**\n * The endpoints that read or change an account, which only an account that may use the server\n * reaches; one awaiting approval still signs in and out. Better Auth checks the session inside\n * most of these endpoints rather than declaring it, so they are listed by their own objects.\n */\n const activeAccountPaths = new Set(\n [\n auth.api.generatePasskeyRegistrationOptions,\n auth.api.listPasskeys,\n auth.api.updatePasskey,\n auth.api.verifyPasskeyRegistration,\n auth.api.enableTwoFactor,\n auth.api.generateBackupCodes,\n auth.api.getTOTPURI,\n auth.api.accountInfo,\n auth.api.changeEmail,\n auth.api.changePassword,\n auth.api.deleteUser,\n auth.api.getAccessToken,\n auth.api.linkSocialAccount,\n auth.api.listUserAccounts,\n auth.api.listSessions,\n auth.api.refreshToken,\n auth.api.revokeOtherSessions,\n auth.api.revokeSession,\n auth.api.revokeSessions,\n auth.api.unlinkAccount\n ].map((endpoint) => authRequestPath(endpoint.path))\n )\n /** The second factor a request proves, by the endpoint it is for. */\n const assuranceMethods = new Map<string, 'totp' | 'recovery-code' | 'passkey'>([\n [authRequestPath(twoStep.endpoints.verifyTOTP.path), 'totp'],\n [authRequestPath(twoStep.endpoints.verifyBackupCode.path), 'recovery-code'],\n [authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path), 'passkey']\n ])\n\n return {\n handler: async (request) => {\n const path = new URL(request.url).pathname\n if (activeAccountPaths.has(path) && !(await resolveSession(request.headers))) {\n return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })\n }\n const response = await auth.handler(request)\n const method = assuranceMethods.get(path)\n if (response.ok && method)\n await recordResponseAssurance(response, method, database, assurance)\n return response\n },\n resolveIdentity,\n resolveSession,\n async listAuthenticationMethods(headers) {\n const accounts = await auth.api.listUserAccounts({ headers })\n return accounts.map((account) => ({\n id: account.id,\n providerId: account.providerId,\n createdAt: account.createdAt\n }))\n },\n async changePassword(headers, input) {\n const session = authenticationEmail ? await auth.api.getSession({ headers }) : null\n await auth.api.changePassword({\n headers,\n body: { ...input, revokeOtherSessions: false }\n })\n await auth.api.revokeOtherSessions({ headers })\n if (authenticationEmail && session) {\n await authenticationEmail.sendPasswordChanged({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n url: config.publicURL\n })\n }\n },\n async startSocialLink(headers, input) {\n await freshSession(headers)\n const response = await auth.api.linkSocialAccount({\n headers,\n body: {\n provider: input.provider,\n callbackURL: input.callbackURL,\n errorCallbackURL: input.callbackURL,\n disableRedirect: true\n }\n })\n return response.url\n },\n async unlinkAuthenticationMethod(headers, methodId) {\n await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })\n },\n async banUser(headers, userId, reason) {\n await auth.api.banUser({ headers, body: { userId, banReason: reason } })\n },\n async unbanUser(headers, userId) {\n await auth.api.unbanUser({ headers, body: { userId } })\n },\n async revokeUserSessions(headers, userId) {\n await auth.api.revokeUserSessions({ headers, body: { userId } })\n },\n async setRole(headers, userId, role) {\n await auth.api.setRole({ headers, body: { userId, role } })\n },\n async mfaStatus(headers) {\n const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })\n if (!session) return null\n const passkeys = await auth.api.listPasskeys({ headers })\n return assurance.status({\n sessionId: session.session.id,\n userId: session.user.id,\n deploymentRole: deploymentRole(session.user),\n twoFactorEnabled:\n 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true,\n passkeyCount: passkeys.length\n })\n },\n async enableTOTP(headers, password) {\n const response = await auth.api.enableTwoFactor({\n headers,\n body: { password, method: 'totp' }\n })\n if (response.method !== 'totp') throw new Error('TOTP setup was unavailable')\n return { totpURI: response.totpURI, backupCodes: response.backupCodes }\n },\n async verifyTOTP(headers, code) {\n const before = await currentSession(headers)\n const response = await verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'totp',\n twoStep.endpoints.verifyTOTP\n )\n // The first code from a new authenticator is what turns it on.\n if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {\n await notifyTwoStep(before.user, 'authenticator-on')\n }\n return response\n },\n async verifyRecoveryCode(headers, code) {\n return verifySecondFactor(\n auth,\n config,\n database,\n assurance,\n headers,\n code,\n 'recovery-code',\n twoStep.endpoints.verifyBackupCode\n )\n },\n async generateRecoveryCodes(headers, password) {\n return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes\n },\n async disableTOTP(headers, password) {\n await auth.api.disableTwoFactor({ headers, body: { password } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'authenticator-off')\n },\n async listPasskeys(headers) {\n return (await auth.api.listPasskeys({ headers })).map((item) => ({\n id: item.id,\n name: item.name,\n createdAt: item.createdAt\n }))\n },\n async deletePasskey(headers, id) {\n await auth.api.deletePasskey({ headers, body: { id } })\n const session = await currentSession(headers)\n if (session) await notifyTwoStep(session.user, 'passkey-removed')\n },\n emailChangeAvailable,\n async profile(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return {\n id: session.user.id,\n name: session.user.name,\n email: session.user.email,\n image: session.user.image ?? null,\n createdAt: new Date(session.user.createdAt)\n }\n },\n async updateProfile(headers, input) {\n await auth.api.updateUser({ headers, body: { name: input.name } })\n },\n async changeEmail(headers, input) {\n const session = await freshSession(headers)\n if (session.user.email === input.newEmail) {\n throw APIError.from('BAD_REQUEST', {\n code: 'EMAIL_UNCHANGED',\n message: 'Email is the same'\n })\n }\n await auth.api.changeEmail({ headers, body: input })\n await authenticationEmail?.sendEmailChangeRequested({\n email: session.user.email,\n name: session.user.name,\n userId: session.user.id,\n newEmail: input.newEmail\n })\n },\n async sessions(headers) {\n const session = await currentSession(headers)\n if (!session) return null\n return activity.sessions(session.user.id, session.session.id)\n },\n async revokeSession(headers, sessionId) {\n const session = await currentSession(headers)\n if (!session) throw APIError.fromStatus('UNAUTHORIZED')\n if (session.session.id === sessionId) {\n throw APIError.from('BAD_REQUEST', {\n code: 'CURRENT_SESSION',\n message: 'Sign out to end this session'\n })\n }\n const target = await database\n .selectFrom('session')\n .select('token')\n .where('id', '=', sessionId)\n .where('userId', '=', session.user.id)\n .executeTakeFirst()\n if (target) await auth.api.revokeSession({ headers, body: { token: target.token } })\n },\n async revokeOtherSessions(headers) {\n await auth.api.revokeOtherSessions({ headers })\n },\n async signIns(headers) {\n const session = await currentSession(headers)\n return session ? activity.signIns(session.user.id) : null\n },\n schemaVersion: BETTER_AUTH_SCHEMA_VERSION,\n async migrate() {\n const migrations = await getMigrations(auth.options)\n await migrations.runMigrations()\n }\n }\n}\n","import { createEnrollmentService } from '#cloud/admin/enrollment/service'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport type { Kysely } from 'kysely'\n\nimport { createAuthenticationEmailService } from './email'\nimport { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'\n\nexport function createCloudAuthenticationRuntime(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>,\n email: TransactionalEmailService,\n options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}\n) {\n const enrollment = createEnrollmentService(database, {\n publicURL: config.publicURL,\n adminRecipients: config.enrollmentAdminNotificationEmails,\n email\n })\n const auth = createBetterAuthAdapter(config, database, enrollment, {\n email: createAuthenticationEmailService(email, config.publicURL),\n ...options\n })\n return { auth, enrollment }\n}\n","import type { CloudAuthAdapter, CloudIdentity } from '#cloud/server/auth/adapter'\n\nexport type CloudActor = {\n userId: string\n email: string\n name: string\n deploymentRole?: 'user' | 'admin'\n}\n\nexport type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>\nexport type CloudSessionResolver = (request: Request) => Promise<CloudActor | null>\n\nexport function createCloudIdentityResolver(auth: CloudAuthAdapter): CloudIdentityResolver {\n return (request) => auth.resolveIdentity(request.headers)\n}\n\nexport function createCloudSessionResolver(auth: CloudAuthAdapter): CloudSessionResolver {\n return (request) => auth.resolveSession(request.headers)\n}\n","import { AdminDomainError } from '#cloud/admin/errors'\nimport {\n containsPattern,\n countEachFilter,\n listSearch,\n listWindow,\n type AdminListQuery,\n type ListFilters\n} from '#cloud/admin/list'\nimport {\n cloudAdminUserFilterSchema,\n type CloudAdminUser,\n type CloudAdminUserDetail,\n type CloudAdminUserFilter\n} from '#cloud/contract'\nimport {\n createSignInActivity,\n type AuthenticationEmailService,\n type CloudAuthAdapter\n} from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { UserPictureService } from '#cloud/server/pictures'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { countBy, keyBy } from 'es-toolkit'\nimport type { ExpressionBuilder, Kysely } from 'kysely'\n\n/** The sign-ins a person's page lists. */\nconst DETAIL_SIGN_INS = 20\n\ntype UserExpression = ExpressionBuilder<CloudDatabase, 'user'>\n\n/** A search for part of a name or email, matched literally and without case. */\nfunction searchCondition(search: string) {\n const pattern = containsPattern(search)\n return (expression: UserExpression) =>\n expression.or([\n expression('user.email', 'ilike', pattern),\n expression('user.name', 'ilike', pattern)\n ])\n}\n\nconst FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {\n all: (expression) => expression.lit(true),\n administrators: (expression) => expression('user.role', '=', 'admin'),\n suspended: (expression) => expression('user.banned', '=', true),\n 'without-two-step': (expression) =>\n expression.and([\n // Better Auth leaves the flag unset on accounts that never turned it on.\n expression('user.twoFactorEnabled', 'is not', true),\n expression.not(\n expression.exists(\n expression\n .selectFrom('passkey')\n .select('passkey.id')\n .whereRef('passkey.userId', '=', 'user.id')\n )\n )\n ])\n}\n\nexport type AdminUserQuery = AdminListQuery<CloudAdminUserFilter>\n\ntype UserRow = {\n id: string\n name: string\n email: string\n image: string | null\n role: string | null\n banned: boolean | null\n banReason: string | null\n twoFactorEnabled: boolean | null\n createdAt: Date | string\n}\n\nexport function createAdminUserService(\n database: Kysely<CloudDatabase>,\n auth: CloudAuthAdapter,\n options: {\n requireMFA?: boolean\n notify?: AuthenticationEmailService\n /** Takes down a person's picture; without it, `removePicture` refuses. */\n pictures?: UserPictureService\n } = {}\n) {\n const activity = createSignInActivity(database)\n\n async function audit(\n actorId: string,\n action: string,\n userId: string,\n metadata: Record<string, unknown> = {}\n ): Promise<void> {\n await database\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action,\n subjectType: 'user',\n subjectId: userId,\n metadata\n })\n .execute()\n }\n\n function refuseSelf(actorId: string, userId: string, action: string): void {\n if (actorId === userId) {\n throw new AdminDomainError(\n 'self_admin_action_forbidden',\n `Administrators cannot ${action} themselves`\n )\n }\n }\n\n async function requireSafeTarget(\n actorId: string,\n userId: string,\n action: 'ban' | 'demote'\n ): Promise<void> {\n refuseSelf(actorId, userId, action)\n const target = await database\n .selectFrom('user')\n .select('role')\n .where('id', '=', userId)\n .executeTakeFirst()\n if (target?.role !== 'admin') return\n const count = await database\n .selectFrom('user')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('role', '=', 'admin')\n .where((expression) =>\n expression.or([expression('banned', '=', false), expression('banned', 'is', null)])\n )\n .executeTakeFirstOrThrow()\n if (Number(count.count) <= 1) {\n throw new AdminDomainError(\n 'last_admin_required',\n 'Cannot remove the last deployment administrator'\n )\n }\n }\n\n /** What the list shows about each account beyond its own row. */\n async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {\n const ids = rows.map((row) => row.id)\n if (ids.length === 0) return []\n const [passkeys, sessions, memberships] = await Promise.all([\n database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),\n database\n .selectFrom('session')\n .select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])\n .where('session.userId', 'in', ids)\n .where('session.expiresAt', '>', new Date())\n .groupBy('session.userId')\n .execute(),\n database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute()\n ])\n const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))\n const lastActive = keyBy(sessions, (session) => session.userId)\n const workspaceCounts = countBy(memberships, (membership) => membership.userId)\n return rows.map((row) => ({\n id: row.id,\n name: row.name,\n email: row.email,\n image: row.image,\n role: row.role ?? undefined,\n banned: row.banned,\n banReason: row.banReason,\n createdAt: dateString(row.createdAt) ?? '',\n twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),\n lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),\n workspaceCount: workspaceCounts[row.id] ?? 0\n }))\n }\n\n const userColumns = [\n 'user.id',\n 'user.name',\n 'user.email',\n 'user.image',\n 'user.role',\n 'user.banned',\n 'user.banReason',\n 'user.twoFactorEnabled',\n 'user.emailVerified',\n 'user.createdAt'\n ] as const\n\n return {\n /** A page of accounts in sign-up order, with how many match the search under each filter. */\n async list(query: AdminUserQuery = {}) {\n const search = listSearch(query)\n const filter = query.filter ?? 'all'\n const { limit, offset } = listWindow(query)\n let searched = database.selectFrom('user')\n if (search) searched = searched.where(searchCondition(search))\n const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)\n const rows = await searched\n .where(FILTERS[filter])\n .select(userColumns)\n .orderBy('user.createdAt')\n .orderBy('user.id')\n .limit(limit)\n .offset(offset)\n .execute()\n return { users: await accountSummaries(rows), total: counts[filter], counts }\n },\n\n /** Everything an administrator reads about one account; null when there is none. */\n async detail(userId: string): Promise<CloudAdminUserDetail | null> {\n const row = await database\n .selectFrom('user')\n .select(userColumns)\n .where('user.id', '=', userId)\n .executeTakeFirst()\n if (!row) return null\n const [[summary], methods, passkeys, sessions, signIns, workspaces] = await Promise.all([\n accountSummaries([row]),\n database\n .selectFrom('account')\n .select(['providerId', 'createdAt'])\n .where('userId', '=', userId)\n .orderBy('createdAt')\n .execute(),\n database\n .selectFrom('passkey')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .where('userId', '=', userId)\n .executeTakeFirstOrThrow(),\n activity.sessions(userId, ''),\n activity.signIns(userId, DETAIL_SIGN_INS),\n database\n .selectFrom('workspaceMember')\n .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')\n .select((expression) => [\n 'workspace.id',\n 'workspace.name',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n expression\n .selectFrom('workspaceMember as member')\n .select(({ fn }) => fn.countAll<number>().as('count'))\n .whereRef('member.workspaceId', '=', 'workspace.id')\n .as('memberCount')\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspaceMember.createdAt')\n .execute()\n ])\n if (!summary) return null\n return {\n user: { ...summary, emailVerified: row.emailVerified },\n methods: methods.map((method) => ({\n provider: method.providerId,\n createdAt: dateString(method.createdAt) ?? ''\n })),\n authenticator: row.twoFactorEnabled === true,\n passkeyCount: Number(passkeys.count),\n sessions,\n signIns,\n workspaces: workspaces.map((workspace) => ({\n id: workspace.id,\n name: workspace.name,\n role: workspace.role,\n memberCount: Number(workspace.memberCount ?? 0),\n joinedAt: dateString(workspace.createdAt) ?? ''\n }))\n }\n },\n\n async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {\n await requireSafeTarget(actorId, userId, 'ban')\n await auth.banUser(headers, userId, reason)\n await audit(actorId, 'user.banned', userId, reason ? { reason } : {})\n },\n async unban(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.unbanUser(headers, userId)\n await audit(actorId, 'user.unbanned', userId)\n },\n async revokeSessions(headers: Headers, actorId: string, userId: string): Promise<void> {\n await auth.revokeUserSessions(headers, userId)\n await audit(actorId, 'user.sessions-revoked', userId)\n },\n async setAdmin(\n headers: Headers,\n actorId: string,\n userId: string,\n enabled: boolean\n ): Promise<void> {\n if (!enabled) await requireSafeTarget(actorId, userId, 'demote')\n if (enabled && options.requireMFA) {\n const user = await database\n .selectFrom('user')\n .select('twoFactorEnabled')\n .where('id', '=', userId)\n .executeTakeFirst()\n const passkey = await database\n .selectFrom('passkey')\n .select('id')\n .where('userId', '=', userId)\n .executeTakeFirst()\n if (!user?.twoFactorEnabled && !passkey) {\n throw new AdminDomainError(\n 'mfa_required',\n 'Users must enroll MFA before becoming deployment administrators'\n )\n }\n }\n await auth.setRole(headers, userId, enabled ? 'admin' : 'user')\n await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)\n },\n\n /**\n * Removes an account's authenticator app, recovery codes, and passkeys, for someone who lost\n * them; they sign in with their password or a linked account and set them up again.\n */\n async resetTwoStep(actorId: string, userId: string): Promise<void> {\n refuseSelf(actorId, userId, 'reset two-step sign-in for')\n const user = await database.transaction().execute(async (transaction) => {\n const target = await transaction\n .selectFrom('user')\n .select(['id', 'email', 'name'])\n .where('id', '=', userId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n await transaction.deleteFrom('twoFactor').where('userId', '=', userId).execute()\n await transaction.deleteFrom('passkey').where('userId', '=', userId).execute()\n await transaction.deleteFrom('mfaAssurance').where('userId', '=', userId).execute()\n await transaction\n .updateTable('user')\n .set({ twoFactorEnabled: false, updatedAt: new Date() })\n .where('id', '=', userId)\n .execute()\n await transaction\n .insertInto('adminAuditEvent')\n .values({\n id: crypto.randomUUID(),\n actorUserId: actorId,\n action: 'user.two-step-reset',\n subjectType: 'user',\n subjectId: userId,\n metadata: {}\n })\n .execute()\n return target\n })\n await options.notify?.sendTwoStepChanged({\n email: user.email,\n name: user.name,\n userId: user.id,\n change: 'reset-by-administrator'\n })\n },\n\n /** Takes down a person's picture, such as one that should not be shown; initials replace it. */\n async removePicture(actorId: string, userId: string): Promise<void> {\n if (!options.pictures) throw new Error('Pictures are not available')\n await database\n .selectFrom('user')\n .select('id')\n .where('id', '=', userId)\n .executeTakeFirstOrThrow()\n await options.pictures.remove(userId)\n await audit(actorId, 'user.picture-removed', userId)\n }\n }\n}\n\nexport type AdminUserService = ReturnType<typeof createAdminUserService>\n","/** The workspace's plan does not include the AI service. */\nexport class AINotEntitledError extends Error {\n constructor() {\n super('The workspace is not entitled to the AI service')\n this.name = 'AINotEntitledError'\n }\n}\n","import { CloudConfigError, type CloudServerConfig } from '#cloud/server/config/schema'\nimport { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK } from 'jose'\n\nconst ALGORITHM = 'ES256'\n\nexport type AISigningKey = {\n privateKey: CryptoKey\n /** The public half, as published in the JWKS. */\n publicJWK: JWK & { kid: string }\n}\n\n/**\n * Imports the P-256 key that signs AI service tokens. Its `kid` is the public key's thumbprint,\n * so replacing the key changes the `kid`, and a service that caches the JWKS refetches it on the\n * first token it cannot match. Tokens the old key signed fail once and are re-requested.\n */\nexport async function importAISigningKey(pem: string): Promise<AISigningKey> {\n const privateKey = await importPKCS8(pem, ALGORITHM, { extractable: true })\n const { kty, crv, x, y } = await exportJWK(privateKey)\n const publicJWK = { kty, crv, x, y }\n const kid = await calculateJwkThumbprint(publicJWK)\n return {\n privateKey: await importPKCS8(pem, ALGORITHM),\n publicJWK: { ...publicJWK, kid, alg: ALGORITHM, use: 'sig' }\n }\n}\n\n/**\n * Imports the configured signing key at startup, so a key that cannot sign stops the runtime\n * instead of failing every token request after discovery has advertised the AI service.\n */\nexport async function loadAISigningKey(\n config: Pick<CloudServerConfig, 'aiSigningKey'>\n): Promise<AISigningKey | undefined> {\n if (!config.aiSigningKey) return undefined\n try {\n return await importAISigningKey(config.aiSigningKey)\n } catch {\n throw new CloudConfigError('AI signing key must be a PKCS #8 P-256 private key')\n }\n}\n\nexport const AI_SIGNING_ALGORITHM = ALGORITHM\n","import type {\n DocumentAccess,\n DocumentAccessSource,\n DocumentPermission,\n WorkspaceRole\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { maxBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type AccessDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nconst PERMISSION_WEIGHT: Record<DocumentPermission, number> = { view: 1, edit: 2 }\n\nfunction workspacePermission(role: WorkspaceRole): DocumentPermission {\n return role === 'viewer' ? 'view' : 'edit'\n}\n\nexport async function resolveDocumentAccess(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<DocumentAccess | undefined> {\n const document = await database\n .selectFrom('document')\n .leftJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .leftJoin('documentGrant', (join) =>\n join\n .onRef('documentGrant.documentId', '=', 'document.id')\n .on('documentGrant.userId', '=', userId)\n .on('documentGrant.revokedAt', 'is', null)\n )\n .select([\n 'document.createdBy',\n 'workspaceMember.role as workspaceRole',\n 'documentGrant.permission as grantPermission'\n ])\n .where('document.id', '=', documentId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) return undefined\n\n const sources: DocumentAccessSource[] = []\n const candidates: DocumentPermission[] = []\n const owner = document.createdBy === userId\n if (owner) {\n sources.push('owner')\n candidates.push('edit')\n }\n if (document.workspaceRole) {\n sources.push('workspace')\n candidates.push(workspacePermission(document.workspaceRole))\n }\n if (document.grantPermission) {\n sources.push('direct-grant')\n candidates.push(document.grantPermission)\n }\n const permission = maxBy(candidates, (candidate) => PERMISSION_WEIGHT[candidate])\n if (!permission) return undefined\n const workspaceCanManage =\n document.workspaceRole === 'admin' || document.workspaceRole === 'editor'\n return {\n permission,\n canManageSharing: owner || workspaceCanManage || document.grantPermission === 'edit',\n sources\n }\n}\n\nexport function canEditDocument(access: DocumentAccess): boolean {\n return access.permission === 'edit'\n}\n\n/**\n * Removing a document belongs to its owner and its workspace's admins and editors. A direct grant\n * or an accepted invitation lets someone edit, never delete the owner's document.\n */\nexport async function canDeleteDocument(\n database: AccessDatabase,\n userId: string,\n documentId: string\n): Promise<boolean> {\n const document = await database\n .selectFrom('document')\n .leftJoin('workspaceMember', (join) =>\n join\n .onRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .on('workspaceMember.userId', '=', userId)\n )\n .select(['document.createdBy', 'workspaceMember.role as workspaceRole'])\n .where('document.id', '=', documentId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) return false\n return (\n document.createdBy === userId ||\n document.workspaceRole === 'admin' ||\n document.workspaceRole === 'editor'\n )\n}\n","/** The document does not exist, or the person may not know it does. */\nexport class DocumentNotFoundError extends Error {\n override readonly name = 'DocumentNotFoundError'\n}\n/** The person may see the document but not do this to it. */\nexport class DocumentForbiddenError extends Error {\n override readonly name = 'DocumentForbiddenError'\n}\n/** A save named a base revision the document has moved on from. */\nexport class DocumentConflictError extends Error {\n override readonly name = 'DocumentConflictError'\n}\n/** An upload is not the file it declared, or no longer one that can land. */\nexport class UploadInvalidError extends Error {\n override readonly name = 'UploadInvalidError'\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport class StorageQuotaExceededError extends Error {\n override readonly name = 'StorageQuotaExceededError'\n}\n\nexport type StorageQuotaSnapshot = {\n committedBytes: number\n reservedBytes: number\n}\n\ntype StorageDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport function createStorageQuotaService(database: Kysely<CloudDatabase>) {\n async function snapshot(\n executor: StorageDatabase,\n workspaceId: string,\n now = new Date()\n ): Promise<StorageQuotaSnapshot> {\n const [usage, reservation] = await Promise.all([\n executor\n .selectFrom('workspaceStorageUsage')\n .select('committedBytes')\n .where('workspaceId', '=', workspaceId)\n .executeTakeFirst(),\n executor\n .selectFrom('uploadStorageReservation')\n .select((expression) =>\n expression.fn.coalesce(expression.fn.sum('bytes'), expression.val(0)).as('reservedBytes')\n )\n .where('workspaceId', '=', workspaceId)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .where('expiresAt', '>', now)\n .executeTakeFirstOrThrow()\n ])\n return {\n committedBytes: Number(usage?.committedBytes ?? 0),\n reservedBytes: Number(reservation.reservedBytes)\n }\n }\n\n async function reserve(\n executor: StorageDatabase,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n await executor\n .insertInto('workspaceStorageUsage')\n .values({ workspaceId: input.workspaceId, committedBytes: 0 })\n .onConflict((conflict) => conflict.column('workspaceId').doNothing())\n .execute()\n await executor\n .selectFrom('workspaceStorageUsage')\n .select('workspaceId')\n .where('workspaceId', '=', input.workspaceId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const usage = await snapshot(executor, input.workspaceId)\n if (\n input.maximumBytes !== null &&\n usage.committedBytes + usage.reservedBytes + input.bytes > input.maximumBytes\n ) {\n throw new StorageQuotaExceededError('Workspace storage quota exceeded')\n }\n await executor\n .insertInto('uploadStorageReservation')\n .values({\n id: crypto.randomUUID(),\n workspaceId: input.workspaceId,\n uploadId: input.uploadId,\n bytes: input.bytes,\n expiresAt: input.expiresAt,\n committedAt: null,\n releasedAt: null\n })\n .onConflict((conflict) => conflict.column('uploadId').doNothing())\n .execute()\n }\n\n async function commit(executor: StorageDatabase, uploadId: string): Promise<void> {\n const reservation = await executor\n .selectFrom('uploadStorageReservation')\n .select(['id', 'workspaceId', 'bytes', 'committedAt', 'releasedAt'])\n .where('uploadId', '=', uploadId)\n .forUpdate()\n .executeTakeFirst()\n if (!reservation || reservation.committedAt || reservation.releasedAt) return\n await executor\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) =>\n expression('committedBytes', '+', Number(reservation.bytes)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', reservation.workspaceId)\n .execute()\n await executor\n .updateTable('uploadStorageReservation')\n .set({ committedAt: new Date() })\n .where('id', '=', reservation.id)\n .execute()\n }\n\n async function release(executor: StorageDatabase, uploadId: string): Promise<void> {\n await executor\n .updateTable('uploadStorageReservation')\n .set({ releasedAt: new Date() })\n .where('uploadId', '=', uploadId)\n .where('committedAt', 'is', null)\n .where('releasedAt', 'is', null)\n .execute()\n }\n\n return {\n snapshot: (workspaceId: string) => snapshot(database, workspaceId),\n\n async reserve(input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<void> {\n await database.transaction().execute((transaction) => reserve(transaction, input))\n },\n\n reserveInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n workspaceId: string\n uploadId: string\n bytes: number\n expiresAt: Date\n maximumBytes: number | null\n }\n ): Promise<void> {\n return reserve(transaction, input)\n },\n\n async commit(uploadId: string): Promise<void> {\n await database.transaction().execute((transaction) => commit(transaction, uploadId))\n },\n\n commitInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return commit(transaction, uploadId)\n },\n\n async release(uploadId: string): Promise<void> {\n await release(database, uploadId)\n },\n\n releaseInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {\n return release(transaction, uploadId)\n }\n }\n}\n\nexport type StorageQuotaService = ReturnType<typeof createStorageQuotaService>\n","import {\n parseCommitImageUploads,\n parseCommitUpload,\n parseCreateDocument,\n parseCreateUpload,\n parseRequestImageLinks,\n parseRequestImageUploads\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport type { DocumentService } from '#cloud/server/documents/service'\nimport { StorageQuotaExceededError } from '#cloud/server/quota'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport {\n documentParams,\n uploadParams,\n validatedJSON,\n workspaceParams\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type DocumentRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** The response a document domain error stands for, or null for any other error. */\nexport function documentDomainError(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof DocumentConflictError) {\n return context.json({ error: { code: 'revision_conflict' as const } }, 409)\n }\n if (error instanceof StorageQuotaExceededError) {\n return context.json({ error: { code: 'storage_quota_exceeded' as const } }, 409)\n }\n if (error instanceof UploadInvalidError) {\n return context.json({ error: { code: 'invalid_upload' as const } }, 422)\n }\n return null\n}\n\n/** Answers with what `respond` gives, or with the response a document domain error stands for. */\nasync function documentResponse<T extends Response>(\n context: Context,\n respond: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await respond()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\nexport function createDocumentRoutes(\n service: DocumentService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<DocumentRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/workspaces/:workspaceId/documents',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.documentCreation,\n routeParamResource('workspaceId'),\n (context) => context.req.method !== 'POST'\n )\n )\n router.use(\n '/documents/:documentId/images',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n router.use(\n '/documents/:documentId/uploads',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.uploadCreation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .get('/shared-documents', async (context) =>\n context.json({ documents: await service.listShared(context.get('actor').userId) })\n )\n .get('/workspaces/:workspaceId/documents', workspaceParams, async (context) => {\n const documents = await service.list(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n if (!documents) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ documents })\n })\n .get('/workspaces/:workspaceId/usage', workspaceParams, async (context) => {\n try {\n return context.json({\n usage: await service.usage(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .post(\n '/workspaces/:workspaceId/documents',\n workspaceParams,\n validatedJSON(parseCreateDocument),\n async (context) => {\n try {\n const document = await service.create(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json')\n )\n return context.json({ document }, 201)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n }\n )\n .delete('/documents/:documentId', documentParams, async (context) => {\n try {\n await service.remove(context.get('actor').userId, context.req.valid('param').documentId)\n return context.body(null, 204)\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n })\n .get('/documents/:documentId/access', documentParams, (context) =>\n documentResponse(context, async () =>\n context.json({\n access: await service.access(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .get('/documents/:documentId', documentParams, (context) =>\n documentResponse(context, async () =>\n context.json({\n document: await service.download(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/uploads',\n documentParams,\n validatedJSON(parseCreateUpload),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.createUpload(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/documents/:documentId/images/commit',\n documentParams,\n validatedJSON(parseCommitImageUploads),\n (context) =>\n documentResponse(context, async () => {\n await service.commitImageUploads(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json').uploads\n )\n return context.body(null, 204)\n })\n )\n .post(\n '/documents/:documentId/images/links',\n documentParams,\n validatedJSON(parseRequestImageLinks),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.imageLinks(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json').checksums\n )\n )\n )\n )\n .post(\n '/documents/:documentId/images',\n documentParams,\n validatedJSON(parseRequestImageUploads),\n (context) =>\n documentResponse(context, async () =>\n context.json(\n await service.requestImageUploads(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/uploads/:uploadId/commit',\n uploadParams,\n validatedJSON(parseCommitUpload),\n async (context) => {\n try {\n const document = await service.commitUpload(\n context.get('actor').userId,\n context.req.valid('param').uploadId,\n context.req.valid('json')\n )\n return context.json({ document })\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ExpressionBuilder } from 'kysely'\n\n/**\n * No revision refers to the stored file any more, no workspace keeps it as an image, and no\n * collaboration room keeps it as its snapshot, so it can leave the object store.\n */\nexport function unreferencedObject(expression: ExpressionBuilder<CloudDatabase, 'storageObject'>) {\n return expression.and([\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision')\n .select('documentRevision.id')\n .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceImage')\n .select('workspaceImage.checksum')\n .whereRef('workspaceImage.storageObjectId', '=', 'storageObject.id')\n )\n ),\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRoomSnapshot')\n .select('documentRoomSnapshot.documentId')\n .whereRef('documentRoomSnapshot.snapshotObjectId', '=', 'storageObject.id')\n )\n )\n ])\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { Kysely } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\nexport type DocumentCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n retentionMs: number\n now?: Date\n}\n\nexport type DocumentCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n objectsDeleted: number\n bytesReclaimed: number\n}\n\nexport type DocumentCleanupService = {\n cleanupDeletedDocuments(options: DocumentCleanupOptions): Promise<DocumentCleanupResult>\n}\n\ntype ClaimedDocument = {\n id: string\n workspaceId: string\n deletedAt: Date\n}\n\ntype StoredRevisionObject = {\n id: string\n objectKey: string\n byteSize: number\n}\n\nexport function createDocumentCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore\n): DocumentCleanupService {\n return {\n async cleanupDeletedDocuments(options) {\n const now = options.now ?? new Date()\n const retentionBefore = new Date(now.getTime() - options.retentionMs)\n const staleBefore = new Date(now.getTime() - options.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const documents = await claimDocuments(\n database,\n options.batchSize,\n retentionBefore,\n staleBefore,\n now,\n claimId\n )\n const result: DocumentCleanupResult = {\n claimed: documents.length,\n cleaned: 0,\n failed: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0\n }\n for (const document of documents) {\n try {\n const revisionObjects = await documentObjects(database, document.id)\n for (const object of revisionObjects) await objects.delete(object.objectKey)\n const reclaimed = await removeDocumentMetadata(\n database,\n document,\n revisionObjects,\n retentionBefore,\n claimId\n )\n if (!reclaimed) continue\n result.cleaned++\n result.objectsDeleted += reclaimed.objectsDeleted\n result.bytesReclaimed += reclaimed.bytesReclaimed\n } catch {\n result.failed++\n await releaseClaim(database, document.id, claimId)\n }\n }\n return result\n }\n }\n}\n\nasync function claimDocuments(\n database: Kysely<CloudDatabase>,\n batchSize: number,\n retentionBefore: Date,\n staleBefore: Date,\n now: Date,\n claimId: string\n): Promise<ClaimedDocument[]> {\n return database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('document')\n .select(['id', 'workspaceId', 'deletedAt'])\n .where('deletedAt', 'is not', null)\n .where('deletedAt', '<=', retentionBefore)\n .where((expression) =>\n expression.or([\n expression('cleanupClaimId', 'is', null),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('upload')\n .select('upload.id')\n .whereRef('upload.documentId', '=', 'document.id')\n .where('upload.status', 'in', ['pending', 'cleaning'])\n )\n )\n )\n .orderBy('deletedAt')\n .limit(batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n const claimed = candidates.filter(\n (document): document is ClaimedDocument => document.deletedAt !== null\n )\n if (claimed.length === 0) return []\n await transaction\n .updateTable('document')\n .set({ cleanupClaimId: claimId, cleanupClaimedAt: now })\n .where(\n 'id',\n 'in',\n claimed.map((document) => document.id)\n )\n .execute()\n return claimed\n })\n}\n\nasync function documentObjects(\n database: Kysely<CloudDatabase>,\n documentId: string\n): Promise<StoredRevisionObject[]> {\n const rows = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select(['storageObject.id', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('documentRevision.documentId', '=', documentId)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentRevision as otherRevision')\n .select('otherRevision.id')\n .whereRef('otherRevision.storageObjectId', '=', 'storageObject.id')\n .where('otherRevision.documentId', '!=', documentId)\n )\n )\n )\n .execute()\n return rows.map((row) => ({ ...row, byteSize: Number(row.byteSize) }))\n}\n\nasync function removeDocumentMetadata(\n database: Kysely<CloudDatabase>,\n document: ClaimedDocument,\n objects: StoredRevisionObject[],\n retentionBefore: Date,\n claimId: string\n): Promise<{ objectsDeleted: number; bytesReclaimed: number } | null> {\n return database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'cleanupClaimId'])\n .where('id', '=', document.id)\n .forUpdate()\n .executeTakeFirst()\n if (\n !locked?.deletedAt ||\n locked.deletedAt > retentionBefore ||\n locked.cleanupClaimId !== claimId\n ) {\n return null\n }\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: null })\n .where('id', '=', document.id)\n .execute()\n await transaction.deleteFrom('documentRevision').where('documentId', '=', document.id).execute()\n let objectsDeleted = 0\n let bytesReclaimed = 0\n for (const object of objects) {\n const deleted = await transaction\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .executeTakeFirst()\n if (Number(deleted.numDeletedRows) > 0) {\n objectsDeleted++\n bytesReclaimed += object.byteSize\n }\n }\n if (bytesReclaimed > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', bytesReclaimed),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', document.workspaceId)\n .execute()\n }\n await transaction.deleteFrom('document').where('id', '=', document.id).execute()\n return { objectsDeleted, bytesReclaimed }\n })\n}\n\nasync function releaseClaim(\n database: Kysely<CloudDatabase>,\n documentId: string,\n claimId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ cleanupClaimId: null, cleanupClaimedAt: null })\n .where('id', '=', documentId)\n .where('cleanupClaimId', '=', claimId)\n .execute()\n}\n","import type {\n CommitUploadInput,\n DocumentImageDownload,\n DocumentImageLink,\n ImageUploadOffer,\n RequestImageUploadsInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { StorageQuotaService } from '#cloud/server/quota'\nimport { uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\n/** Images are stored as the bytes their file holds, whatever format those are. */\nexport const IMAGE_CONTENT_TYPE = 'application/octet-stream'\n\ntype Executor = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\n/** An image no revision has used for this long may be released; a save uploads first. */\nexport const IMAGE_RELEASE_GRACE_MS = 24 * 60 * 60_000\n\n/**\n * The images a workspace's documents use, each stored once under the SHA-256 the object store\n * verified, and which of them each stored revision uses under the names its file gives them.\n */\nexport function createDocumentImages(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n quota: StorageQuotaService\n) {\n /**\n * Gives up uploads a request reserved when it could not offer them all, so a retry is not\n * refused for space they hold. A multipart upload the store began is aborted first; one that\n * cannot be stays pending for cleanup, which aborts it once it expires.\n */\n async function abandonUploads(\n uploads: readonly { uploadId: string; objectKey: string }[],\n offers: readonly ImageUploadOffer[]\n ): Promise<void> {\n const begun = new Map(offers.map((offer) => [offer.uploadId, offer.upload]))\n for (const { uploadId, objectKey } of uploads) {\n try {\n const upload = begun.get(uploadId)\n if (upload?.kind === 'multipart') {\n await objects.abortUpload({ key: objectKey, uploadId: upload.uploadId })\n }\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .where('status', '=', 'pending')\n .execute()\n } catch (error) {\n // Cleanup releases it once it expires.\n console.warn('Giving up an image upload failed', error)\n }\n }\n }\n\n return {\n /**\n * Uploads for the images of `input` the workspace lacks, each with its own object key and\n * reservation, so an abandoned one is cleaned up like any other upload. Images it holds\n * already need nothing.\n */\n async requestUploads(input: {\n userId: string\n documentId: string\n workspaceId: string\n images: RequestImageUploadsInput['images']\n expiresAt: Date\n maximumBytes: number | null\n }): Promise<ImageUploadOffer[]> {\n const requested = uniqBy(input.images, (image) => image.checksum)\n // Held images are renewed, so none is released before the save that asked commits.\n const held = new Set(\n (\n await database\n .updateTable('workspaceImage')\n .set({ touchedAt: new Date() })\n .where('workspaceId', '=', input.workspaceId)\n .where(\n 'checksum',\n 'in',\n requested.map((image) => image.checksum)\n )\n .returning('checksum')\n .execute()\n ).map((row) => row.checksum)\n )\n const missing = requested\n .filter((image) => !held.has(image.checksum))\n .map((image) => {\n const uploadId = crypto.randomUUID()\n return {\n ...image,\n uploadId,\n objectKey: `documents/${input.workspaceId}/images/${uploadId}`\n }\n })\n if (missing.length === 0) return []\n await database.transaction().execute(async (transaction) => {\n for (const image of missing) {\n await transaction\n .insertInto('upload')\n .values({\n id: image.uploadId,\n kind: 'image',\n documentId: input.documentId,\n baseRevisionId: null,\n objectKey: image.objectKey,\n checksum: image.checksum,\n byteSize: image.byteSize,\n contentType: IMAGE_CONTENT_TYPE,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: input.userId,\n expiresAt: input.expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: input.workspaceId,\n uploadId: image.uploadId,\n bytes: image.byteSize,\n expiresAt: input.expiresAt,\n maximumBytes: input.maximumBytes\n })\n }\n })\n const offers: ImageUploadOffer[] = []\n try {\n for (const image of missing) {\n const upload = await objects.createUpload({\n key: image.objectKey,\n byteSize: image.byteSize,\n checksum: image.checksum,\n contentType: IMAGE_CONTENT_TYPE,\n expiresAt: input.expiresAt\n })\n offers.push({ checksum: image.checksum, uploadId: image.uploadId, upload })\n if (upload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: upload.uploadId })\n .where('id', '=', image.uploadId)\n .execute()\n }\n }\n } catch (error) {\n await abandonUploads(missing, offers)\n throw error\n }\n return offers\n },\n\n /**\n * Stores a verified image upload as the workspace's copy of that image. When another upload of\n * the same bytes got there first, this one's file is left unreferenced for cleanup to delete\n * and its reservation is released rather than counted twice.\n */\n async landInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: {\n uploadId: string\n workspaceId: string\n objectKey: string\n stored: { checksum: string; byteSize: number; contentType: string }\n }\n ): Promise<void> {\n const storageObjectId = crypto.randomUUID()\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: input.objectKey,\n checksum: input.stored.checksum,\n byteSize: input.stored.byteSize,\n contentType: input.stored.contentType\n })\n .execute()\n const landed = await transaction\n .insertInto('workspaceImage')\n .values({\n workspaceId: input.workspaceId,\n checksum: input.stored.checksum,\n storageObjectId\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'checksum']).doNothing())\n .returning('checksum')\n .executeTakeFirst()\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', input.uploadId)\n .execute()\n if (landed) await quota.commitInTransaction(transaction, input.uploadId)\n else await quota.releaseInTransaction(transaction, input.uploadId)\n },\n\n /**\n * Records the images a new revision uses. Each must be the workspace's already; holding them\n * until the revision refers to them keeps a release of an unused image from racing the save.\n * Whether every image was there.\n */\n async attachInTransaction(\n transaction: Transaction<CloudDatabase>,\n input: { workspaceId: string; revisionId: string; images: CommitUploadInput['images'] }\n ): Promise<boolean> {\n const images = uniqBy(input.images, (image) => image.name)\n if (images.length === 0) return true\n const checksums = uniq(images.map((image) => image.checksum))\n const held = await transaction\n .selectFrom('workspaceImage')\n .select('checksum')\n .where('workspaceId', '=', input.workspaceId)\n .where('checksum', 'in', checksums)\n .forShare()\n .execute()\n if (held.length !== checksums.length) return false\n await transaction\n .insertInto('revisionImage')\n .values(\n images.map((image) => ({\n revisionId: input.revisionId,\n name: image.name,\n workspaceId: input.workspaceId,\n checksum: image.checksum\n }))\n )\n .execute()\n return true\n }\n }\n}\n\nexport type DocumentImages = ReturnType<typeof createDocumentImages>\n\n/** Gives a revision made from another, by a restore or a duplicate, the same images. */\nexport async function copyRevisionImages(\n transaction: Transaction<CloudDatabase>,\n fromRevisionId: string,\n toRevisionId: string\n): Promise<void> {\n await transaction\n .insertInto('revisionImage')\n .columns(['revisionId', 'name', 'workspaceId', 'checksum'])\n .expression((expression) =>\n expression\n .selectFrom('revisionImage')\n .select((select) => [\n select.val(toRevisionId).as('revisionId'),\n 'name',\n 'workspaceId',\n 'checksum'\n ])\n .where('revisionId', '=', fromRevisionId)\n )\n .execute()\n}\n\n/** Where to download each image a revision uses, under its name in the file. */\nexport async function revisionImageDownloads(\n executor: Executor,\n objects: ObjectStore,\n revisionId: string,\n expiresAt: Date\n): Promise<DocumentImageDownload[]> {\n const rows = await executor\n .selectFrom('revisionImage')\n .innerJoin('workspaceImage', (join) =>\n join\n .onRef('workspaceImage.workspaceId', '=', 'revisionImage.workspaceId')\n .onRef('workspaceImage.checksum', '=', 'revisionImage.checksum')\n )\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select([\n 'revisionImage.name',\n 'revisionImage.checksum',\n 'storageObject.objectKey',\n 'storageObject.byteSize'\n ])\n .where('revisionImage.revisionId', '=', revisionId)\n .orderBy('revisionImage.name')\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n name: row.name,\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt })\n }))\n )\n}\n\n/**\n * Releases up to `batchSize` images no revision uses that no save has asked for since `before`:\n * their bytes go back to the workspace's usage, and their files, no longer anyone's, are left for\n * the object sweep. A save holds the images it refers to, so it either lands first and keeps them\n * or finds them gone and uploads them again. How many were released and their bytes.\n */\nexport async function releaseUnusedImages(\n database: Kysely<CloudDatabase>,\n before: Date,\n batchSize: number\n): Promise<{ released: number; bytes: number }> {\n return database.transaction().execute(async (transaction) => {\n const unused = await transaction\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.workspaceId', 'workspaceImage.checksum', 'storageObject.byteSize'])\n .where('workspaceImage.touchedAt', '<', before)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n )\n )\n )\n .limit(batchSize)\n .forUpdate('workspaceImage')\n .skipLocked()\n .execute()\n let bytes = 0\n for (const image of unused) {\n await transaction\n .deleteFrom('workspaceImage')\n .where('workspaceId', '=', image.workspaceId)\n .where('checksum', '=', image.checksum)\n .execute()\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', Number(image.byteSize)),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', image.workspaceId)\n .execute()\n bytes += Number(image.byteSize)\n }\n return { released: unused.length, bytes }\n })\n}\n\n/**\n * Where to download the images of `checksums` the document's workspace holds, for someone who may\n * view the document. A live room names images by checksum before any save does, and an editor\n * whose image the workspace already holds through another document uploads nothing for this one,\n * so the workspace, not the document, is what an image belongs to. Asking needs the image's\n * SHA-256, which only someone with its bytes has.\n */\nexport async function documentImageLinks(\n executor: Executor,\n objects: ObjectStore,\n input: { documentId: string; checksums: string[]; expiresAt: Date }\n): Promise<DocumentImageLink[]> {\n const rows = await executor\n .selectFrom('workspaceImage')\n .innerJoin('document', 'document.workspaceId', 'workspaceImage.workspaceId')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select(['workspaceImage.checksum', 'storageObject.objectKey', 'storageObject.byteSize'])\n .where('document.id', '=', input.documentId)\n .where('workspaceImage.checksum', 'in', uniq(input.checksums))\n .execute()\n return Promise.all(\n rows.map(async (row) => ({\n checksum: row.checksum,\n byteSize: Number(row.byteSize),\n download: await objects.createDownload({ key: row.objectKey, expiresAt: input.expiresAt })\n }))\n )\n}\n\n/** The images the workspace's current revisions use, each counted once however many use it. */\nexport async function currentImageUsage(\n executor: Executor,\n workspaceId: string\n): Promise<{ objectCount: number; bytesUsed: number }> {\n const usage = await executor\n .selectFrom('workspaceImage')\n .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')\n .select((expression) => [\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('workspaceImage.workspaceId', '=', workspaceId)\n .where((expression) =>\n expression.exists(\n expression\n .selectFrom('revisionImage')\n .innerJoin('document', 'document.currentRevisionId', 'revisionImage.revisionId')\n .select('revisionImage.name')\n .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')\n .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')\n .where('document.deletedAt', 'is', null)\n )\n )\n .executeTakeFirstOrThrow()\n return { objectCount: Number(usage.objectCount), bytesUsed: Number(usage.bytesUsed) }\n}\n","import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\n\n/** How far back a workspace without full revision history keeps its versions. */\nexport const LIMITED_HISTORY_DAYS = 30\n\n/**\n * The oldest moment a workspace's history reaches, or null when it keeps everything: with the\n * `revisionHistory` entitlement off, only the last 30 days, as on a free plan.\n */\nexport async function historyStart(\n policy: CloudPolicy | undefined,\n deploymentMode: CloudPolicyContext['deploymentMode'],\n workspaceId: string,\n now: Date\n): Promise<Date | null> {\n const full = policy\n ? await policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, true, {\n targetingKey: workspaceId,\n workspaceId,\n deploymentMode\n })\n : true\n return full ? null : new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { IMAGE_RELEASE_GRACE_MS, releaseUnusedImages } from '#cloud/server/documents/images'\nimport { historyStart, LIMITED_HISTORY_DAYS } from '#cloud/server/documents/versions/history'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { groupBy, sumBy, uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { unreferencedObject } from './objects'\n\n/** How long a save between versions is kept before compaction may delete it. */\nexport const REVISION_COMPACTION_GRACE_MS = 24 * 60 * 60_000\n/**\n * How long a stored file nothing refers to is left alone: a collaboration room records its next\n * snapshot's file before writing it and points the room at it moments later.\n */\nexport const OBJECT_SWEEP_GRACE_MS = 15 * 60_000\n\nexport type RevisionCompactionOptions = {\n batchSize: number\n /** How long a save stays before it can be compacted, so recent work is never lost to it. */\n graceMs: number\n now?: Date\n}\n\nexport type RevisionCompactionResult = {\n versionsPruned: number\n /** Images no revision used any more, released after their grace period. */\n imagesReleased: number\n revisionsDeleted: number\n objectsDeleted: number\n bytesReclaimed: number\n failed: number\n}\n\nexport type RevisionCompactionService = {\n compactRevisions(options: RevisionCompactionOptions): Promise<RevisionCompactionResult>\n}\n\n/**\n * Keeps a document's stored history to its versions. A save that is neither the document's\n * current state nor kept by a version is deleted once it is older than the grace period, and its\n * file with it when nothing else uses it; a workspace without full history first loses the\n * versions older than its 30 days.\n */\nexport function createRevisionCompactionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: { policy?: CloudPolicy; deploymentMode?: CloudPolicyContext['deploymentMode'] } = {}\n): RevisionCompactionService {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n async function pruneVersions(now: Date, batchSize: number): Promise<number> {\n if (!options.policy) return 0\n const limitedBefore = new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)\n const workspaces = await database\n .selectFrom('documentVersion')\n .innerJoin('document', 'document.id', 'documentVersion.documentId')\n .select('document.workspaceId')\n .distinct()\n .where('documentVersion.createdAt', '<', limitedBefore)\n .execute()\n let pruned = 0\n for (const { workspaceId } of workspaces) {\n const start = await historyStart(options.policy, deploymentMode, workspaceId, now)\n if (!start) continue\n const deleted = await database\n .deleteFrom('documentVersion')\n .where('id', 'in', (query) =>\n query\n .selectFrom('documentVersion as version')\n .innerJoin('document', 'document.id', 'version.documentId')\n .select('version.id')\n .where('document.workspaceId', '=', workspaceId)\n .where('version.createdAt', '<', start)\n // The document's current state stays listed however old it is.\n .whereRef('version.revisionId', '!=', 'document.currentRevisionId')\n .limit(batchSize)\n )\n .executeTakeFirst()\n pruned += Number(deleted.numDeletedRows)\n }\n return pruned\n }\n\n /** Saves that may go: old, unversioned, not current, in a document that is not deleted. */\n function compactable(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>, before: Date) {\n return source\n .selectFrom('documentRevision')\n .innerJoin('document', 'document.id', 'documentRevision.documentId')\n .where('documentRevision.createdAt', '<', before)\n .where('document.deletedAt', 'is', null)\n .where((expression) =>\n expression.or([\n expression('document.currentRevisionId', 'is', null),\n expression('document.currentRevisionId', '!=', expression.ref('documentRevision.id'))\n ])\n )\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('documentVersion')\n .select('documentVersion.id')\n .whereRef('documentVersion.revisionId', '=', 'documentRevision.id')\n )\n )\n )\n }\n\n /** A file no revision refers to: freed by compaction, waiting for the object store. */\n function unreferencedObjects(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>) {\n return source.selectFrom('storageObject').where(unreferencedObject)\n }\n\n /**\n * Deletes up to `limit` compactable saves of one document and returns the bytes of files nothing\n * refers to any more to the workspace's usage. Their rows stay until the files are gone, so a\n * delete that fails is tried again on the next pass.\n */\n async function compactDocument(\n documentId: string,\n workspaceId: string,\n before: Date,\n limit: number\n ) {\n return database.transaction().execute(async (transaction) => {\n // Saves and restores lock the document too, so none can keep a revision deleted here.\n await transaction\n .selectFrom('document')\n .select('id')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n const revisions = await compactable(transaction, before)\n .select(['documentRevision.id', 'documentRevision.storageObjectId'])\n .where('documentRevision.documentId', '=', documentId)\n .limit(limit)\n .execute()\n if (revisions.length === 0) return { revisions: 0, bytes: 0 }\n await transaction\n .deleteFrom('documentRevision')\n .where(\n 'id',\n 'in',\n revisions.map((revision) => revision.id)\n )\n .execute()\n const freed = await unreferencedObjects(transaction)\n .select('byteSize')\n .where('id', 'in', uniq(revisions.map((revision) => revision.storageObjectId)))\n .execute()\n const bytes = sumBy(freed, (object) => Number(object.byteSize))\n if (bytes > 0) {\n await transaction\n .updateTable('workspaceStorageUsage')\n .set({\n committedBytes: (expression) => expression('committedBytes', '-', bytes),\n updatedAt: new Date()\n })\n .where('workspaceId', '=', workspaceId)\n .execute()\n }\n return { revisions: revisions.length, bytes }\n })\n }\n\n /** Deletes freed files from the object store, then their rows; a failure stays for next time. */\n async function sweepObjects(now: Date, batchSize: number, result: RevisionCompactionResult) {\n const freed = await unreferencedObjects(database)\n .select(['id', 'objectKey'])\n .where('createdAt', '<', new Date(now.getTime() - OBJECT_SWEEP_GRACE_MS))\n .limit(batchSize)\n .execute()\n for (const object of freed) {\n try {\n await objects.delete(object.objectKey)\n await database\n .deleteFrom('storageObject')\n .where('id', '=', object.id)\n .where(unreferencedObject)\n .execute()\n result.objectsDeleted++\n } catch {\n result.failed++\n }\n }\n }\n\n return {\n async compactRevisions(input) {\n const now = input.now ?? new Date()\n const before = new Date(now.getTime() - input.graceMs)\n const result: RevisionCompactionResult = {\n versionsPruned: await pruneVersions(now, input.batchSize),\n imagesReleased: 0,\n revisionsDeleted: 0,\n objectsDeleted: 0,\n bytesReclaimed: 0,\n failed: 0\n }\n const candidates = await compactable(database, before)\n .select(['documentRevision.documentId', 'document.workspaceId'])\n .limit(input.batchSize)\n .execute()\n let capacity = input.batchSize\n for (const [documentId, rows] of Object.entries(\n groupBy(candidates, (row) => row.documentId)\n )) {\n const workspaceId = rows[0]?.workspaceId\n if (!workspaceId || capacity <= 0) continue\n try {\n const compacted = await compactDocument(documentId, workspaceId, before, capacity)\n capacity -= compacted.revisions\n result.revisionsDeleted += compacted.revisions\n result.bytesReclaimed += compacted.bytes\n } catch {\n result.failed++\n }\n }\n // Compaction just freed the images of the saves it deleted; the release lets their grace pass.\n // A release that raced a save referring to an image fails whole and is tried next time.\n try {\n const images = await releaseUnusedImages(\n database,\n new Date(now.getTime() - IMAGE_RELEASE_GRACE_MS),\n input.batchSize\n )\n result.imagesReleased = images.released\n result.bytesReclaimed += images.bytes\n } catch {\n result.failed++\n }\n await sweepObjects(now, input.batchSize, result)\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nexport type UploadCleanupOptions = {\n batchSize: number\n leaseDurationMs: number\n now?: Date\n}\n\nexport type UploadCleanupResult = {\n claimed: number\n cleaned: number\n failed: number\n}\n\nexport type UploadCleanupService = {\n cleanupExpiredUploads(options: UploadCleanupOptions): Promise<UploadCleanupResult>\n}\n\ntype ClaimedUpload = {\n id: string\n objectKey: string\n multipartUploadId: string | null\n}\n\nexport function createUploadCleanupService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore\n): UploadCleanupService {\n const quota = createStorageQuotaService(database)\n return {\n async cleanupExpiredUploads(options) {\n const now = options.now ?? new Date()\n const staleBefore = new Date(now.getTime() - options.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const uploads = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('upload')\n .select(['id', 'objectKey', 'multipartUploadId'])\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('expiresAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'finalizing'),\n expression('finalizationStartedAt', '<=', staleBefore)\n ]),\n expression.and([\n expression('status', '=', 'cleaning'),\n expression('cleanupClaimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('expiresAt')\n .limit(options.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n const ids = candidates.map((upload) => upload.id)\n await transaction\n .updateTable('upload')\n .set({\n status: 'cleaning',\n finalizationStartedAt: null,\n cleanupClaimId: claimId,\n cleanupClaimedAt: now\n })\n .where('id', 'in', ids)\n .execute()\n return candidates\n })\n\n let cleaned = 0\n let failed = 0\n for (const upload of uploads) {\n try {\n await removeUploadObject(objects, upload)\n const result = await database\n .updateTable('upload')\n .set({\n status: 'abandoned',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) > 0) {\n await quota.release(upload.id)\n cleaned++\n }\n } catch {\n failed++\n await database\n .updateTable('upload')\n .set({\n status: 'pending',\n finalizationStartedAt: null,\n cleanupClaimId: null,\n cleanupClaimedAt: null\n })\n .where('id', '=', upload.id)\n .where('status', '=', 'cleaning')\n .where('cleanupClaimId', '=', claimId)\n .execute()\n }\n }\n return { claimed: uploads.length, cleaned, failed }\n }\n }\n}\n\n/**\n * Aborting covers a multipart upload that never finished; deleting covers one that did, such as an\n * upload whose commit lost to a newer revision after its parts were assembled.\n */\nasync function removeUploadObject(objects: ObjectStore, upload: ClaimedUpload): Promise<void> {\n if (upload.multipartUploadId) {\n await objects.abortUpload({ key: upload.objectKey, uploadId: upload.multipartUploadId })\n }\n await objects.delete(upload.objectKey)\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { createRateLimitCleanupService } from '#cloud/server/rate-limit/cleanup'\nimport type { Kysely } from 'kysely'\n\nimport { createDocumentCleanupService } from './documents'\nimport { createRevisionCompactionService } from './revisions'\nimport { createUploadCleanupService } from './uploads'\nimport type { CleanupPassOptions, CleanupServices } from './worker'\n\n/** Every cleanup service, over a deployment's database and bucket. */\nexport function createCleanupServices(\n config: Pick<CloudServerConfig, 'deployment'>,\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n policy: CloudPolicy\n): CleanupServices {\n return {\n uploads: createUploadCleanupService(database, objects),\n documents: createDocumentCleanupService(database, objects),\n revisions: createRevisionCompactionService(database, objects, {\n policy,\n deploymentMode: config.deployment\n }),\n rateLimits: createRateLimitCleanupService(database)\n }\n}\n\n/** The batch, lease, and retention a deployment sets for each cleanup pass. */\nexport function cleanupPassOptions(config: CloudServerConfig): CleanupPassOptions {\n return {\n batchSize: config.cleanupBatchSize,\n documentRetentionMs: config.documentRetentionMs,\n leaseDurationMs: config.cleanupLeaseDurationMs\n }\n}\n","/**\n * Waits `milliseconds`, or less if `signal` aborts first. One timer and one listener that is\n * removed again, so a long-lived signal doesn't collect a composite signal per wait.\n */\nexport async function waitForWorkerInterval(\n milliseconds: number,\n signal: AbortSignal\n): Promise<void> {\n if (signal.aborted) return\n const stopped = new AbortController()\n await new Promise<void>((resolve) => {\n stopped.signal.addEventListener('abort', () => resolve(), { once: true })\n const timer = setTimeout(() => stopped.abort(), milliseconds)\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer)\n stopped.abort()\n },\n { once: true, signal: stopped.signal }\n )\n })\n}\n","import { waitForWorkerInterval } from './interval'\n\nexport type PeriodicWorkerOptions<Result> = {\n intervalMs: number\n run(): Promise<Result>\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type PeriodicWorker<Result> = {\n runOnce(): Promise<Result>\n stop(): Promise<void>\n}\n\nexport function startPeriodicWorker<Result>(\n options: PeriodicWorkerOptions<Result>\n): PeriodicWorker<Result> {\n const controller = new AbortController()\n const abort = () => controller.abort()\n options.signal?.addEventListener('abort', abort, { once: true })\n\n async function loop(): Promise<void> {\n while (!controller.signal.aborted) {\n try {\n await options.run()\n } catch (error) {\n options.onError?.(error)\n }\n await waitForWorkerInterval(options.intervalMs, controller.signal)\n }\n }\n\n const running = loop()\n return {\n runOnce: () => options.run(),\n async stop() {\n controller.abort()\n options.signal?.removeEventListener('abort', abort)\n await running\n }\n }\n}\n","import { startPeriodicWorker } from '../worker/periodic'\nimport type { DocumentCleanupResult, DocumentCleanupService } from './documents'\nimport {\n REVISION_COMPACTION_GRACE_MS,\n type RevisionCompactionResult,\n type RevisionCompactionService\n} from './revisions'\nimport type { UploadCleanupResult, UploadCleanupService } from './uploads'\n\nexport type CleanupWorkerOptions = {\n batchSize: number\n documentRetentionMs: number\n intervalMs: number\n leaseDurationMs: number\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type CleanupResult = {\n uploads: UploadCleanupResult\n documents: DocumentCleanupResult\n revisions: RevisionCompactionResult | null\n rateLimits: number\n}\n\nexport type CleanupServices = {\n documents: DocumentCleanupService\n uploads: UploadCleanupService\n revisions?: RevisionCompactionService\n rateLimits?: { cleanupExpired(before: Date): Promise<number> }\n}\n\nexport type CleanupWorker = {\n runOnce(): Promise<CleanupResult>\n stop(): Promise<void>\n}\n\nexport type CleanupPassOptions = Pick<\n CleanupWorkerOptions,\n 'batchSize' | 'documentRetentionMs' | 'leaseDurationMs'\n>\n\n/** One cleanup pass, for runtimes that schedule passes themselves. */\nexport async function runCleanup(\n cleanup: CleanupServices,\n options: CleanupPassOptions\n): Promise<CleanupResult> {\n const uploads = await cleanup.uploads.cleanupExpiredUploads({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs\n })\n const documents = await cleanup.documents.cleanupDeletedDocuments({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs,\n retentionMs: options.documentRetentionMs\n })\n const revisions = cleanup.revisions\n ? await cleanup.revisions.compactRevisions({\n batchSize: options.batchSize,\n graceMs: REVISION_COMPACTION_GRACE_MS\n })\n : null\n const rateLimits = cleanup.rateLimits\n ? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))\n : 0\n return { uploads, documents, revisions, rateLimits }\n}\n\nexport function startCleanupWorker(\n cleanup: CleanupServices,\n options: CleanupWorkerOptions\n): CleanupWorker {\n return startPeriodicWorker({\n intervalMs: options.intervalMs,\n signal: options.signal,\n onError: options.onError,\n run: () => runCleanup(cleanup, options)\n })\n}\n","import type { DocumentSummary } from '#cloud/contract'\nimport type { DocumentDatabase, DocumentSummaryRow } from '#cloud/server/documents/repository'\n\nconst SUMMARY_COLUMNS = [\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n] as const\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport function documentSummary(row: DocumentSummaryRow): DocumentSummary {\n return {\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n}\n\nexport async function getDocumentSummaryRow(\n database: DocumentDatabase,\n documentId: string\n): Promise<DocumentSummaryRow | undefined> {\n return database\n .selectFrom('document')\n .select(SUMMARY_COLUMNS)\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { DocumentServiceOptions } from '#cloud/server/documents/service'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { Kysely } from 'kysely'\n\n/**\n * The document `userId` may write to, and how large one file and the workspace's storage may\n * be for this save: technical limits, tightened by policy.\n */\nexport async function writableDocument(\n database: Kysely<CloudDatabase>,\n options: Pick<DocumentServiceOptions, 'policy' | 'technicalMaximumUploadBytes'>,\n userId: string,\n documentId: string\n) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n // Access was resolved just above, so the document is read without resolving it again.\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) throw new DocumentNotFoundError()\n const document = documentSummary(row)\n const policyContext = {\n targetingKey: document.workspaceId,\n actorId: userId,\n workspaceId: document.workspaceId,\n documentId,\n deploymentMode: 'self-hosted' as const\n }\n const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER\n const maximumFileBytes = Math.min(\n technicalMaximum,\n options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumFileBytes,\n technicalMaximum,\n policyContext\n )\n : technicalMaximum\n )\n const maximumStorageBytes = options.policy\n ? await options.policy.number(\n CLOUD_FEATURE_KEYS.maximumStorageBytes,\n Number.MAX_SAFE_INTEGER,\n policyContext\n )\n : Number.MAX_SAFE_INTEGER\n return {\n document,\n maximumFileBytes,\n maximumStorageBytes:\n maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes\n }\n}\n","import type { DocumentSummary, SharedDocument, WorkspaceRole } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { CreateDocumentRecord } from '#cloud/server/documents/types'\nimport { uniq } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\nimport * as v from 'valibot'\n\nimport { resolveDocumentAccess } from './access'\nimport { documentSummary, getDocumentSummaryRow } from './summary'\n\nconst uuidSchema = v.pipe(v.string(), v.uuid())\n\nexport type DocumentDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nexport type DocumentSummaryRow = Omit<DocumentSummary, 'createdAt' | 'updatedAt'> & {\n createdAt: Date | string\n updatedAt: Date | string\n}\n\nexport async function workspaceRole(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceRole | undefined> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', userId)\n .executeTakeFirst()\n return member?.role\n}\n\nexport async function listDocuments(\n database: DocumentDatabase,\n userId: string,\n workspaceId: string\n): Promise<DocumentSummary[] | undefined> {\n if (!(await workspaceRole(database, userId, workspaceId))) return undefined\n const rows = await database\n .selectFrom('document')\n .select([\n 'id',\n 'workspaceId',\n 'name',\n 'kind',\n 'currentRevisionId',\n 'version',\n 'createdAt',\n 'updatedAt'\n ])\n .where('workspaceId', '=', workspaceId)\n .where('deletedAt', 'is', null)\n .orderBy('updatedAt', 'desc')\n .execute()\n return rows.map(documentSummary)\n}\n\n/** Documents granted to the person directly that live in workspaces they are not a member of. */\nexport async function listSharedDocuments(\n database: DocumentDatabase,\n userId: string\n): Promise<SharedDocument[]> {\n const rows = await database\n .selectFrom('documentGrant')\n .innerJoin('document', 'document.id', 'documentGrant.documentId')\n .innerJoin('workspace', 'workspace.id', 'document.workspaceId')\n .select([\n 'document.id',\n 'document.workspaceId',\n 'document.name',\n 'document.kind',\n 'document.currentRevisionId',\n 'document.version',\n 'document.createdAt',\n 'document.updatedAt',\n 'workspace.name as workspaceName',\n 'documentGrant.permission',\n 'documentGrant.createdAt as sharedAt',\n 'documentGrant.createdBy'\n ])\n .where('documentGrant.userId', '=', userId)\n .where('documentGrant.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n .where((expression) =>\n expression.not(\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', userId)\n )\n )\n )\n .orderBy('document.updatedAt', 'desc')\n .execute()\n // Grants can be made by operator tools whose IDs are not accounts, so only UUIDs are looked up.\n const granters = uniq(rows.map((row) => row.createdBy)).filter((id) => v.is(uuidSchema, id))\n const names = new Map(\n granters.length === 0\n ? []\n : (\n await database\n .selectFrom('user')\n .select(['id', 'name'])\n .where('id', 'in', granters)\n .execute()\n ).map((user) => [user.id, user.name] as const)\n )\n return rows.map(({ workspaceName, permission, sharedAt, createdBy, ...row }) => {\n const sharedByName = names.get(createdBy)\n return {\n ...documentSummary(row),\n workspaceName,\n permission,\n sharedBy: sharedByName === undefined ? null : { name: sharedByName },\n sharedAt: sharedAt instanceof Date ? sharedAt.toISOString() : sharedAt\n }\n })\n}\n\nexport async function findDocument(\n database: DocumentDatabase,\n userId: string,\n documentId: string\n): Promise<(DocumentSummary & { role: WorkspaceRole }) | undefined> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) return undefined\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row) return undefined\n const role: WorkspaceRole = access.permission === 'edit' ? 'editor' : 'viewer'\n return { ...documentSummary(row), role }\n}\n\nexport async function insertDocument(\n database: DocumentDatabase,\n input: CreateDocumentRecord\n): Promise<void> {\n await database.insertInto('document').values(input).execute()\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Transaction } from 'kysely'\n\n/** How long the newest version may be old before a save keeps the state it replaces. */\nexport const CHECKPOINT_INTERVAL_MS = 30 * 60_000\n\n/** Keeps a revision in the history, unless a version already keeps it. */\nexport async function keepRevision(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n revisionId: string\n createdBy: string\n createdAt: Date\n restoredFromVersionId?: string\n }\n): Promise<void> {\n await transaction\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId: input.documentId,\n revisionId: input.revisionId,\n kind: 'checkpoint',\n name: null,\n description: null,\n createdBy: input.createdBy,\n restoredFromVersionId: input.restoredFromVersionId ?? null,\n createdAt: input.createdAt\n })\n .onConflict((conflict) => conflict.column('revisionId').doNothing())\n .execute()\n}\n\n/**\n * Records the history's checkpoints as a save lands: the document's first save, and the state a\n * save replaces once the newest version is half an hour old. Each stretch of editing, and how the\n * document was left at the end of every session, stays in the history; the saves between them are\n * compacted later. Whether the history gained a checkpoint.\n */\nexport async function recordCheckpoint(\n transaction: Transaction<CloudDatabase>,\n input: {\n documentId: string\n previousRevisionId: string | null\n revisionId: string\n userId: string\n now: Date\n }\n): Promise<boolean> {\n if (!input.previousRevisionId) {\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.revisionId,\n createdBy: input.userId,\n createdAt: input.now\n })\n return true\n }\n const newest = await transaction\n .selectFrom('documentVersion')\n .select('createdAt')\n .where('documentId', '=', input.documentId)\n .orderBy('createdAt', 'desc')\n .limit(1)\n .executeTakeFirst()\n if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) {\n return false\n }\n const previous = await transaction\n .selectFrom('documentRevision')\n .select(['createdBy', 'createdAt'])\n .where('id', '=', input.previousRevisionId)\n .executeTakeFirst()\n if (!previous) return false\n await keepRevision(transaction, {\n documentId: input.documentId,\n revisionId: input.previousRevisionId,\n createdBy: previous.createdBy,\n createdAt: previous.createdAt\n })\n return true\n}\n\n/**\n * Tells the document's live rooms that its history changed. The change stands whatever the hook\n * does; an open list that misses it loads the history again when it is next opened.\n */\nexport function announceVersions(\n onVersionsChanged: ((documentId: string) => void) | undefined,\n documentId: string\n): void {\n try {\n onVersionsChanged?.(documentId)\n } catch (error) {\n console.error('[Cloud] Announcing a version history change failed:', error)\n }\n}\n","import type {\n CommitImageUploadsInput,\n CommitUploadInput,\n CreateDocumentInput,\n CreateUploadInput,\n DocumentDownload,\n DocumentSummary,\n ImageUploadOffer,\n RequestImageUploadsInput,\n SharedDocument\n} from '#cloud/contract'\nimport { createUploadCleanupService } from '#cloud/server/cleanup'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n canDeleteDocument,\n canEditDocument,\n resolveDocumentAccess\n} from '#cloud/server/documents/access'\nimport {\n DocumentConflictError,\n DocumentForbiddenError,\n DocumentNotFoundError,\n UploadInvalidError\n} from '#cloud/server/documents/errors'\nimport {\n createDocumentImages,\n currentImageUsage,\n documentImageLinks,\n revisionImageDownloads\n} from '#cloud/server/documents/images'\nimport { writableDocument } from '#cloud/server/documents/limits'\nimport {\n findDocument,\n insertDocument,\n listDocuments,\n listSharedDocuments,\n workspaceRole\n} from '#cloud/server/documents/repository'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport type { CreateDocumentUploadResult } from '#cloud/server/documents/types'\nimport { announceVersions, recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'\nimport type { ObjectStore, StoredObject } from '#cloud/server/objects'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport { isUndefined, limitAsync, omitBy, uniq, uniqBy } from 'es-toolkit'\nimport type { Kysely, Transaction } from 'kysely'\n\nconst DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000\nconst UPLOAD_LIFETIME_MS = 15 * 60 * 1000\n/** How many of a save's images are checked and landed at once. */\nconst IMAGE_COMMIT_CONCURRENCY = 8\nconst WRITABLE_ROLES = new Set(['admin', 'editor'])\n\nexport type DocumentServiceOptions = {\n policy?: CloudPolicy\n technicalMaximumUploadBytes?: number\n /** Called once a save adds a checkpoint to the document's history. */\n onVersionsChanged?: (documentId: string) => void\n}\n\n/** Whether the stored object is the file the upload declared, which the commit names again. */\nfunction matchesUpload(\n stored: { checksum: string; byteSize: number; contentType: string },\n upload: { checksum: string; byteSize: number | string | bigint; contentType: string }\n): boolean {\n return (\n stored.checksum === upload.checksum &&\n stored.byteSize === Number(upload.byteSize) &&\n stored.contentType === upload.contentType\n )\n}\n\nexport function createDocumentService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: DocumentServiceOptions = {}\n) {\n const cleanup = createUploadCleanupService(database, objects)\n const quota = createStorageQuotaService(database)\n const images = createDocumentImages(database, objects, quota)\n\n /**\n * Makes a committed upload the document's current revision, unless it already was, and records\n * the checkpoint the save adds, if any. Whether the history gained one.\n */\n async function landRevision(\n transaction: Transaction<CloudDatabase>,\n {\n userId,\n uploadId,\n upload,\n stored,\n revisionId,\n storageObjectId,\n images: revisionImages,\n name,\n kind\n }: {\n userId: string\n uploadId: string\n upload: {\n documentId: string\n workspaceId: string\n baseRevisionId: string | null\n objectKey: string\n }\n stored: { checksum: string; byteSize: number; contentType: string }\n revisionId: string\n storageObjectId: string\n images: CommitUploadInput['images']\n name: CommitUploadInput['name']\n kind: CommitUploadInput['kind']\n }\n ): Promise<boolean> {\n const lockedUpload = await transaction\n .selectFrom('upload')\n .select('status')\n .where('id', '=', uploadId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (lockedUpload.status === 'committed') return false\n if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()\n const document = await transaction\n .selectFrom('document')\n .select(['currentRevisionId'])\n .where('id', '=', upload.documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n if (document.currentRevisionId !== upload.baseRevisionId) {\n throw new DocumentConflictError()\n }\n await transaction\n .insertInto('storageObject')\n .values({\n id: storageObjectId,\n objectKey: upload.objectKey,\n checksum: stored.checksum,\n byteSize: stored.byteSize,\n contentType: stored.contentType\n })\n .execute()\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: upload.documentId,\n parentRevisionId: upload.baseRevisionId,\n storageObjectId,\n createdBy: userId\n })\n .execute()\n const attached = await images.attachInTransaction(transaction, {\n workspaceId: upload.workspaceId,\n revisionId,\n images: revisionImages\n })\n if (!attached) throw new UploadInvalidError()\n await transaction\n .updateTable('document')\n .set({\n // A revision may also retitle its document, or say the file it holds is a board.\n ...omitBy({ name, kind }, isUndefined),\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1)\n })\n .where('id', '=', upload.documentId)\n .execute()\n const checkpointed = await recordCheckpoint(transaction, {\n documentId: upload.documentId,\n previousRevisionId: document.currentRevisionId,\n revisionId,\n userId,\n now: new Date()\n })\n await transaction\n .updateTable('upload')\n .set({ status: 'committed', finalizationStartedAt: null })\n .where('id', '=', uploadId)\n .execute()\n await quota.commitInTransaction(transaction, uploadId)\n return checkpointed\n }\n\n /** Links for images a live room names, by checksum. */\n async function imageLinksOf(documentId: string, checksums: string[]) {\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n images: await documentImageLinks(database, objects, { documentId, checksums, expiresAt })\n }\n }\n\n async function createDownload(documentId: string): Promise<DocumentDownload> {\n const row = await getDocumentSummaryRow(database, documentId)\n if (!row?.currentRevisionId) throw new DocumentNotFoundError()\n const document: DocumentSummary = documentSummary(row)\n const revision = await database\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.id as revisionId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', document.currentRevisionId)\n .where('documentRevision.documentId', '=', documentId)\n .executeTakeFirst()\n if (!revision) throw new DocumentNotFoundError()\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document,\n revisionId: revision.revisionId,\n byteSize: Number(revision.byteSize),\n checksum: revision.checksum,\n contentType: revision.contentType,\n download: await objects.createDownload({ key: revision.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, revision.revisionId, expiresAt)\n }\n }\n\n /** What committing an upload reads of it and its document. */\n function selectUploads() {\n return database\n .selectFrom('upload')\n .innerJoin('document', 'document.id', 'upload.documentId')\n .select([\n 'upload.id',\n 'upload.documentId',\n 'upload.kind',\n 'document.workspaceId',\n 'upload.baseRevisionId',\n 'upload.objectKey',\n 'upload.checksum',\n 'upload.byteSize',\n 'upload.contentType',\n 'upload.multipartUploadId',\n 'upload.status',\n 'upload.expiresAt'\n ])\n }\n type UploadRow = Awaited<ReturnType<ReturnType<typeof selectUploads>['executeTakeFirstOrThrow']>>\n\n /**\n * Claims a pending upload, completes it when it came in parts, checks the store holds the file\n * it declared, and lands it with `land`. An upload that fails goes back to pending, so its\n * commit can be tried again.\n */\n async function finalizeUpload<T>(\n upload: UploadRow,\n multipart: CommitUploadInput['multipart'],\n land: (stored: StoredObject) => Promise<T>\n ): Promise<T> {\n if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {\n throw new UploadInvalidError()\n }\n const claimed = await database\n .updateTable('upload')\n .set({ status: 'finalizing', finalizationStartedAt: new Date() })\n .where('id', '=', upload.id)\n .where('status', '=', 'pending')\n .returning('id')\n .executeTakeFirst()\n if (!claimed) throw new UploadInvalidError()\n try {\n if (multipart) {\n if (\n !objects.capabilities.multipartUpload ||\n multipart.uploadId !== upload.multipartUploadId\n ) {\n throw new UploadInvalidError()\n }\n await objects.completeUpload({\n key: upload.objectKey,\n uploadId: multipart.uploadId,\n parts: multipart.parts\n })\n }\n const stored = await objects.head(upload.objectKey)\n if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()\n return await land(stored)\n } catch (error) {\n await database\n .updateTable('upload')\n .set({ status: 'pending', finalizationStartedAt: null })\n .where('id', '=', upload.id)\n .where('status', '=', 'finalizing')\n .execute()\n throw error\n }\n }\n\n function landImage(upload: UploadRow, stored: StoredObject): Promise<void> {\n return database.transaction().execute((transaction) =>\n images.landInTransaction(transaction, {\n uploadId: upload.id,\n workspaceId: upload.workspaceId,\n objectKey: upload.objectKey,\n stored\n })\n )\n }\n\n async function commitUpload(\n userId: string,\n uploadId: string,\n input: CommitUploadInput\n ): Promise<DocumentSummary> {\n const upload = await selectUploads()\n .where('upload.id', '=', uploadId)\n .where('upload.createdBy', '=', userId)\n .executeTakeFirst()\n if (!upload) throw new DocumentNotFoundError()\n const access = await resolveDocumentAccess(database, userId, upload.documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n if (input.checksum !== upload.checksum) throw new UploadInvalidError()\n if (upload.status !== 'committed') {\n const checkpointed =\n upload.kind === 'image'\n ? await finalizeUpload(upload, input.multipart, (stored) =>\n landImage(upload, stored).then(() => false)\n )\n : await finalizeUpload(upload, input.multipart, (stored) =>\n database.transaction().execute((transaction) =>\n landRevision(transaction, {\n userId,\n uploadId,\n upload,\n stored,\n revisionId: crypto.randomUUID(),\n storageObjectId: crypto.randomUUID(),\n images: input.images,\n name: input.name,\n kind: input.kind\n })\n )\n )\n if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)\n }\n const document = await findDocument(database, userId, upload.documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n }\n\n return {\n async cleanupExpiredUploads(now = new Date()): Promise<number> {\n const result = await cleanup.cleanupExpiredUploads({\n batchSize: 100,\n leaseDurationMs: 5 * 60 * 1000,\n now\n })\n if (result.failed > 0) throw new Error('One or more expired uploads could not be cleaned')\n return result.cleaned\n },\n\n list(userId: string, workspaceId: string): Promise<DocumentSummary[] | undefined> {\n return listDocuments(database, userId, workspaceId)\n },\n\n listShared(userId: string): Promise<SharedDocument[]> {\n return listSharedDocuments(database, userId)\n },\n\n async usage(userId: string, workspaceId: string) {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n const result = await database\n .selectFrom('document')\n .leftJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')\n .leftJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select((expression) => [\n expression.fn.count('document.id').as('documentCount'),\n expression.fn.count('storageObject.id').as('objectCount'),\n expression.fn\n .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))\n .as('bytesUsed')\n ])\n .where('document.workspaceId', '=', workspaceId)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirstOrThrow()\n const shared = await currentImageUsage(database, workspaceId)\n return {\n bytesUsed: Number(result.bytesUsed) + shared.bytesUsed,\n objectCount: Number(result.objectCount) + shared.objectCount,\n documentCount: Number(result.documentCount)\n }\n },\n\n async access(userId: string, documentId: string) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return access\n },\n\n async downloadShared(documentId: string): Promise<DocumentDownload> {\n return createDownload(documentId)\n },\n\n /** Links for images a live room names, for someone who may view the document. */\n async imageLinks(userId: string, documentId: string, checksums: string[]) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return imageLinksOf(documentId, checksums)\n },\n\n /** Links for images a live room names, for a guest a share already let in. */\n imageLinksShared(documentId: string, checksums: string[]) {\n return imageLinksOf(documentId, checksums)\n },\n\n async download(userId: string, documentId: string): Promise<DocumentDownload> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n return createDownload(documentId)\n },\n\n async remove(userId: string, documentId: string): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access) || !(await canDeleteDocument(database, userId, documentId))) {\n throw new DocumentForbiddenError()\n }\n await database\n .updateTable('document')\n .set({ deletedAt: new Date() })\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .execute()\n },\n\n async create(\n userId: string,\n workspaceId: string,\n input: CreateDocumentInput\n ): Promise<DocumentSummary> {\n const role = await workspaceRole(database, userId, workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()\n const documentId = input.id ?? crypto.randomUUID()\n await insertDocument(database, {\n id: documentId,\n workspaceId,\n name: input.name,\n kind: input.kind,\n createdBy: userId\n })\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n return document\n },\n\n async createUpload(\n userId: string,\n documentId: string,\n input: CreateUploadInput\n ): Promise<CreateDocumentUploadResult> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (document.currentRevisionId !== input.baseRevisionId) throw new DocumentConflictError()\n if (input.byteSize > maximumFileBytes) throw new UploadInvalidError()\n const uploadId = crypto.randomUUID()\n const objectKey = `documents/${document.workspaceId}/${documentId}/uploads/${uploadId}.fig`\n const expiresAt = new Date(Date.now() + UPLOAD_LIFETIME_MS)\n await database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('upload')\n .values({\n id: uploadId,\n documentId,\n baseRevisionId: input.baseRevisionId,\n objectKey,\n checksum: input.checksum,\n byteSize: input.byteSize,\n contentType: input.contentType,\n multipartUploadId: null,\n status: 'pending',\n finalizationStartedAt: null,\n createdBy: userId,\n expiresAt\n })\n .execute()\n await quota.reserveInTransaction(transaction, {\n workspaceId: document.workspaceId,\n uploadId,\n bytes: input.byteSize,\n expiresAt,\n maximumBytes: maximumStorageBytes\n })\n })\n let objectUpload\n try {\n objectUpload = await objects.createUpload({\n key: objectKey,\n byteSize: input.byteSize,\n checksum: input.checksum,\n contentType: input.contentType,\n expiresAt\n })\n } catch (error) {\n await quota.release(uploadId)\n await database\n .updateTable('upload')\n .set({ status: 'abandoned' })\n .where('id', '=', uploadId)\n .execute()\n throw error\n }\n if (objectUpload.kind === 'multipart') {\n await database\n .updateTable('upload')\n .set({ multipartUploadId: objectUpload.uploadId })\n .where('id', '=', uploadId)\n .execute()\n }\n return { id: uploadId, upload: objectUpload }\n },\n\n /** Uploads for the images a save of the document will name that its workspace lacks. */\n async requestImageUploads(\n userId: string,\n documentId: string,\n input: RequestImageUploadsInput\n ): Promise<{ uploads: ImageUploadOffer[] }> {\n const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(\n database,\n options,\n userId,\n documentId\n )\n if (input.images.some((image) => image.byteSize > maximumFileBytes)) {\n throw new UploadInvalidError()\n }\n return {\n uploads: await images.requestUploads({\n userId,\n documentId,\n workspaceId: document.workspaceId,\n images: input.images,\n expiresAt: new Date(Date.now() + UPLOAD_LIFETIME_MS),\n maximumBytes: maximumStorageBytes\n })\n }\n },\n commitUpload,\n\n /**\n * Commits the image uploads a save asked for in one request, however many there are: each\n * must be an image upload this person made for the document.\n */\n async commitImageUploads(\n userId: string,\n documentId: string,\n uploads: CommitImageUploadsInput['uploads']\n ): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!canEditDocument(access)) throw new DocumentForbiddenError()\n const ids = uniq(uploads.map((upload) => upload.uploadId))\n const rows = new Map(\n (\n await selectUploads()\n .where('upload.id', 'in', ids)\n .where('upload.documentId', '=', documentId)\n .where('upload.createdBy', '=', userId)\n .execute()\n ).map((row) => [row.id, row])\n )\n if (rows.size !== ids.length || [...rows.values()].some((row) => row.kind !== 'image')) {\n throw new UploadInvalidError()\n }\n for (const commit of uploads) {\n if (rows.get(commit.uploadId)?.checksum !== commit.checksum) throw new UploadInvalidError()\n }\n // Each image is its own object, so a few are checked and landed at once, each once however\n // often the request names it.\n const land = limitAsync(\n (upload: UploadRow, multipart: CommitUploadInput['multipart']) =>\n finalizeUpload(upload, multipart, (stored) => landImage(upload, stored)),\n IMAGE_COMMIT_CONCURRENCY\n )\n await Promise.all(\n uniqBy(uploads, (commit) => commit.uploadId).map(async (commit) => {\n const upload = rows.get(commit.uploadId)\n if (!upload) throw new UploadInvalidError()\n if (upload.status !== 'committed') await land(upload, commit.multipart)\n })\n )\n }\n }\n}\n\nexport type DocumentService = ReturnType<typeof createDocumentService>\n","import { parseCreateAIToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'\nimport { validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { AINotEntitledError } from './errors'\nimport type { AITokenService } from './service'\n\nexport type AIRouteEnvironment = { Variables: { actor: CloudActor } }\n\n/** Without a service, the deployment has no AI service and the token route is not found. */\nexport function createAIRoutes(\n service: AITokenService | undefined,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<AIRouteEnvironment>()\n if (service && rateLimit) {\n router.use(\n '/ai/token',\n createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.aiToken)\n )\n }\n return router.post('/ai/token', validatedJSON(parseCreateAIToken), async (context) => {\n if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)\n try {\n return context.json(\n await service.issue(context.get('actor'), context.req.valid('json').workspaceId)\n )\n } catch (error) {\n if (error instanceof DocumentNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof AINotEntitledError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n throw error\n }\n })\n}\n","import { CLOUD_AI_TOKEN_AUDIENCE, type AIToken } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport { SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\n\nimport { AINotEntitledError } from './errors'\nimport { AI_SIGNING_ALGORITHM, type AISigningKey } from './keys'\n\nexport type AITokenServiceOptions = {\n database: Kysely<CloudDatabase>\n policy: CloudPolicy\n deploymentMode: 'official' | 'self-hosted'\n /** The Cloud public URL, which services check as the token's `iss`. */\n issuer: string\n signingKey: AISigningKey\n lifetimeSeconds: number\n}\n\nexport function createAITokenService(options: AITokenServiceOptions) {\n const { privateKey, publicJWK } = options.signingKey\n\n return {\n /**\n * Signs a token that lets a workspace member reach the AI service on the workspace's behalf.\n * Entitlements are read for every token, so a plan change reaches the service within one\n * token lifetime.\n */\n async issue(actor: CloudActor, workspaceId: string): Promise<AIToken> {\n if (!(await workspaceRole(options.database, actor.userId, workspaceId))) {\n throw new DocumentNotFoundError()\n }\n const context = {\n targetingKey: workspaceId,\n actorId: actor.userId,\n workspaceId,\n deploymentMode: options.deploymentMode\n }\n const [enabled, allowance] = await Promise.all([\n options.policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),\n options.policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)\n ])\n if (!enabled) throw new AINotEntitledError()\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAt = issuedAt + options.lifetimeSeconds\n const token = await new SignJWT({\n workspaceId,\n monthlyCreditAllowance: allowance < 0 ? null : allowance\n })\n .setProtectedHeader({ alg: AI_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })\n .setIssuer(options.issuer)\n .setAudience(CLOUD_AI_TOKEN_AUDIENCE)\n .setSubject(actor.userId)\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAt)\n .sign(privateKey)\n return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }\n },\n\n jwks() {\n return { keys: [publicJWK] }\n }\n }\n}\n\nexport type AITokenService = ReturnType<typeof createAITokenService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nexport async function requireSharingAccess(\n database: Kysely<CloudDatabase>,\n userId: string,\n documentId: string\n): Promise<void> {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (!access.canManageSharing) throw new DocumentForbiddenError()\n}\n\n/**\n * Ends every collaboration ticket and room key issued for the document so far: removing someone's\n * access must also remove them from its live room.\n */\nexport async function advanceCollaborationEpoch(\n database: Kysely<CloudDatabase>,\n documentId: string\n): Promise<void> {\n await database\n .updateTable('document')\n .set({ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1) })\n .where('id', '=', documentId)\n .executeTakeFirst()\n}\n","import { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\n\nconst CONTINUATION_SALT = utf8ToBytes('openpencil-cloud-invitation-continuation')\nconst CONTINUATION_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\n\nexport function hashCapability(value: string): string {\n return bytesToHex(sha256(utf8ToBytes(value)))\n}\n\nexport function capabilityHashMatches(stored: string, value: string): boolean {\n let expected: Uint8Array\n try {\n expected = hexToBytes(stored)\n } catch {\n return false\n }\n const actual = sha256(utf8ToBytes(value))\n if (expected.length !== actual.length) return false\n let difference = 0\n for (const [index, expectedByte] of expected.entries()) {\n difference |= expectedByte ^ (actual[index] ?? 0)\n }\n return difference === 0\n}\n\nfunction continuationKey(secret: string): Uint8Array {\n return hkdf(sha256, utf8ToBytes(secret), CONTINUATION_SALT, new Uint8Array(), 32)\n}\n\nexport async function encryptContinuationToken(secret: string, token: string): Promise<string> {\n return new CompactEncrypt(utf8ToBytes(token))\n .setProtectedHeader(CONTINUATION_HEADER)\n .encrypt(continuationKey(secret))\n}\n\nexport async function decryptContinuationToken(secret: string, value: string): Promise<string> {\n const { plaintext, protectedHeader } = await compactDecrypt(value, continuationKey(secret))\n if (\n protectedHeader.alg !== CONTINUATION_HEADER.alg ||\n protectedHeader.enc !== CONTINUATION_HEADER.enc\n ) {\n throw new Error('Unsupported invitation continuation encryption')\n }\n return new TextDecoder().decode(plaintext)\n}\n","export class InvitationDeliveryError extends Error {\n override readonly name = 'InvitationDeliveryError'\n}\n\nexport class DocumentShareInvalidError extends Error {\n override readonly name = 'DocumentShareInvalidError'\n}\n\n/** A valid link this server opens only for people signed in to it. */\nexport class DocumentShareSignInRequiredError extends Error {\n override readonly name = 'DocumentShareSignInRequiredError'\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\nimport { staticEntitlementsSchema } from './schema'\nimport { staticEntitlementValues, type StaticEntitlementsInput } from './static'\n\nexport class DatabaseEntitlementSource implements EntitlementSource {\n constructor(private readonly database: Kysely<CloudDatabase>) {}\n\n private async values(subject: EntitlementSubject): Promise<Record<string, boolean | number>> {\n if (subject.type !== 'workspace') return {}\n const row = await this.database\n .selectFrom('workspaceEntitlement')\n .select('values')\n .where('workspaceId', '=', subject.id)\n .executeTakeFirst()\n return row ? staticEntitlementValues(v.parse(staticEntitlementsSchema, row.values)) : {}\n }\n\n async boolean(subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = (await this.values(subject))[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, _key: string): Promise<string | null> {\n return null\n }\n}\n\nexport function createWorkspaceEntitlementRepository(database: Kysely<CloudDatabase>) {\n return {\n async get(workspaceId: string) {\n return database\n .selectFrom('workspaceEntitlement')\n .selectAll()\n .where('workspaceId', '=', workspaceId)\n .executeTakeFirst()\n },\n\n async set(workspaceId: string, values: StaticEntitlementsInput, source: string) {\n const validated = v.parse(staticEntitlementsSchema, values)\n return database\n .insertInto('workspaceEntitlement')\n .values({ workspaceId, values: validated, source })\n .onConflict((conflict) =>\n conflict.column('workspaceId').doUpdateSet({\n values: validated,\n source,\n revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n )\n .returningAll()\n .executeTakeFirstOrThrow()\n },\n\n /**\n * Stores entitlements an external writer versioned, unless the stored row carries a newer\n * version: billing events arrive out of order, and a late one must not undo a newer plan.\n * An unversioned row, such as one an operator set, is replaced.\n */\n async setVersioned(\n workspaceId: string,\n values: StaticEntitlementsInput,\n source: string,\n externalVersion: number\n ): Promise<{ applied: boolean }> {\n const validated = v.parse(staticEntitlementsSchema, values)\n const row = await database\n .insertInto('workspaceEntitlement')\n .values({ workspaceId, values: validated, source, externalVersion })\n .onConflict((conflict) =>\n conflict\n .column('workspaceId')\n .doUpdateSet({\n values: validated,\n source,\n externalVersion,\n revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),\n updatedAt: new Date()\n })\n .where((expression) =>\n expression.or([\n expression('workspaceEntitlement.externalVersion', 'is', null),\n expression('workspaceEntitlement.externalVersion', '<', externalVersion)\n ])\n )\n )\n .returning('workspaceId')\n .executeTakeFirst()\n return { applied: row !== undefined }\n },\n\n async clear(workspaceId: string): Promise<void> {\n await database\n .deleteFrom('workspaceEntitlement')\n .where('workspaceId', '=', workspaceId)\n .execute()\n }\n }\n}\n","export type EntitlementSubject = {\n type: 'workspace' | 'user' | 'organization' | 'deployment'\n id: string\n}\n\nexport type EntitlementSource = {\n boolean(subject: EntitlementSubject, key: string): Promise<boolean | null>\n number(subject: EntitlementSubject, key: string): Promise<number | null>\n string(subject: EntitlementSubject, key: string): Promise<string | null>\n}\n\nexport class StaticEntitlementSource implements EntitlementSource {\n constructor(private readonly values: Readonly<Record<string, boolean | number | string>>) {}\n\n async boolean(_subject: EntitlementSubject, key: string): Promise<boolean | null> {\n const value = this.values[key]\n return typeof value === 'boolean' ? value : null\n }\n\n async number(_subject: EntitlementSubject, key: string): Promise<number | null> {\n const value = this.values[key]\n return typeof value === 'number' ? value : null\n }\n\n async string(_subject: EntitlementSubject, key: string): Promise<string | null> {\n const value = this.values[key]\n return typeof value === 'string' ? value : null\n }\n}\n","import {\n type EvaluationContext,\n type Logger,\n type Provider,\n type ProviderMetadata,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport type { EntitlementSource, EntitlementSubject } from './entitlements'\n\nfunction subject(context: EvaluationContext): EntitlementSubject {\n const type = context.subjectType\n return {\n type: type === 'user' || type === 'organization' || type === 'deployment' ? type : 'workspace',\n id: context.targetingKey ?? 'deployment'\n }\n}\n\nexport class EntitlementOpenFeatureProvider implements Provider {\n readonly metadata: ProviderMetadata = { name: 'openpencil-entitlements' }\n readonly runsOn = 'server' as const\n\n constructor(private readonly source: EntitlementSource) {}\n\n async resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<boolean>> {\n const value = await this.source.boolean(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<number>> {\n const value = await this.source.number(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext,\n _logger: Logger\n ): Promise<ResolutionDetails<string>> {\n const value = await this.source.string(subject(context), flagKey)\n return value === null\n ? { value: defaultValue, reason: 'DEFAULT' }\n : { value, reason: 'TARGETING_MATCH' }\n }\n\n async resolveObjectEvaluation<T>(\n _flagKey: string,\n defaultValue: T\n ): Promise<ResolutionDetails<T>> {\n return { value: defaultValue, reason: 'DEFAULT' }\n }\n}\n","import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'\nimport {\n DefaultLogger,\n TypedInMemoryProvider,\n type EvaluationContext,\n type Provider,\n type ResolutionDetails\n} from '@openfeature/server-sdk'\n\nimport { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'\n\nconst DEFAULT_FLAGS = {\n [CLOUD_FEATURE_KEYS.links]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestView]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestEdit]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.guestPresence]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.collaboration]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.serverEnforcedWrites]: {\n variants: { enabled: false, disabled: false },\n defaultVariant: 'disabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.revisionHistory]: {\n variants: { enabled: true, disabled: false },\n defaultVariant: 'enabled',\n disabled: false\n },\n [CLOUD_FEATURE_KEYS.maximumFileBytes]: {\n variants: { default: CLOUD_PROTOCOL_MAX_UPLOAD_BYTES },\n defaultVariant: 'default',\n disabled: false\n }\n} as const\n\nfunction evaluationContext(context: CloudPolicyContext): EvaluationContext {\n const evaluation: EvaluationContext = {\n targetingKey: context.targetingKey,\n deploymentMode: context.deploymentMode\n }\n if (context.actorId) evaluation.actorId = context.actorId\n if (context.workspaceId) evaluation.workspaceId = context.workspaceId\n if (context.organizationId) evaluation.organizationId = context.organizationId\n if (context.documentId) evaluation.documentId = context.documentId\n return evaluation\n}\n\nconst logger = new DefaultLogger()\n\n/** A flag's value, or the default when the provider failed or reported an error, as a client does. */\nasync function resolved<T>(evaluation: () => Promise<ResolutionDetails<T>>, defaultValue: T) {\n try {\n const details = await evaluation()\n return details.errorCode ? defaultValue : details.value\n } catch {\n return defaultValue\n }\n}\n\n/**\n * Answers entitlement questions from one OpenFeature provider. It asks the provider directly\n * rather than through the global `OpenFeature` API: each app has its own provider, and the API\n * keeps every provider registered under a domain reachable for the life of the process, with the\n * database its entitlement source holds.\n */\nexport class CloudPolicy {\n constructor(private readonly provider: Provider) {}\n\n boolean(key: string, defaultValue: boolean, context: CloudPolicyContext): Promise<boolean> {\n return resolved(\n () =>\n this.provider.resolveBooleanEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n ),\n defaultValue\n )\n }\n\n number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {\n return resolved(\n () =>\n this.provider.resolveNumberEvaluation(\n key,\n defaultValue,\n evaluationContext(context),\n logger\n ),\n defaultValue\n )\n }\n}\n\nexport function createDefaultCloudPolicy(provider?: Provider): CloudPolicy {\n return new CloudPolicy(provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))\n}\n","import type { CloudServerConfig } from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nimport { DatabaseEntitlementSource } from './database'\nimport { StaticEntitlementSource } from './entitlements'\nimport { createDefaultCloudPolicy } from './policy'\nimport { EntitlementOpenFeatureProvider } from './provider'\nimport { staticEntitlementValues } from './static'\n\n/** The policy a deployment configures: its static entitlements, or the database's. */\nexport function createConfiguredCloudPolicy(\n config: Pick<CloudServerConfig, 'staticEntitlements'>,\n database: Kysely<CloudDatabase>\n) {\n return createDefaultCloudPolicy(\n new EntitlementOpenFeatureProvider(\n config.staticEntitlements\n ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))\n : new DatabaseEntitlementSource(database)\n )\n )\n}\n","import type { WorkspaceEntitlements } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { workspaceRole } from '#cloud/server/documents/repository'\nimport { createStorageQuotaService } from '#cloud/server/quota'\nimport type { Kysely } from 'kysely'\n\nimport { CLOUD_FEATURE_KEYS } from './keys'\nimport type { CloudPolicy } from './policy'\n\nexport function createEntitlementService(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n technicalMaximumFileBytes: number,\n technicalMaximumParticipants = Number.MAX_SAFE_INTEGER\n) {\n const quota = createStorageQuotaService(database)\n return {\n async workspace(userId: string, workspaceId: string): Promise<WorkspaceEntitlements> {\n if (!(await workspaceRole(database, userId, workspaceId))) throw new DocumentNotFoundError()\n const context = {\n targetingKey: workspaceId,\n actorId: userId,\n workspaceId,\n deploymentMode: 'self-hosted' as const\n }\n const [\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudAI,\n maximumFileBytes,\n maximumStorage,\n maximumParticipants,\n monthlyCreditAllowance,\n usage\n ] = await Promise.all([\n policy.boolean(CLOUD_FEATURE_KEYS.links, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestEdit, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),\n policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),\n policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),\n policy.number(\n CLOUD_FEATURE_KEYS.maximumParticipants,\n technicalMaximumParticipants,\n context\n ),\n policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context),\n quota.snapshot(workspaceId)\n ])\n // Technical limits are ceilings: an entitlement can lower them but never raise them.\n const participants = Math.min(technicalMaximumParticipants, maximumParticipants)\n return {\n features: {\n links,\n guestView,\n guestEdit,\n guestPresence,\n collaboration,\n revisionHistory,\n cloudAI\n },\n limits: {\n maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),\n maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,\n maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,\n monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance\n },\n usage: {\n committedStorageBytes: usage.committedBytes,\n reservedStorageBytes: usage.reservedBytes\n }\n }\n }\n }\n}\n\nexport type EntitlementService = ReturnType<typeof createEntitlementService>\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentForbiddenError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'\nimport type { Kysely } from 'kysely'\n\nexport type SharingPolicyOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport type CapabilityLinkPolicyInput = {\n actorId: string\n documentId: string\n}\n\nexport function createSharingPolicy(\n database: Kysely<CloudDatabase>,\n options: SharingPolicyOptions\n) {\n async function requireCapabilityLink(input: CapabilityLinkPolicyInput): Promise<void> {\n if (!options.policy) return\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', input.documentId)\n .executeTakeFirstOrThrow()\n const context: CloudPolicyContext = {\n targetingKey: document.workspaceId,\n actorId: input.actorId,\n workspaceId: document.workspaceId,\n documentId: input.documentId,\n deploymentMode: options.deploymentMode ?? 'self-hosted'\n }\n // Whether guests may follow the link is checked when they do, so edit links still work for\n // people signed in to the server.\n if (!(await options.policy.boolean(CLOUD_FEATURE_KEYS.links, false, context))) {\n throw new DocumentForbiddenError()\n }\n }\n\n return { requireCapabilityLink }\n}\n\nexport type SharingPolicy = ReturnType<typeof createSharingPolicy>\n","import type {\n CreateDocumentShareInput,\n DocumentPermission,\n DocumentShare,\n ResolveDocumentShareInput,\n UpdateDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely, UpdateObject } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { shareContract } from '../contracts'\nimport { capabilityHashMatches, hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '../errors'\nimport { createSharingPolicy } from '../policy'\n\nconst SHARE_SECRET_BYTES = 24\n\nexport type DocumentShareCapability = {\n share: DocumentShare\n secret: string\n path: string\n}\n\nexport type ResolvedSharePrincipal =\n | { kind: 'user'; userId: string; name: string; email: string }\n | { kind: 'guest'; guestId: string; name: string }\n\nexport type ResolvedDocumentShare = {\n documentId: string\n permission: DocumentPermission\n principal: ResolvedSharePrincipal\n roomEpoch: number\n}\n\nexport type CapabilityServiceOptions = {\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCapabilityService(\n database: Kysely<CloudDatabase>,\n options: CapabilityServiceOptions\n) {\n const sharingPolicy = createSharingPolicy(database, options)\n\n async function updateActiveShare(\n userId: string,\n documentId: string,\n shareId: string,\n changes: UpdateObject<CloudDatabase, 'documentShare'>\n ) {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .updateTable('documentShare')\n .set(changes)\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n return {\n async listShares(userId: string, documentId: string): Promise<DocumentShare[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentShare')\n .selectAll()\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt', 'desc')\n .execute()\n return rows.map(shareContract)\n },\n\n async createShare(\n userId: string,\n documentId: string,\n input: CreateDocumentShareInput\n ): Promise<DocumentShareCapability> {\n await requireSharingAccess(database, userId, documentId)\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const id = crypto.randomUUID()\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n return transaction\n .insertInto('documentShare')\n .values({\n id,\n documentId,\n permission: input.permission,\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n createdBy: userId,\n expiresAt: input.expiresAt ? new Date(input.expiresAt) : null,\n revokedAt: null,\n lastUsedAt: null\n })\n .returningAll()\n .executeTakeFirstOrThrow()\n })\n return { share: shareContract(row), secret, path: `/share/${id}#${secret}` }\n },\n\n async updateShare(\n userId: string,\n documentId: string,\n shareId: string,\n input: UpdateDocumentShareInput\n ): Promise<DocumentShare> {\n // Authorization comes first, so a caller without access learns nothing about the share\n // or the document's link policy.\n await requireSharingAccess(database, userId, documentId)\n const current = await database\n .selectFrom('documentShare')\n .select('id')\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!current) throw new DocumentNotFoundError()\n await sharingPolicy.requireCapabilityLink({ actorId: userId, documentId })\n const changes: UpdateObject<CloudDatabase, 'documentShare'> = { updatedAt: new Date() }\n if (input.permission) changes.permission = input.permission\n if (input.expiresAt !== undefined) {\n changes.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n }\n const row = await updateActiveShare(userId, documentId, shareId, changes)\n return shareContract(row)\n },\n\n async rotateShare(\n userId: string,\n documentId: string,\n shareId: string\n ): Promise<DocumentShareCapability> {\n const secret = randomHex(SHARE_SECRET_BYTES)\n const row = await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const updated = await transaction\n .updateTable('documentShare')\n .set({\n secretHash: hashCapability(secret),\n roomEpoch: document.collaborationEpoch,\n updatedAt: new Date()\n })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .returningAll()\n .executeTakeFirst()\n if (!updated) throw new DocumentNotFoundError()\n return updated\n })\n return { share: shareContract(row), secret, path: `/share/${shareId}#${secret}` }\n },\n\n async revokeShare(userId: string, documentId: string, shareId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentShare')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('id', '=', shareId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n },\n\n async resolveShare(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<ResolvedDocumentShare> {\n const row = await database\n .selectFrom('documentShare')\n .innerJoin('document', 'document.id', 'documentShare.documentId')\n .select([\n 'documentShare.id',\n 'documentShare.documentId',\n 'documentShare.permission',\n 'documentShare.secretHash',\n 'documentShare.roomEpoch',\n 'documentShare.expiresAt'\n ])\n .where('documentShare.id', '=', shareId)\n .where('documentShare.revokedAt', 'is', null)\n .where('document.deletedAt', 'is', null)\n .executeTakeFirst()\n if (\n !row ||\n !capabilityHashMatches(row.secretHash, input.secret) ||\n (row.expiresAt && new Date(row.expiresAt).getTime() <= Date.now())\n ) {\n throw new DocumentShareInvalidError()\n }\n if (!actor && options.policy) {\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', row.documentId)\n .executeTakeFirstOrThrow()\n const featureKey =\n row.permission === 'edit' ? CLOUD_FEATURE_KEYS.guestEdit : CLOUD_FEATURE_KEYS.guestView\n if (\n !(await options.policy.boolean(featureKey, false, {\n targetingKey: document.workspaceId,\n workspaceId: document.workspaceId,\n documentId: row.documentId,\n deploymentMode: options.deploymentMode ?? 'self-hosted'\n }))\n ) {\n // Guests are not let in here; people signed in to the server are.\n throw new DocumentShareSignInRequiredError()\n }\n }\n await database\n .updateTable('documentShare')\n .set({ lastUsedAt: new Date() })\n .where('id', '=', shareId)\n .execute()\n return {\n documentId: row.documentId,\n permission: row.permission,\n principal: actor\n ? { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email }\n : {\n kind: 'guest',\n guestId: input.guestId ?? crypto.randomUUID(),\n name: input.guestName ?? 'Guest'\n },\n roomEpoch: row.roomEpoch\n }\n }\n }\n}\n\nexport type CapabilityService = ReturnType<typeof createCapabilityService>\n","import type { DocumentGrant, PutDocumentGrantInput } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { Kysely } from 'kysely'\n\nimport { advanceCollaborationEpoch, requireSharingAccess } from '../access'\nimport { grantContract } from '../contracts'\n\nexport function createGrantService(database: Kysely<CloudDatabase>) {\n return {\n async listGrants(userId: string, documentId: string): Promise<DocumentGrant[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentGrant')\n .select(['id', 'documentId', 'userId', 'permission', 'createdBy', 'createdAt', 'updatedAt'])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('createdAt')\n .execute()\n return rows.map(grantContract)\n },\n\n async putGrant(\n userId: string,\n documentId: string,\n targetUserId: string,\n input: PutDocumentGrantInput\n ): Promise<DocumentGrant> {\n await requireSharingAccess(database, userId, documentId)\n const row = await database\n .insertInto('documentGrant')\n .values({\n id: crypto.randomUUID(),\n documentId,\n userId: targetUserId,\n permission: input.permission,\n createdBy: userId,\n revokedAt: null\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'userId']).doUpdateSet({\n permission: input.permission,\n createdBy: userId,\n revokedAt: null,\n updatedAt: new Date()\n })\n )\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirstOrThrow()\n return grantContract(row)\n },\n\n /** Revoking access advances the collaboration epoch, so tickets and room keys issued before stop working. */\n async revokeGrant(userId: string, documentId: string, targetUserId: string): Promise<void> {\n await database.transaction().execute(async (transaction) => {\n await requireSharingAccess(transaction, userId, documentId)\n const result = await transaction\n .updateTable('documentGrant')\n .set({ revokedAt: new Date(), updatedAt: new Date() })\n .where('documentId', '=', documentId)\n .where('userId', '=', targetUserId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n await advanceCollaborationEpoch(transaction, documentId)\n })\n }\n }\n}\n\nexport type GrantService = ReturnType<typeof createGrantService>\n","import type { InvitationPreview } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentShareInvalidError } from '#cloud/server/sharing/errors'\nimport type { Kysely } from 'kysely'\n\nimport { capabilityHashMatches, decryptContinuationToken, encryptContinuationToken } from './crypto'\n\nconst CONTINUATION_LIFETIME_MS = 10 * 60_000\n\nexport type InvitationContinuationService = ReturnType<typeof createInvitationContinuationService>\n\nexport function createInvitationContinuationService(\n database: Kysely<CloudDatabase>,\n secret: string,\n validateInvitation: (invitationId: string, token: string) => Promise<InvitationPreview>\n) {\n return {\n async create(input: { invitationId: string; token: string }): Promise<{ id: string }> {\n await validateInvitation(input.invitationId, input.token)\n const id = crypto.randomUUID()\n await database\n .insertInto('invitationContinuation')\n .values({\n id,\n invitationId: input.invitationId,\n tokenEncrypted: await encryptContinuationToken(secret, input.token),\n expiresAt: new Date(Date.now() + CONTINUATION_LIFETIME_MS),\n consumedAt: null\n })\n .execute()\n return { id }\n },\n\n async consume(id: string): Promise<{ invitationId: string; token: string }> {\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .selectFrom('invitationContinuation')\n .select(['invitationId', 'tokenEncrypted', 'expiresAt', 'consumedAt'])\n .where('id', '=', id)\n .forUpdate()\n .executeTakeFirst()\n if (!row || row.consumedAt || new Date(row.expiresAt).getTime() <= Date.now()) {\n throw new DocumentShareInvalidError()\n }\n await transaction\n .updateTable('invitationContinuation')\n .set({ consumedAt: new Date() })\n .where('id', '=', id)\n .execute()\n return {\n invitationId: row.invitationId,\n token: await decryptContinuationToken(secret, row.tokenEncrypted)\n }\n })\n }\n }\n}\n\nexport function invitationTokenIsActive(\n invitation: {\n tokenHash: string\n expiresAt: Date | string\n acceptedAt: Date | string | null\n revokedAt: Date | string | null\n },\n token: string\n): boolean {\n return (\n capabilityHashMatches(invitation.tokenHash, token) &&\n !invitation.acceptedAt &&\n !invitation.revokedAt &&\n new Date(invitation.expiresAt).getTime() > Date.now()\n )\n}\n\nexport function recipientHint(email: string): string {\n const [local = '', domain = ''] = email.split('@')\n const visible = local.slice(0, 2)\n return `${visible}${'*'.repeat(Math.max(3, local.length - visible.length))}@${domain}`\n}\n\nexport function invitationMatchesActor(actor: CloudActor, email: string): boolean {\n return email === actor.email.trim().toLowerCase()\n}\n","import type { CreateWorkspaceInput, WorkspaceRole, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type WorkspaceDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>\n\nfunction toISOString(value: Date | string): string {\n return value instanceof Date ? value.toISOString() : value\n}\n\nexport async function listWorkspaces(\n database: WorkspaceDatabase,\n userId: string\n): Promise<WorkspaceSummary[]> {\n const rows = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspaceMember.role'\n ])\n .where('workspaceMember.userId', '=', userId)\n .orderBy('workspace.updatedAt', 'desc')\n .execute()\n\n return rows.map((row) => ({\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }))\n}\n\nexport async function findWorkspace(\n database: WorkspaceDatabase,\n userId: string,\n workspaceId: string\n): Promise<WorkspaceSummary | undefined> {\n const row = await database\n .selectFrom('workspace')\n .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')\n .select([\n 'workspace.id',\n 'workspace.name',\n 'workspace.slug',\n 'workspace.createdAt',\n 'workspace.updatedAt',\n 'workspaceMember.role'\n ])\n .where('workspace.id', '=', workspaceId)\n .where('workspaceMember.userId', '=', userId)\n .executeTakeFirst()\n return row\n ? {\n ...row,\n createdAt: toISOString(row.createdAt),\n updatedAt: toISOString(row.updatedAt)\n }\n : undefined\n}\n\nexport async function insertWorkspace(\n database: WorkspaceDatabase,\n actorId: string,\n input: CreateWorkspaceInput & { id: string; slug: string }\n): Promise<boolean> {\n const inserted = await database\n .insertInto('workspace')\n .values({\n id: input.id,\n name: input.name,\n slug: input.slug,\n createdBy: actorId\n })\n .onConflict((conflict) => conflict.column('slug').doNothing())\n .returning('id')\n .executeTakeFirst()\n return inserted !== undefined\n}\n\nexport async function insertWorkspaceMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n userId: string,\n role: WorkspaceRole\n): Promise<void> {\n await database.insertInto('workspaceMember').values({ workspaceId, userId, role }).execute()\n}\n","import type {\n CreateWorkspaceInvitationInput,\n CreatedWorkspaceInvitation,\n InvitationPreview,\n WorkspaceInvitation,\n WorkspaceMembers,\n WorkspaceRole,\n WorkspaceSummary\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { TransactionalEmailService } from '#cloud/server/email/types'\nimport {\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '#cloud/server/sharing/continuation'\nimport { dateString } from '#cloud/server/sharing/contracts'\nimport { hashCapability } from '#cloud/server/sharing/crypto'\nimport { findWorkspace, type WorkspaceDatabase } from '#cloud/server/workspaces/repository'\nimport type { Kysely } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nconst INVITATION_SECRET_BYTES = 24\nconst INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000\n\n/** The workspace does not exist, or the person is not a member of it. */\nexport class WorkspaceNotFoundError extends Error {\n constructor() {\n super('Workspace not found')\n this.name = 'WorkspaceNotFoundError'\n }\n}\n\n/** Only a workspace's administrators may do this. */\nexport class WorkspaceForbiddenError extends Error {\n constructor() {\n super('Workspace administrators only')\n this.name = 'WorkspaceForbiddenError'\n }\n}\n\n/** The change would leave a workspace with members but no administrator. */\nexport class WorkspaceLastAdminError extends Error {\n constructor() {\n super('A workspace needs an administrator')\n this.name = 'WorkspaceLastAdminError'\n }\n}\n\n/**\n * A workspace still holds documents: live ones, or deleted ones kept until cleanup removes their\n * files, which deleting the workspace now would leave behind in object storage.\n */\nexport class WorkspaceNotEmptyError extends Error {\n constructor(readonly reason: 'documents' | 'pending-cleanup') {\n super('Workspace still holds documents')\n this.name = 'WorkspaceNotEmptyError'\n }\n}\n\n/** The person invited already belongs to the workspace. */\nexport class WorkspaceAlreadyMemberError extends Error {\n constructor() {\n super('Already a member of this workspace')\n this.name = 'WorkspaceAlreadyMemberError'\n }\n}\n\n/** The invitation is unknown, used, withdrawn, expired, or meant for someone else. */\nexport class WorkspaceInvitationInvalidError extends Error {\n constructor() {\n super('Workspace invitation is not valid')\n this.name = 'WorkspaceInvitationInvalidError'\n }\n}\n\nexport type WorkspaceMemberServiceOptions = {\n email?: TransactionalEmailService\n publicURL: string\n}\n\nfunction invitationContract(row: {\n id: string\n emailNormalized: string\n role: WorkspaceRole\n invitedBy: string\n inviterName: string | null\n invitedAt: Date | string\n expiresAt: Date | string\n}): WorkspaceInvitation {\n return {\n id: row.id,\n email: row.emailNormalized,\n role: row.role,\n invitedBy: { id: row.invitedBy, name: row.inviterName },\n invitedAt: dateString(row.invitedAt) ?? '',\n expiresAt: dateString(row.expiresAt) ?? ''\n }\n}\n\nasync function adminCount(database: WorkspaceDatabase, workspaceId: string): Promise<number> {\n const rows = await database\n .selectFrom('workspaceMember')\n .select('userId')\n .where('workspaceId', '=', workspaceId)\n .where('role', '=', 'admin')\n .forUpdate()\n .execute()\n return rows.length\n}\n\n/** A member's row, locked until the transaction ends so roles change one at a time. */\nasync function lockedMember(\n database: WorkspaceDatabase,\n workspaceId: string,\n memberId: string\n): Promise<{ role: WorkspaceRole }> {\n const member = await database\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .forUpdate()\n .executeTakeFirst()\n if (!member) throw new WorkspaceNotFoundError()\n return member\n}\n\n/**\n * Who belongs to a workspace and who is invited to it. Administrators invite, change roles, and\n * remove people; anyone may leave. A workspace with members always keeps an administrator.\n */\nexport function createWorkspaceMemberService(\n database: Kysely<CloudDatabase>,\n options: WorkspaceMemberServiceOptions\n) {\n async function membership(userId: string, workspaceId: string): Promise<WorkspaceSummary> {\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new WorkspaceNotFoundError()\n return workspace\n }\n\n async function requireAdmin(userId: string, workspaceId: string): Promise<WorkspaceSummary> {\n const workspace = await membership(userId, workspaceId)\n if (workspace.role !== 'admin') throw new WorkspaceForbiddenError()\n return workspace\n }\n\n /** A workspace's members with their accounts; user ids are text in membership rows. */\n function memberUsers(workspaceId: string) {\n return database\n .selectFrom('workspaceMember')\n .innerJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('workspaceMember.userId')\n )\n )\n )\n .where('workspaceMember.workspaceId', '=', workspaceId)\n }\n\n function acceptanceURL(invitationId: string, token: string): string {\n return cloudInvitationURL(options.publicURL, invitationId, token)\n }\n\n /** Invites someone by email; a newer invitation to the same address replaces the older. */\n async function invite(\n userId: string,\n workspaceId: string,\n input: CreateWorkspaceInvitationInput\n ): Promise<CreatedWorkspaceInvitation> {\n const workspace = await requireAdmin(userId, workspaceId)\n const existing = await memberUsers(workspaceId)\n .select('workspaceMember.userId')\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)\n )\n .executeTakeFirst()\n if (existing) throw new WorkspaceAlreadyMemberError()\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', userId)\n .executeTakeFirst()\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const url = acceptanceURL(id, token)\n const row = await database.transaction().execute(async (transaction) => {\n await transaction\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('workspaceId', '=', workspaceId)\n .where('emailNormalized', '=', input.email)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .execute()\n const inserted = await transaction\n .insertInto('workspaceInvitation')\n .values({\n id,\n workspaceId,\n emailNormalized: input.email,\n role: input.role,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning(['id', 'emailNormalized', 'role', 'invitedBy', 'invitedAt', 'expiresAt'])\n .executeTakeFirstOrThrow()\n await options.email?.enqueue(\n {\n idempotencyKey: `workspace-invitation/${id}`,\n kind: 'workspace-invitation',\n recipientEmail: input.email,\n payload: {\n inviterName: inviter?.name ?? 'An OpenPencil user',\n workspaceName: workspace.name,\n role: input.role,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL: url\n }\n },\n transaction\n )\n return inserted\n })\n return {\n invitation: invitationContract({ ...row, inviterName: inviter?.name ?? null }),\n acceptanceURL: url\n }\n }\n\n return {\n async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {\n await requireAdmin(userId, workspaceId)\n await database\n .updateTable('workspace')\n .set({ name, updatedAt: new Date() })\n .where('id', '=', workspaceId)\n .execute()\n return membership(userId, workspaceId)\n },\n\n async list(userId: string, workspaceId: string): Promise<WorkspaceMembers> {\n const workspace = await membership(userId, workspaceId)\n const members = await memberUsers(workspaceId)\n .select([\n 'workspaceMember.userId',\n 'workspaceMember.role',\n 'workspaceMember.createdAt',\n 'user.name',\n 'user.email',\n 'user.image'\n ])\n .orderBy('workspaceMember.createdAt')\n .execute()\n const invitations =\n workspace.role === 'admin'\n ? await database\n .selectFrom('workspaceInvitation')\n .leftJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('workspaceInvitation.invitedBy')\n )\n )\n )\n .select([\n 'workspaceInvitation.id',\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.invitedAt',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.invitedBy',\n 'user.name as inviterName'\n ])\n .where('workspaceInvitation.workspaceId', '=', workspaceId)\n .where('workspaceInvitation.acceptedAt', 'is', null)\n .where('workspaceInvitation.revokedAt', 'is', null)\n .where('workspaceInvitation.expiresAt', '>', new Date())\n .orderBy('workspaceInvitation.invitedAt')\n .execute()\n : []\n return {\n members: members.map((member) => ({\n userId: member.userId,\n name: member.name,\n email: member.email,\n image: member.image,\n role: member.role,\n joinedAt: dateString(member.createdAt) ?? ''\n })),\n invitations: invitations.map(invitationContract)\n }\n },\n\n invite,\n\n /** Sends a waiting invitation again with a new link; the old link stops working. */\n async resendInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<CreatedWorkspaceInvitation> {\n await requireAdmin(userId, workspaceId)\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select(['emailNormalized', 'role'])\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (!invitation) throw new WorkspaceNotFoundError()\n return invite(userId, workspaceId, {\n email: invitation.emailNormalized,\n role: invitation.role\n })\n },\n\n async revokeInvitation(\n userId: string,\n workspaceId: string,\n invitationId: string\n ): Promise<void> {\n await requireAdmin(userId, workspaceId)\n const result = await database\n .updateTable('workspaceInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('workspaceId', '=', workspaceId)\n .where('acceptedAt', 'is', null)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new WorkspaceNotFoundError()\n },\n\n async updateRole(\n userId: string,\n workspaceId: string,\n memberId: string,\n role: WorkspaceRole\n ): Promise<void> {\n await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n if (member.role === 'admin' && role !== 'admin') {\n if ((await adminCount(transaction, workspaceId)) <= 1) throw new WorkspaceLastAdminError()\n }\n await transaction\n .updateTable('workspaceMember')\n .set({ role })\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n })\n },\n\n /** Deletes an empty workspace, with its members and invitations. */\n async delete(userId: string, workspaceId: string): Promise<void> {\n await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n // Locked first, so a document created meanwhile waits and then finds no workspace.\n await transaction\n .selectFrom('workspace')\n .select('id')\n .where('id', '=', workspaceId)\n .forUpdate()\n .executeTakeFirstOrThrow()\n const documents = await transaction\n .selectFrom('document')\n .select(['deletedAt'])\n .where('workspaceId', '=', workspaceId)\n .execute()\n if (documents.some((document) => document.deletedAt === null)) {\n throw new WorkspaceNotEmptyError('documents')\n }\n if (documents.length > 0) throw new WorkspaceNotEmptyError('pending-cleanup')\n await transaction.deleteFrom('workspace').where('id', '=', workspaceId).execute()\n })\n },\n\n /** Removes a member, or lets someone leave; the last administrator cannot go. */\n async remove(userId: string, workspaceId: string, memberId: string): Promise<void> {\n if (memberId === userId) await membership(userId, workspaceId)\n else await requireAdmin(userId, workspaceId)\n await database.transaction().execute(async (transaction) => {\n const member = await lockedMember(transaction, workspaceId, memberId)\n if (member.role === 'admin' && (await adminCount(transaction, workspaceId)) <= 1) {\n throw new WorkspaceLastAdminError()\n }\n await transaction\n .deleteFrom('workspaceMember')\n .where('workspaceId', '=', workspaceId)\n .where('userId', '=', memberId)\n .execute()\n })\n },\n\n /** What a workspace invitation link offers, or null when the id is not one. */\n async preview(invitationId: string, token: string): Promise<InvitationPreview | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .innerJoin('workspace', 'workspace.id', 'workspaceInvitation.workspaceId')\n .select([\n 'workspaceInvitation.emailNormalized',\n 'workspaceInvitation.role',\n 'workspaceInvitation.tokenHash',\n 'workspaceInvitation.expiresAt',\n 'workspaceInvitation.acceptedAt',\n 'workspaceInvitation.revokedAt',\n 'workspaceInvitation.invitedBy',\n 'workspace.name as workspaceName'\n ])\n .where('workspaceInvitation.id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (!invitationTokenIsActive(invitation, token)) throw new WorkspaceInvitationInvalidError()\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'workspace',\n workspaceName: invitation.workspaceName,\n role: invitation.role,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n },\n\n /**\n * Joins the workspace an invitation names, or returns null when the id is not a workspace\n * invitation. Someone already in it keeps the role they have.\n */\n async accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null> {\n const invitation = await database\n .selectFrom('workspaceInvitation')\n .select([\n 'workspaceId',\n 'emailNormalized',\n 'role',\n 'tokenHash',\n 'expiresAt',\n 'acceptedAt',\n 'revokedAt'\n ])\n .where('id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation) return null\n if (\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, token)\n ) {\n throw new WorkspaceInvitationInvalidError()\n }\n return database.transaction().execute(async (transaction) => {\n await transaction\n .insertInto('workspaceMember')\n .values({\n workspaceId: invitation.workspaceId,\n userId: actor.userId,\n role: invitation.role\n })\n .onConflict((conflict) => conflict.columns(['workspaceId', 'userId']).doNothing())\n .execute()\n await transaction\n .updateTable('workspaceInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n const member = await transaction\n .selectFrom('workspaceMember')\n .select('role')\n .where('workspaceId', '=', invitation.workspaceId)\n .where('userId', '=', actor.userId)\n .executeTakeFirstOrThrow()\n return { workspaceId: invitation.workspaceId, role: member.role }\n })\n }\n }\n}\n\nexport type WorkspaceMemberService = ReturnType<typeof createWorkspaceMemberService>\n","import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents'\nimport {\n DocumentShareInvalidError,\n DocumentShareSignInRequiredError,\n InvitationDeliveryError\n} from '#cloud/server/sharing/errors'\nimport { WorkspaceInvitationInvalidError } from '#cloud/server/workspaces/members'\nimport type { Context } from 'hono'\n\nexport function sharingDomainError(context: Context, error: unknown): Response | null {\n if (\n error instanceof DocumentNotFoundError ||\n error instanceof DocumentShareInvalidError ||\n error instanceof WorkspaceInvitationInvalidError\n ) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n if (error instanceof InvitationDeliveryError) {\n return context.json({ error: { code: 'invitation_delivery_failed' as const } }, 502)\n }\n if (error instanceof DocumentForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n return null\n}\n\nexport async function sharingRoute<T>(\n context: Context,\n action: () => Promise<T>\n): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n const response = sharingDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n","import type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\n\n/**\n * Who follows a link: the person signed in to the server, if any, whom the server lets in where\n * it turns guests away.\n */\nexport async function shareActor(\n request: Request,\n resolveSession?: CloudSessionResolver\n): Promise<CloudActor | undefined> {\n return resolveSession ? ((await resolveSession(request)) ?? undefined) : undefined\n}\n","import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport type { DocumentService } from '#cloud/server/documents'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport { shareParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono } from 'hono'\n\nimport { shareActor } from './actor'\n\nexport function createPublicDocumentRoutes(\n sharing: DocumentSharingService,\n documents: DocumentService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post(\n '/shares/:shareId/document',\n shareParams,\n validatedJSON(parseResolveDocumentShare),\n (context) =>\n sharingRoute(context, async () => {\n const resolution = await sharing.resolveShare(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json({\n resolution,\n document: await documents.downloadShared(resolution.documentId)\n })\n })\n )\n .post(\n '/shares/:shareId/images',\n shareParams,\n validatedJSON(parseRequestSharedImageLinks),\n (context) =>\n sharingRoute(context, async () => {\n const { checksums, ...share } = context.req.valid('json')\n const resolution = await sharing.resolveShare(\n context.req.valid('param').shareId,\n share,\n await shareActor(context.req.raw, resolveSession)\n )\n return context.json(await documents.imageLinksShared(resolution.documentId, checksums))\n })\n )\n}\n","import type {\n AcceptDocumentInvitationInput,\n AcceptedInvitation,\n CreateDocumentInvitationInput,\n CreateInvitationContinuationInput,\n DocumentInvitation,\n InvitationPreview,\n WorkspaceRole\n} from '#cloud/contract'\nimport { cloudInvitationURL } from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { Kysely } from 'kysely'\n\nimport { randomHex } from '@open-pencil/scene-graph/random'\n\nimport { requireSharingAccess } from '../access'\nimport {\n createInvitationContinuationService,\n invitationMatchesActor,\n invitationTokenIsActive,\n recipientHint\n} from '../continuation'\nimport { dateString, grantContract, invitationContract } from '../contracts'\nimport { hashCapability } from '../crypto'\nimport { DocumentShareInvalidError, InvitationDeliveryError } from '../errors'\n\nconst INVITATION_SECRET_BYTES = 24\nconst INVITATION_LIFETIME_MS = 7 * 24 * 60 * 60_000\n\n/** Workspace invitations share the invitation link; their ids are not document invitations. */\nexport type WorkspaceInvitationResolver = {\n preview(invitationId: string, token: string): Promise<InvitationPreview | null>\n accept(\n actor: CloudActor,\n invitationId: string,\n token: string\n ): Promise<{ workspaceId: string; role: WorkspaceRole } | null>\n}\n\nexport type InvitationServiceOptions = {\n workspaceInvitations?: WorkspaceInvitationResolver\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n}\n\nexport function createInvitationService(\n database: Kysely<CloudDatabase>,\n options: InvitationServiceOptions\n) {\n async function previewDocumentInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const invitation = await database\n .selectFrom('documentInvitation')\n .innerJoin('document', 'document.id', 'documentInvitation.documentId')\n .select([\n 'documentInvitation.emailNormalized',\n 'documentInvitation.permission',\n 'documentInvitation.tokenHash',\n 'documentInvitation.expiresAt',\n 'documentInvitation.acceptedAt',\n 'documentInvitation.revokedAt',\n 'documentInvitation.invitedBy',\n 'document.name as documentName'\n ])\n .where('documentInvitation.id', '=', invitationId)\n .executeTakeFirst()\n if (!invitation || !invitationTokenIsActive(invitation, input.token)) {\n throw new DocumentShareInvalidError()\n }\n const inviter = await database\n .selectFrom('user')\n .select('name')\n .where('id', '=', invitation.invitedBy)\n .executeTakeFirst()\n return {\n kind: 'document',\n documentName: invitation.documentName,\n inviterName: inviter?.name ?? 'An OpenPencil user',\n permission: invitation.permission,\n expiresAt: dateString(invitation.expiresAt) ?? '',\n recipientHint: recipientHint(invitation.emailNormalized)\n }\n }\n\n const continuation = options.continuationSecret\n ? createInvitationContinuationService(\n database,\n options.continuationSecret,\n // Continuations are kept for document invitations only.\n async (invitationId, token) => previewDocumentInvitation(invitationId, { token })\n )\n : null\n\n return {\n async listInvitations(userId: string, documentId: string): Promise<DocumentInvitation[]> {\n await requireSharingAccess(database, userId, documentId)\n const rows = await database\n .selectFrom('documentInvitation')\n .select([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .orderBy('invitedAt')\n .execute()\n return rows.map(invitationContract)\n },\n\n async createInvitation(\n userId: string,\n documentId: string,\n input: CreateDocumentInvitationInput\n ): Promise<{ invitation: DocumentInvitation; token: string }> {\n await requireSharingAccess(database, userId, documentId)\n const id = crypto.randomUUID()\n const token = randomHex(INVITATION_SECRET_BYTES)\n const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)\n const deliveryContext =\n (options.delivery || options.outbox) && options.publicURL\n ? await Promise.all([\n database\n .selectFrom('user')\n .select('name')\n .where('id', '=', userId)\n .executeTakeFirst(),\n database\n .selectFrom('document')\n .select('name')\n .where('id', '=', documentId)\n .executeTakeFirstOrThrow()\n ])\n : null\n const acceptanceURL =\n deliveryContext && options.publicURL\n ? cloudInvitationURL(options.publicURL, id, token)\n : null\n const message =\n deliveryContext && acceptanceURL\n ? {\n deliveryId: id,\n recipientEmail: input.email,\n inviterName: deliveryContext[0]?.name ?? 'An OpenPencil user',\n documentName: deliveryContext[1].name,\n permission: input.permission,\n expiresAt: expiresAt.toISOString(),\n acceptanceURL\n }\n : null\n const row = await database.transaction().execute(async (transaction) => {\n const inserted = await transaction\n .insertInto('documentInvitation')\n .values({\n id,\n documentId,\n emailNormalized: input.email,\n permission: input.permission,\n tokenHash: hashCapability(token),\n invitedBy: userId,\n expiresAt,\n acceptedAt: null,\n revokedAt: null\n })\n .returning([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'invitedAt',\n 'expiresAt',\n 'acceptedAt'\n ])\n .executeTakeFirstOrThrow()\n if (options.outbox && message) {\n await options.outbox.enqueueDocumentInvitation(message, transaction)\n }\n return inserted\n })\n const invitation = invitationContract(row)\n if (options.delivery && message && !options.outbox) {\n try {\n await options.delivery.sendDocumentInvitation(message)\n } catch (error) {\n await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', id)\n .execute()\n throw new InvitationDeliveryError('Invitation delivery failed', { cause: error })\n }\n }\n return { invitation, token }\n },\n\n async createInvitationContinuation(input: CreateInvitationContinuationInput) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.create(input)\n },\n\n async consumeInvitationContinuation(id: string) {\n if (!continuation) throw new DocumentShareInvalidError()\n return continuation.consume(id)\n },\n\n /** What an invitation link offers: a document, or a workspace when the id is one of those. */\n async previewInvitation(\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<InvitationPreview> {\n const workspace = await options.workspaceInvitations?.preview(invitationId, input.token)\n return workspace ?? previewDocumentInvitation(invitationId, input)\n },\n\n async acceptInvitation(\n actor: CloudActor,\n invitationId: string,\n input: AcceptDocumentInvitationInput\n ): Promise<AcceptedInvitation> {\n const workspace = await options.workspaceInvitations?.accept(actor, invitationId, input.token)\n if (workspace) return { kind: 'workspace', ...workspace }\n const invitation = await database\n .selectFrom('documentInvitation')\n .select([\n 'id',\n 'documentId',\n 'emailNormalized',\n 'permission',\n 'invitedBy',\n 'tokenHash',\n 'expiresAt',\n 'acceptedAt',\n 'revokedAt'\n ])\n .where('id', '=', invitationId)\n .executeTakeFirst()\n if (\n !invitation ||\n !invitationMatchesActor(actor, invitation.emailNormalized) ||\n !invitationTokenIsActive(invitation, input.token)\n ) {\n throw new DocumentShareInvalidError()\n }\n return database.transaction().execute(async (transaction) => {\n const row = await transaction\n .insertInto('documentGrant')\n .values({\n id: crypto.randomUUID(),\n documentId: invitation.documentId,\n userId: actor.userId,\n permission: invitation.permission,\n // The grant is the inviter's, so \"shared by\" names them, not the recipient.\n createdBy: invitation.invitedBy,\n revokedAt: null\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'userId']).doUpdateSet({\n permission: invitation.permission,\n createdBy: invitation.invitedBy,\n revokedAt: null,\n updatedAt: new Date()\n })\n )\n .returning([\n 'id',\n 'documentId',\n 'userId',\n 'permission',\n 'createdBy',\n 'createdAt',\n 'updatedAt'\n ])\n .executeTakeFirstOrThrow()\n await transaction\n .updateTable('documentInvitation')\n .set({ acceptedAt: new Date() })\n .where('id', '=', invitationId)\n .where('acceptedAt', 'is', null)\n .execute()\n return { kind: 'document' as const, grant: grantContract(row) }\n })\n },\n\n async revokeInvitation(\n userId: string,\n documentId: string,\n invitationId: string\n ): Promise<void> {\n await requireSharingAccess(database, userId, documentId)\n const result = await database\n .updateTable('documentInvitation')\n .set({ revokedAt: new Date() })\n .where('id', '=', invitationId)\n .where('documentId', '=', documentId)\n .where('revokedAt', 'is', null)\n .executeTakeFirst()\n if (Number(result.numUpdatedRows) === 0) throw new DocumentNotFoundError()\n }\n }\n}\n\nexport type InvitationService = ReturnType<typeof createInvitationService>\n","import {\n parseAcceptDocumentInvitation,\n parseCreateInvitationContinuation,\n parseCreateDocumentInvitation,\n parseLookupCloudUser,\n parseCreateDocumentShare,\n parsePutDocumentGrant,\n parseResolveDocumentShare,\n parseUpdateDocumentShare\n} from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport { sharingRoute } from '#cloud/server/sharing/http'\nimport type { DocumentSharingService } from '#cloud/server/sharing/service'\nimport {\n documentInvitationParams,\n documentParams,\n documentShareParams,\n documentUserParams,\n invitationContinuationParams,\n invitationParams,\n shareParams,\n validatedJSON\n} from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nimport { shareActor } from './actor'\n\nexport type SharingRouteEnvironment = {\n Variables: { actor: CloudActor }\n}\n\nexport function createDocumentSharingRoutes(\n service: DocumentSharingService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<SharingRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/invitations',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('documentId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .post(\n '/documents/:documentId/users/lookup',\n documentParams,\n validatedJSON(parseLookupCloudUser),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n user: await service.lookupUser(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n )\n })\n )\n )\n .get('/documents/:documentId/users/:userId', documentUserParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n user: await service.userProfile(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId\n )\n })\n )\n )\n .get('/documents/:documentId/shares', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n shares: await service.listShares(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/shares',\n documentParams,\n validatedJSON(parseCreateDocumentShare),\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/shares/:shareId',\n documentShareParams,\n validatedJSON(parseUpdateDocumentShare),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n share: await service.updateShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId,\n context.req.valid('json')\n )\n })\n )\n )\n .post('/documents/:documentId/shares/:shareId/rotate', documentShareParams, (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.rotateShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId\n )\n )\n )\n )\n .delete('/documents/:documentId/shares/:shareId', documentShareParams, (context) =>\n sharingRoute(context, async () => {\n await service.revokeShare(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').shareId\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/grants', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n grants: await service.listGrants(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .put(\n '/documents/:documentId/grants/:userId',\n documentUserParams,\n validatedJSON(parsePutDocumentGrant),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n grant: await service.putGrant(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId,\n context.req.valid('json')\n )\n })\n )\n )\n .delete('/documents/:documentId/grants/:userId', documentUserParams, (context) =>\n sharingRoute(context, async () => {\n await service.revokeGrant(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').userId\n )\n return context.body(null, 204)\n })\n )\n .get('/documents/:documentId/invitations', documentParams, (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitations: await service.listInvitations(\n context.get('actor').userId,\n context.req.valid('param').documentId\n )\n })\n )\n )\n .post(\n '/documents/:documentId/invitations',\n documentParams,\n validatedJSON(parseCreateDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.createInvitation(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post(\n '/invitations/:invitationId/accept',\n invitationParams,\n validatedJSON(parseAcceptDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n accepted: await service.acceptInvitation(\n context.get('actor'),\n context.req.valid('param').invitationId,\n context.req.valid('json')\n )\n })\n )\n )\n .delete(\n '/documents/:documentId/invitations/:invitationId',\n documentInvitationParams,\n (context) =>\n sharingRoute(context, async () => {\n await service.revokeInvitation(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').invitationId\n )\n return context.body(null, 204)\n })\n )\n}\n\nexport function createPublicSharingRoutes(\n service: DocumentSharingService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono()\n .post(\n '/invitations/continuations',\n validatedJSON(parseCreateInvitationContinuation),\n (context) =>\n sharingRoute(context, async () =>\n context.json(await service.createInvitationContinuation(context.req.valid('json')), 201)\n )\n )\n .post(\n '/invitations/continuations/:continuationId/consume',\n invitationContinuationParams,\n (context) =>\n sharingRoute(context, async () =>\n context.json(\n await service.consumeInvitationContinuation(context.req.valid('param').continuationId)\n )\n )\n )\n .post(\n '/invitations/:invitationId/preview',\n invitationParams,\n validatedJSON(parseAcceptDocumentInvitation),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n invitation: await service.previewInvitation(\n context.req.valid('param').invitationId,\n context.req.valid('json')\n )\n })\n )\n )\n .post(\n '/shares/:shareId/resolve',\n shareParams,\n validatedJSON(parseResolveDocumentShare),\n (context) =>\n sharingRoute(context, async () =>\n context.json({\n resolution: await service.resolveShare(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n await shareActor(context.req.raw, resolveSession)\n )\n })\n )\n )\n}\n","import type { CloudUserProfile, LookupCloudUserInput } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nimport { requireSharingAccess } from './access'\nimport {\n createCapabilityService,\n type DocumentShareCapability,\n type ResolvedDocumentShare,\n type ResolvedSharePrincipal\n} from './capabilities/service'\nimport { createGrantService } from './grants/service'\nimport { createInvitationService, type WorkspaceInvitationResolver } from './invitations/service'\n\nexport type { DocumentShareCapability, ResolvedDocumentShare, ResolvedSharePrincipal }\n\nexport type DocumentSharingServiceOptions = {\n continuationSecret?: string\n delivery?: InvitationDelivery\n outbox?: InvitationOutbox\n publicURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n workspaceInvitations?: WorkspaceInvitationResolver\n}\n\nexport function createDocumentSharingService(\n database: Kysely<CloudDatabase>,\n options: DocumentSharingServiceOptions = {}\n) {\n const capabilities = createCapabilityService(database, options)\n const grants = createGrantService(database)\n const invitations = createInvitationService(database, options)\n\n return {\n async lookupUser(\n userId: string,\n documentId: string,\n input: LookupCloudUserInput\n ): Promise<CloudUserProfile | null> {\n await requireSharingAccess(database, userId, documentId)\n const user = await database\n .selectFrom('user')\n .select(['id', 'name', 'email', 'image'])\n .where((expression) =>\n expression(expression.fn('lower', [expression.ref('email')]), '=', input.email)\n )\n .executeTakeFirst()\n return user ?? null\n },\n\n async userProfile(\n userId: string,\n documentId: string,\n profileUserId: string\n ): Promise<CloudUserProfile | null> {\n await requireSharingAccess(database, userId, documentId)\n // Only people connected to this document: its owner, its workspace's members, the holders\n // and givers of its grants, and the people who invited others to it. User IDs are text in\n // these tables, so they are compared with the requested ID rather than `user.id`.\n const related = await database\n .selectFrom('document')\n .select('document.id')\n .where('document.id', '=', documentId)\n .where((expression) =>\n expression.or([\n expression('document.createdBy', '=', profileUserId),\n expression.exists(\n expression\n .selectFrom('workspaceMember')\n .select('workspaceMember.userId')\n .whereRef('workspaceMember.workspaceId', '=', 'document.workspaceId')\n .where('workspaceMember.userId', '=', profileUserId)\n ),\n expression.exists(\n expression\n .selectFrom('documentGrant')\n .select('documentGrant.id')\n .whereRef('documentGrant.documentId', '=', 'document.id')\n .where((grant) =>\n grant.or([\n grant.and([\n grant('documentGrant.userId', '=', profileUserId),\n grant('documentGrant.revokedAt', 'is', null)\n ]),\n grant('documentGrant.createdBy', '=', profileUserId)\n ])\n )\n ),\n expression.exists(\n expression\n .selectFrom('documentInvitation')\n .select('documentInvitation.id')\n .whereRef('documentInvitation.documentId', '=', 'document.id')\n .where('documentInvitation.invitedBy', '=', profileUserId)\n )\n ])\n )\n .executeTakeFirst()\n if (!related) return null\n const user = await database\n .selectFrom('user')\n .select(['id', 'name', 'email', 'image'])\n .where('id', '=', profileUserId)\n .executeTakeFirst()\n return user ?? null\n },\n\n ...capabilities,\n ...grants,\n ...invitations\n }\n}\n\nexport type DocumentSharingService = ReturnType<typeof createDocumentSharingService>\n","import { parseResolveDocumentShare } from '#cloud/contract'\nimport type { CloudActor, CloudSessionResolver } from '#cloud/server/auth'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration/service'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport {\n CLOUD_RATE_LIMITS,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport { DocumentShareInvalidError, DocumentShareSignInRequiredError } from '#cloud/server/sharing'\nimport { documentParams, shareParams, validatedJSON } from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CollaborationRouteEnvironment = { Variables: { actor: CloudActor } }\n\nfunction notFound(context: Context, error: unknown): Response | null {\n if (error instanceof DocumentNotFoundError || error instanceof DocumentShareInvalidError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof DocumentShareSignInRequiredError) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return null\n}\n\nexport function createCollaborationRoutes(\n service: CollaborationTicketService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<CollaborationRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/documents/:documentId/collaboration-ticket',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.collaborationTicket,\n routeParamResource('documentId')\n )\n )\n }\n return router.post(\n '/documents/:documentId/collaboration-ticket',\n documentParams,\n async (context) => {\n try {\n return context.json({\n ticket: await service.issueUserTicket(\n context.get('actor'),\n context.req.valid('param').documentId\n )\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n\nexport function createPublicCollaborationRoutes(\n service: CollaborationTicketService,\n resolveSession?: CloudSessionResolver\n) {\n return new Hono().post(\n '/shares/:shareId/collaboration-ticket',\n shareParams,\n validatedJSON(parseResolveDocumentShare),\n async (context) => {\n try {\n return context.json({\n ticket: await service.issueShareTicket(\n context.req.valid('param').shareId,\n context.req.valid('json'),\n resolveSession ? ((await resolveSession(context.req.raw)) ?? undefined) : undefined\n )\n })\n } catch (error) {\n const response = notFound(context, error)\n if (response) return response\n throw error\n }\n }\n )\n}\n","import {\n RELAY_DOCUMENT_PARAM,\n type CollaborationPrincipal,\n type CollaborationTicket,\n type DocumentPermission,\n type ResolveDocumentShareInput\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { DocumentNotFoundError } from '#cloud/server/documents'\nimport { resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport { base64url, SignJWT } from 'jose'\nimport type { Kysely } from 'kysely'\nimport { withQuery } from 'ufo'\n\nconst TICKET_LIFETIME_SECONDS = 5 * 60\n\nasync function derivedRoomKey(authSecret: string, documentId: string, roomEpoch: number) {\n const inputBytes = new TextEncoder().encode(`${authSecret}:room:${documentId}:${roomEpoch}`)\n const key = await crypto.subtle.importKey('raw', inputBytes, 'HKDF', false, ['deriveBits'])\n const bits = await crypto.subtle.deriveBits(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new TextEncoder().encode(`openpencil-cloud:${documentId}`),\n info: new TextEncoder().encode(`collaboration-room:${roomEpoch}`)\n },\n key,\n 256\n )\n return base64url.encode(new Uint8Array(bits))\n}\n\nexport type CollaborationTicketClaims = {\n authSecret: string\n documentId: string\n principal: CollaborationPrincipal\n permission: DocumentPermission\n roomEpoch: number\n /**\n * The relay that enforces writes; without one the ticket is for peer-to-peer rooms. The ticket's\n * URL names the document, so a runtime can route the socket to where the room lives.\n */\n relayURL?: string\n}\n\n/** Signs a ticket for a document's collaboration room once access has been decided. */\nexport async function signCollaborationTicket({\n authSecret,\n documentId,\n principal,\n permission,\n roomEpoch,\n relayURL\n}: CollaborationTicketClaims): Promise<CollaborationTicket> {\n const issuedAt = Math.floor(Date.now() / 1000)\n const expiresAtSeconds = issuedAt + TICKET_LIFETIME_SECONDS\n const roomId = `cloud:${documentId}:${roomEpoch}`\n const roomKey = await derivedRoomKey(authSecret, documentId, roomEpoch)\n const claims = {\n documentId,\n roomId,\n principal,\n permission,\n roomEpoch,\n serverEnforcedWrites: Boolean(relayURL)\n }\n const token = await new SignJWT(claims)\n .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })\n .setIssuedAt(issuedAt)\n .setExpirationTime(expiresAtSeconds)\n .setSubject(principal.kind === 'user' ? principal.userId : principal.guestId)\n .sign(new TextEncoder().encode(authSecret))\n return {\n token,\n provider: relayURL ? ('relay' as const) : ('trystero' as const),\n ...(relayURL ? { serverURL: withQuery(relayURL, { [RELAY_DOCUMENT_PARAM]: documentId }) } : {}),\n ...claims,\n roomKey,\n expiresAt: new Date(expiresAtSeconds * 1000).toISOString()\n }\n}\n\nexport type CollaborationTicketServiceOptions = {\n database: Kysely<CloudDatabase>\n sharing: DocumentSharingService\n authSecret: string\n relayURL?: string\n policy?: CloudPolicy\n deploymentMode?: 'official' | 'self-hosted'\n}\n\nexport function createCollaborationTicketService({\n database,\n sharing,\n authSecret,\n relayURL,\n policy,\n deploymentMode = 'self-hosted'\n}: CollaborationTicketServiceOptions) {\n return {\n async issueUserTicket(actor: CloudActor, documentId: string): Promise<CollaborationTicket> {\n const access = await resolveDocumentAccess(database, actor.userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (policy) {\n const workspace = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', documentId)\n .executeTakeFirstOrThrow()\n if (\n !(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, {\n targetingKey: workspace.workspaceId,\n actorId: actor.userId,\n workspaceId: workspace.workspaceId,\n documentId,\n deploymentMode\n }))\n ) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId,\n principal: { kind: 'user', userId: actor.userId, name: actor.name, email: actor.email },\n permission: access.permission,\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n },\n\n async issueShareTicket(\n shareId: string,\n input: ResolveDocumentShareInput,\n actor?: CloudActor\n ): Promise<CollaborationTicket> {\n const resolved = await sharing.resolveShare(shareId, input, actor)\n if (policy) {\n const workspace = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', resolved.documentId)\n .executeTakeFirstOrThrow()\n const context = {\n targetingKey: workspace.workspaceId,\n ...(actor ? { actorId: actor.userId } : {}),\n workspaceId: workspace.workspaceId,\n documentId: resolved.documentId,\n deploymentMode\n }\n if (!(await policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context))) {\n throw new DocumentNotFoundError()\n }\n if (!actor && !(await policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context))) {\n throw new DocumentNotFoundError()\n }\n }\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', resolved.documentId)\n .where('deletedAt', 'is', null)\n .executeTakeFirst()\n if (!document) throw new DocumentNotFoundError()\n return signCollaborationTicket({\n authSecret,\n documentId: resolved.documentId,\n principal: resolved.principal,\n permission: resolved.permission,\n roomEpoch: document.collaborationEpoch,\n relayURL\n })\n }\n }\n}\n\nexport type CollaborationTicketService = ReturnType<typeof createCollaborationTicketService>\n","import {\n collaborationPrincipalSchema,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport { jwtVerify } from 'jose'\nimport * as v from 'valibot'\n\nconst relayClaimsSchema = v.object({\n documentId: v.pipe(v.string(), v.uuid()),\n roomId: v.string(),\n principal: collaborationPrincipalSchema,\n permission: v.picklist(['view', 'edit']),\n roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),\n serverEnforcedWrites: v.literal(true),\n exp: v.pipe(v.number(), v.integer())\n})\n\nexport type RelayAuthorization = {\n roomId: string\n documentId: string\n roomEpoch: number\n permission: DocumentPermission\n principal: CollaborationPrincipal\n /** When the ticket stops being valid, in milliseconds since the epoch. */\n expiresAt: number\n}\n\n/** Verifies a collaboration ticket issued for the relay; throws for anything else. */\nexport async function authorizeRelayTicket(\n token: string,\n authSecret: string\n): Promise<RelayAuthorization> {\n const verified = await jwtVerify(token, new TextEncoder().encode(authSecret), {\n algorithms: ['HS256']\n })\n const claims = v.parse(relayClaimsSchema, verified.payload)\n if (claims.roomId !== `cloud:${claims.documentId}:${claims.roomEpoch}`) {\n throw new Error('Collaboration ticket names a different room')\n }\n return {\n roomId: claims.roomId,\n documentId: claims.documentId,\n roomEpoch: claims.roomEpoch,\n permission: claims.permission,\n principal: claims.principal,\n expiresAt: claims.exp * 1000\n }\n}\n\nexport function principalKey(principal: CollaborationPrincipal): string {\n return principal.kind === 'user' ? `user:${principal.userId}` : `guest:${principal.guestId}`\n}\n","import {\n presenceName,\n type CloudPresence,\n type CollaborationPrincipal,\n type DocumentPermission\n} from '#cloud/contract'\nimport * as decoding from 'lib0/decoding'\nimport * as encoding from 'lib0/encoding'\nimport * as v from 'valibot'\n\nconst awarenessStateSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.looseObject({ user: v.optional(v.looseObject({})) })\n)\n\ntype AwarenessEntry = { clientId: number; clock: number; state: string }\n\nfunction decodeEntries(update: Uint8Array): AwarenessEntry[] | null {\n try {\n const decoder = decoding.createDecoder(update)\n const count = decoding.readVarUint(decoder)\n const entries: AwarenessEntry[] = []\n for (let index = 0; index < count; index++) {\n entries.push({\n clientId: decoding.readVarUint(decoder),\n clock: decoding.readVarUint(decoder),\n state: decoding.readVarString(decoder)\n })\n }\n return decoder.pos === update.byteLength ? entries : null\n } catch {\n return null\n }\n}\n\nfunction encodeEntries(entries: AwarenessEntry[]): Uint8Array {\n return encoding.encode((encoder) => {\n encoding.writeVarUint(encoder, entries.length)\n for (const entry of entries) {\n encoding.writeVarUint(encoder, entry.clientId)\n encoding.writeVarUint(encoder, entry.clock)\n encoding.writeVarString(encoder, entry.state)\n }\n })\n}\n\n/** Who the relay verified a peer to be, as other peers see it in presence. */\nexport type VerifiedPresence = {\n principal: CollaborationPrincipal\n permission: DocumentPermission\n}\n\nfunction verifiedIdentity({ principal, permission }: VerifiedPresence): CloudPresence {\n return {\n kind: principal.kind,\n id: principal.kind === 'user' ? principal.userId : principal.guestId,\n name: principal.name,\n permission\n }\n}\n\nexport type StampedAwareness = {\n /** The update to forward, or null when nothing in it may be forwarded. */\n update: Uint8Array | null\n /** Presence clients this update introduced for the peer. */\n claimed: number[]\n}\n\n/**\n * Rewrites a peer's presence update so others see who the relay verified rather than what the\n * peer claims: the display name comes from the ticket, and a `cloud` field carries the verified\n * identity and permission. Entries for presence clients another peer owns are dropped, so one\n * peer cannot speak for another; removals pass through for the peer's own clients only.\n */\nexport function stampAwareness(\n update: Uint8Array,\n presence: VerifiedPresence,\n ownedByOthers: (clientId: number) => boolean\n): StampedAwareness {\n const entries = decodeEntries(update)\n if (!entries) return { update: null, claimed: [] }\n const identity = verifiedIdentity(presence)\n const forwarded: AwarenessEntry[] = []\n const claimed: number[] = []\n for (const entry of entries) {\n if (ownedByOthers(entry.clientId)) continue\n if (entry.state === 'null') {\n forwarded.push(entry)\n continue\n }\n const parsed = v.safeParse(awarenessStateSchema, entry.state)\n if (!parsed.success) continue\n const state = {\n ...parsed.output,\n // The ticket's name, cut to what peers accept, so a long one cannot hide the member.\n user: { ...parsed.output.user, name: presenceName(identity.name) },\n cloud: identity\n }\n claimed.push(entry.clientId)\n forwarded.push({ ...entry, state: JSON.stringify(state) })\n }\n return { update: forwarded.length > 0 ? encodeEntries(forwarded) : null, claimed }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely } from 'kysely'\n\nimport type { CollaborationRelayOptions } from './hub'\n\n/** The relay's lookups of a document: its participant limit under `policy`, and its epoch. */\nexport function relayDocumentLookups(\n database: Kysely<CloudDatabase>,\n policy: CloudPolicy,\n deploymentMode: 'official' | 'self-hosted'\n): Pick<CollaborationRelayOptions, 'maximumParticipants' | 'currentRoomEpoch'> {\n return {\n async maximumParticipants(documentId) {\n const document = await database\n .selectFrom('document')\n .select('workspaceId')\n .where('id', '=', documentId)\n .executeTakeFirst()\n if (!document) return 0\n const limit = await policy.number(CLOUD_FEATURE_KEYS.maximumParticipants, -1, {\n targetingKey: document.workspaceId,\n workspaceId: document.workspaceId,\n documentId,\n deploymentMode\n })\n return limit < 0 ? null : limit\n },\n async currentRoomEpoch(documentId) {\n const document = await database\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', documentId)\n .executeTakeFirst()\n return document?.collaborationEpoch ?? null\n }\n }\n}\n","import {\n createRelayClientAssembler,\n decodeRelayClientFrame,\n MAX_COLLAB_MESSAGE_BYTES,\n RELAY_CLOSE,\n type RelayClientFrame\n} from '#cloud/contract'\n\nimport { authorizeRelayTicket, principalKey, type RelayAuthorization } from './authorize'\nimport type { RelayPeerState } from './resume'\n\n/** One client's socket, as a runtime adapter hands it to the relay. */\nexport type RelaySocket = {\n send(data: Uint8Array): void\n close(code: number, reason: string): void\n /**\n * Keeps the peer's state with the socket, for a runtime that sets the relay aside while sockets\n * stay open and resumes their peers with `resume` when it wakes.\n */\n remember?(state: RelayPeerState): void\n}\n\n/** What the adapter reports back about that socket. */\nexport type RelayConnection = {\n receive(data: Uint8Array): void\n closed(): void\n}\n\n/** A socket admitted to a room, as the person and permission its ticket names. */\nexport type RelayPeer = {\n id: string\n socket: RelaySocket\n authorization: RelayAuthorization\n presenceClients: Set<number>\n}\n\n/** A room message from an admitted peer. */\nexport type RelayRoomFrame = Extract<RelayClientFrame, { type: 'message' }>\n\n/** What a connection asks of the relay it belongs to. */\nexport type ConnectionRelay = {\n authSecret: string\n /** The one document the relay serves, when it serves one. */\n documentId?: string\n maximumMessageBytes: number\n authTimeoutMs: number\n /** Admits a newcomer whose ticket verified, or turns it away and answers null. */\n admit(socket: RelaySocket, authorization: RelayAuthorization): Promise<RelayPeer | null>\n /** Takes a refreshed ticket for a peer already in its room. */\n refreshed(peer: RelayPeer): void\n /** Handles a peer's room message; a promise while it waits for the room's document. */\n deliver(peer: RelayPeer, frame: RelayRoomFrame): Promise<void> | undefined\n depart(peer: RelayPeer): void\n report(message: string, error: unknown): void\n}\n\n/**\n * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with\n * the peer it already is. It joins fragmented frames, holds what arrives while a ticket is checked\n * or the room's document loads, and refreshes tickets.\n */\nexport function openRelayConnection(\n socket: RelaySocket,\n resumed: RelayPeer | null,\n relay: ConnectionRelay\n): RelayConnection {\n let peer: RelayPeer | null = resumed\n /** Read through an object, since it changes across awaits and between messages. */\n const state = { closed: false, busy: false }\n const isClosed = () => state.closed\n const queued: Uint8Array[] = []\n let queuedBytes = 0\n // Only an editor's writes can be large: a viewer's frames, and a peer's before it is\n // admitted, fit in one message, so nobody else can make the relay hold more.\n const assembler = createRelayClientAssembler(() =>\n peer?.authorization.permission === 'edit' ? MAX_COLLAB_MESSAGE_BYTES : relay.maximumMessageBytes\n )\n const authTimer = resumed\n ? undefined\n : setTimeout(\n () => socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket'),\n relay.authTimeoutMs\n )\n\n async function authenticate(token: string) {\n let authorization: RelayAuthorization\n try {\n authorization = await authorizeRelayTicket(token, relay.authSecret)\n } catch {\n socket.close(RELAY_CLOSE.unauthorized, 'Invalid collaboration ticket')\n return\n }\n if (relay.documentId !== undefined && authorization.documentId !== relay.documentId) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different document')\n return\n }\n if (state.closed) return\n if (peer) {\n // A refreshed ticket keeps the peer in its room as the same person; a lowered\n // permission applies from now on.\n const current = peer.authorization\n if (\n authorization.roomId !== current.roomId ||\n principalKey(authorization.principal) !== principalKey(current.principal)\n ) {\n socket.close(RELAY_CLOSE.unauthorized, 'Ticket is for a different room or person')\n return\n }\n peer.authorization = authorization\n relay.refreshed(peer)\n return\n }\n clearTimeout(authTimer)\n const admitted = await relay.admit(socket, authorization)\n // The socket may have closed while the room loaded.\n if (admitted && isClosed()) relay.depart(admitted)\n else peer = admitted\n }\n\n function process(data: Uint8Array) {\n if (data.byteLength > relay.maximumMessageBytes) {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const assembled = assembler.push(data)\n if (assembled.type === 'partial') return\n if (assembled.type === 'too-large') {\n socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')\n return\n }\n const frame = assembled.type === 'frame' ? decodeRelayClientFrame(assembled.data) : null\n if (!frame) {\n socket.close(RELAY_CLOSE.protocol, 'Malformed collaboration frame')\n return\n }\n if (frame.type === 'auth') {\n state.busy = true\n void authenticate(frame.token)\n .catch((error: unknown) => {\n relay.report('Admitting a collaboration peer failed:', error)\n socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')\n })\n .finally(() => {\n state.busy = false\n flush()\n })\n return\n }\n if (!peer) {\n socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n return\n }\n const delivered = relay.deliver(peer, frame)\n if (!delivered) return\n // The room's document is loading; this peer's later messages wait for it.\n state.busy = true\n void delivered.finally(() => {\n state.busy = false\n flush()\n })\n }\n\n function flush() {\n while (!state.busy && !state.closed && queued.length > 0) {\n const next = queued.shift()\n if (!next) continue\n queuedBytes -= next.byteLength\n process(next)\n }\n }\n\n return {\n receive(data) {\n if (state.closed) return\n queuedBytes += data.byteLength\n // Before admission a peer has sent its ticket and has nothing else to say, so what\n // waits for the room to open is held to one message's worth.\n if (!peer && queuedBytes > relay.maximumMessageBytes) {\n queued.length = 0\n queuedBytes = 0\n socket.close(RELAY_CLOSE.messageTooLarge, 'Too much sent before joining the room')\n return\n }\n queued.push(data)\n flush()\n },\n closed() {\n state.closed = true\n queued.length = 0\n queuedBytes = 0\n clearTimeout(authTimer)\n if (peer) relay.depart(peer)\n }\n }\n}\n","import * as Y from 'yjs'\n\nimport type { CollaborationRoomIdentity, CollaborationStateStore } from './persistence'\n\n/** When a room folds its log into a fresh snapshot: after this many updates or bytes logged. */\nexport type RoomLogLimits = { updates: number; bytes: number }\n\nexport type RoomLog = {\n /**\n * Saves what the document took since the last save: one merged update in the log, or a snapshot\n * in the log's place once it reaches its limits, as the room closes, or after a failed save.\n * Saves run one at a time; a refused one rejects, and the next save writes a snapshot.\n */\n save(options?: { closing?: boolean }): Promise<void>\n}\n\n/**\n * A room's document as its store saved it, its snapshot with the updates logged after it, and the\n * log its saves go to. Each room has one writer, the relay holding it, so sequences only grow.\n */\nexport async function openRoomLog(\n store: CollaborationStateStore,\n room: CollaborationRoomIdentity,\n limits: RoomLogLimits\n): Promise<{ document: Y.Doc; log: RoomLog }> {\n const saved = await store.load(room)\n const document = new Y.Doc()\n if (saved.snapshot) Y.applyUpdate(document, saved.snapshot)\n for (const update of saved.updates) Y.applyUpdate(document, update)\n\n /** Updates since the last save, which the next one logs. */\n let pending: Uint8Array[] = []\n document.on('update', (update: Uint8Array) => pending.push(update))\n /** The last sequence a save may have written: an append that failed may still have landed. */\n let sequence = saved.sequence\n let loggedCount = saved.updates.length\n let loggedBytes = saved.updates.reduce((total, update) => total + update.byteLength, 0)\n /** Set by a failed save, after which only a snapshot is sure to hold the room. */\n let compactNext = false\n /** The save in flight; the next one waits for it, so two never claim one sequence. */\n let saving: Promise<void> = Promise.resolve()\n\n async function write(closing: boolean) {\n const compact =\n compactNext ||\n loggedCount >= limits.updates ||\n loggedBytes >= limits.bytes ||\n (closing && (loggedCount > 0 || pending.length > 0))\n // Updates that arrive while this save is in flight go to the next one.\n const batch = pending\n pending = []\n if (compact) {\n await store.compact(room, sequence, Y.encodeStateAsUpdate(document))\n loggedCount = 0\n loggedBytes = 0\n compactNext = false\n } else if (batch.length > 0) {\n const update = Y.mergeUpdates(batch)\n sequence += 1\n await store.append(room, sequence, update)\n loggedCount += 1\n loggedBytes += update.byteLength\n }\n }\n\n const log: RoomLog = {\n save({ closing = false } = {}) {\n const run = saving.then(() => write(closing))\n saving = run.catch(() => {\n compactNext = true\n })\n return run\n }\n }\n return { document, log }\n}\n","import {\n COLLAB_ACTIONS,\n encodeSyncReply,\n decodeRoomUpdate,\n MAX_COLLAB_MESSAGE_BYTES,\n RELAY_CLOSE,\n RELAY_SERVER_PEER,\n relayServerMessages,\n type RelayServerFrame\n} from '#cloud/contract'\nimport * as Y from 'yjs'\n\nimport type { RelayAuthorization } from './authorize'\nimport { stampAwareness } from './awareness'\nimport {\n openRelayConnection,\n type ConnectionRelay,\n type RelayConnection,\n type RelayPeer,\n type RelayRoomFrame,\n type RelaySocket\n} from './connection'\nimport { openRoomLog, type RoomLog } from './log'\nimport type { CollaborationStateStore } from './persistence'\nimport type { RelayPeerState } from './resume'\n\nexport type { RelayConnection, RelaySocket } from './connection'\n\nexport type CollaborationRelayOptions = {\n authSecret: string\n store: CollaborationStateStore\n /**\n * The one document this relay serves, for runtimes that run a relay per document; tickets for\n * any other document are refused.\n */\n documentId?: string\n /**\n * The most one socket message may carry. An editor's larger frames arrive as fragments joined\n * up to `MAX_COLLAB_MESSAGE_BYTES`; anyone else's frame must fit in one message.\n */\n maximumMessageBytes: number\n maximumConnectionsPerRoom: number\n /** The participant limit policy sets for a document, or null for none. */\n maximumParticipants?: (documentId: string) => Promise<number | null>\n /**\n * The document's current collaboration epoch, which a restore advances; a ticket for an earlier\n * room is turned away so nobody rejoins the document as it was.\n */\n currentRoomEpoch?: (documentId: string) => Promise<number | null>\n /** How long after a change the room's document is saved. */\n persistDelayMs?: number\n /**\n * How many logged updates, or how many of their bytes, a room saves before it writes a fresh\n * snapshot in their place; a closing room always does.\n */\n compactAfterUpdates?: number\n compactAfterBytes?: number\n /** How long a room whose last save failed waits before saving again. */\n persistRetryMs?: number\n /** How long a socket may stay open without presenting a ticket. */\n authTimeoutMs?: number\n onError?: (message: string, error: unknown) => void\n}\n\n/** Messages a viewer may send; their document writes never leave the relay. */\nconst VIEWER_ACTIONS = new Set<string>([COLLAB_ACTIONS.syncStep1, COLLAB_ACTIONS.awareness])\n\ntype Peer = RelayPeer\n\n/** A room's document and the log its saves go to, loaded when a message first needs them. */\ntype RoomContent = { document: Y.Doc; log: RoomLog }\n\ntype Room = {\n id: string\n identity: { documentId: string; roomEpoch: number }\n peers: Map<string, Peer>\n persistTimer: ReturnType<typeof setTimeout> | null\n /**\n * Null until a message needs the document: peers resumed after the runtime woke the relay\n * exchange presence without it, so a wake for presence alone loads nothing from the store.\n */\n content: RoomContent | null\n loading: Promise<RoomContent> | null\n}\n\nexport type CollaborationRelay = ReturnType<typeof createCollaborationRelay>\n\n/**\n * A runtime-neutral relay for collaboration rooms. It forwards room messages between peers and\n * joins every room as a peer itself: it holds the room's document, answers sync requests from\n * it, saves it, drops document writes from viewers, and stamps presence with verified identity.\n */\nexport function createCollaborationRelay(options: CollaborationRelayOptions) {\n const rooms = new Map<string, Room>()\n const opening = new Map<string, Promise<Room>>()\n /** Rooms whose last peer left and whose document is still being saved. */\n const closing = new Map<string, Promise<void>>()\n /** Set by `close()`: a failed save then drops the room instead of retrying. */\n let shuttingDown = false\n const persistDelayMs = options.persistDelayMs ?? 2_000\n const persistRetryMs = options.persistRetryMs ?? 30_000\n const logLimits = {\n updates: options.compactAfterUpdates ?? 500,\n bytes: options.compactAfterBytes ?? 4 * 1024 * 1024\n }\n const authTimeoutMs = options.authTimeoutMs ?? 10_000\n const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error))\n\n function send(socket: RelaySocket, frame: RelayServerFrame) {\n for (const message of relayServerMessages(frame)) socket.send(message)\n }\n\n function sendAll(sockets: Iterable<RelaySocket>, frame: RelayServerFrame) {\n const messages = relayServerMessages(frame)\n for (const socket of sockets) for (const message of messages) socket.send(message)\n }\n\n async function openRoom(authorization: RelayAuthorization): Promise<Room> {\n const existing = rooms.get(authorization.roomId)\n if (existing) return existing\n const pending = opening.get(authorization.roomId)\n if (pending) return pending\n const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }\n const created = (async () => {\n // A room reopened while its last save is in flight must load what that save writes, or,\n // when the save failed, take the room it kept.\n await closing.get(authorization.roomId)\n // A room resumed without its document loads it in place; a new one joins the rooms once\n // loaded, so a restore while it loads finds nothing to end and the epoch check turns it away.\n const room = rooms.get(authorization.roomId) ?? newRoom(authorization.roomId, identity)\n await contentOf(room)\n if (!rooms.has(room.id)) rooms.set(room.id, room)\n return room\n })()\n opening.set(authorization.roomId, created)\n try {\n return await created\n } finally {\n opening.delete(authorization.roomId)\n }\n }\n\n function newRoom(id: string, identity: Room['identity']): Room {\n return { id, identity, peers: new Map(), persistTimer: null, content: null, loading: null }\n }\n\n /** The room's document and log, loaded from the store the first time something needs them. */\n function contentOf(room: Room): Promise<RoomContent> {\n if (room.content) return Promise.resolve(room.content)\n room.loading ??= openRoomLog(options.store, room.identity, logLimits).then(\n (content) => {\n content.document.on('update', () => schedulePersist(room))\n room.content = content\n return content\n },\n (error: unknown) => {\n room.loading = null\n throw error\n }\n )\n return room.loading\n }\n\n /** Saves what changed in the room since its last save; false when the store refused it. */\n async function persist(room: Room, closing = false): Promise<boolean> {\n if (room.persistTimer) clearTimeout(room.persistTimer)\n room.persistTimer = null\n // A room nobody needed the document of since it was resumed has nothing new to save, but\n // a closing one loads it anyway, to fold what its earlier wakes logged into a snapshot.\n if (!room.content && !closing) return true\n try {\n const { log } = await contentOf(room)\n await log.save({ closing })\n return true\n } catch (error) {\n report('Saving a collaboration room failed:', error)\n // The room holds edits the store doesn't have; save again without waiting for another edit.\n // A closing room retries through `saveAndClose`.\n if (!closing && rooms.get(room.id) === room) {\n room.persistTimer ??= setTimeout(() => void persist(room), persistRetryMs)\n }\n return false\n }\n }\n\n function schedulePersist(room: Room) {\n room.persistTimer ??= setTimeout(() => void persist(room), persistDelayMs)\n }\n\n /**\n * Applies a peer's V2 update to the room, inflated first for a sync reply. Rooms are saved as\n * V1 updates; only what peers exchange is V2.\n */\n function applyToRoom(\n document: Y.Doc,\n peer: Peer,\n namespace: string,\n payload: Uint8Array\n ): boolean {\n try {\n const update = decodeRoomUpdate(payload, {\n limit: MAX_COLLAB_MESSAGE_BYTES,\n compressed: namespace === COLLAB_ACTIONS.syncReply\n })\n if (!update) {\n peer.socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration update is too large')\n return false\n }\n Y.applyUpdateV2(document, update, peer.id)\n return true\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed document update')\n return false\n }\n }\n\n function forward(\n room: Room,\n from: Peer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const frame: RelayServerFrame = { type: 'message', namespace, from: from.id, payload }\n const recipients = target\n ? [room.peers.get(target)]\n : [...room.peers.values()].filter((peer) => peer !== from)\n sendAll(deliverable(recipients.flatMap((peer) => (peer ? [peer] : []))), frame)\n }\n\n function handleServerMessage(\n document: Y.Doc,\n peer: Peer,\n namespace: string,\n payload: Uint8Array\n ) {\n if (namespace === COLLAB_ACTIONS.syncStep1) {\n let reply: Uint8Array\n try {\n reply = encodeSyncReply(document, payload)\n } catch {\n peer.socket.close(RELAY_CLOSE.protocol, 'Malformed state vector')\n return\n }\n send(peer.socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncReply,\n from: RELAY_SERVER_PEER,\n payload: reply\n })\n } else if (namespace === COLLAB_ACTIONS.syncReply) {\n applyToRoom(document, peer, namespace, payload)\n }\n }\n\n /** Whether handling a message reads or writes the room's document. */\n function needsDocument(namespace: string, target: string | null): boolean {\n if (namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply)\n return true\n return target === RELAY_SERVER_PEER && namespace === COLLAB_ACTIONS.syncStep1\n }\n\n function handleMessage(\n room: Room,\n document: Y.Doc | null,\n peer: Peer,\n namespace: string,\n target: string | null,\n payload: Uint8Array\n ) {\n const readOnly = peer.authorization.permission === 'view'\n if (readOnly && !VIEWER_ACTIONS.has(namespace)) return\n // Only the server says the history changed.\n if (namespace === COLLAB_ACTIONS.versions) return\n\n let forwarded = payload\n if (namespace === COLLAB_ACTIONS.awareness) {\n const stamped = stampAwareness(payload, peer.authorization, (clientId) =>\n [...room.peers.values()].some(\n (other) => other !== peer && other.presenceClients.has(clientId)\n )\n )\n const known = peer.presenceClients.size\n for (const clientId of stamped.claimed) peer.presenceClients.add(clientId)\n if (peer.presenceClients.size !== known) remember(peer)\n if (!stamped.update) return\n forwarded = stamped.update\n }\n\n if (target === RELAY_SERVER_PEER) {\n if (document) handleServerMessage(document, peer, namespace, payload)\n return\n }\n if (\n (namespace === COLLAB_ACTIONS.yjsUpdate || namespace === COLLAB_ACTIONS.syncReply) &&\n !(document && applyToRoom(document, peer, namespace, payload))\n ) {\n return\n }\n forward(room, peer, namespace, target, forwarded)\n }\n\n /**\n * Whether the peer's ticket still holds, closing its socket when it lapsed. It is checked when\n * the relay hears from the peer and before it sends the peer anything, never by a timer, so a\n * runtime can set an idle relay aside while sockets stay open.\n */\n function current(peer: Peer): boolean {\n if (Date.now() < peer.authorization.expiresAt) return true\n peer.socket.close(RELAY_CLOSE.expired, 'Collaboration ticket expired')\n return false\n }\n\n /** The sockets of peers whose tickets still hold. */\n function deliverable(peers: Iterable<Peer>): RelaySocket[] {\n return [...peers].filter(current).map((peer) => peer.socket)\n }\n\n function remember(peer: Peer) {\n peer.socket.remember?.({\n peerId: peer.id,\n authorization: peer.authorization,\n presenceClients: [...peer.presenceClients]\n })\n }\n\n /** Handles a room message from an admitted peer; a promise while the room's document loads. */\n function deliver(peer: Peer, frame: RelayRoomFrame): Promise<void> | undefined {\n const room = rooms.get(peer.authorization.roomId)\n if (!room) {\n peer.socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket')\n return undefined\n }\n if (!current(peer)) return undefined\n const { namespace, target, payload } = frame\n if (room.content || !needsDocument(namespace, target)) {\n handleMessage(room, room.content?.document ?? null, peer, namespace, target, payload)\n return undefined\n }\n return contentOf(room).then(\n ({ document }) => {\n // The peer may have left while the document loaded.\n if (room.peers.get(peer.id) !== peer) return undefined\n handleMessage(room, document, peer, namespace, target, payload)\n return undefined\n },\n (error: unknown) => {\n report('Loading a collaboration room failed:', error)\n peer.socket.close(RELAY_CLOSE.protocol, 'Could not open the collaboration room')\n }\n )\n }\n\n async function admit(\n socket: RelaySocket,\n authorization: RelayAuthorization\n ): Promise<Peer | null> {\n const limit = await options.maximumParticipants?.(authorization.documentId)\n let room: Room\n let epoch: number | null | undefined\n // The room's last peer may have left while it opened, or a restore ended it; a closed room\n // takes no newcomers. The epoch is read once the room is open, so a restore cannot slip between.\n do {\n room = await openRoom(authorization)\n epoch = await options.currentRoomEpoch?.(authorization.documentId)\n } while (rooms.get(room.id) !== room)\n if (epoch != null && authorization.roomEpoch < epoch) {\n socket.close(RELAY_CLOSE.restored, 'The document was restored')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const capacity = Math.min(limit ?? Number.POSITIVE_INFINITY, options.maximumConnectionsPerRoom)\n if (room.peers.size >= capacity) {\n socket.close(RELAY_CLOSE.roomFull, 'Collaboration room is full')\n if (room.peers.size === 0) await leaveRoom(room)\n return null\n }\n const peer: Peer = {\n id: crypto.randomUUID(),\n socket,\n authorization,\n presenceClients: new Set()\n }\n remember(peer)\n send(socket, {\n type: 'welcome',\n peerId: peer.id,\n peers: [RELAY_SERVER_PEER, ...room.peers.keys()]\n })\n sendAll(deliverable(room.peers.values()), { type: 'join', peerId: peer.id })\n room.peers.set(peer.id, peer)\n // Ask for what the newcomer has that the room lacks, such as edits made offline.\n if (authorization.permission === 'edit') {\n const { document } = await contentOf(room)\n send(socket, {\n type: 'message',\n namespace: COLLAB_ACTIONS.syncStep1,\n from: RELAY_SERVER_PEER,\n payload: Y.encodeStateVector(document)\n })\n }\n return peer\n }\n\n async function saveAndClose(room: Room) {\n if ((await persist(room, true)) || shuttingDown) {\n room.content?.document.destroy()\n return\n }\n // The room holds edits the store doesn't have: keep it for whoever joins next, and save\n // again later, closing it once a save lands while nobody is in it.\n rooms.set(room.id, room)\n room.persistTimer = setTimeout(() => {\n void (room.peers.size > 0 ? persist(room) : leaveRoom(room))\n }, persistRetryMs)\n }\n\n async function leaveRoom(room: Room) {\n if (room.peers.size > 0 || rooms.get(room.id) !== room) return\n rooms.delete(room.id)\n const saved = saveAndClose(room)\n closing.set(room.id, saved)\n try {\n await saved\n } finally {\n if (closing.get(room.id) === saved) closing.delete(room.id)\n }\n }\n\n function depart(peer: Peer) {\n const room = rooms.get(peer.authorization.roomId)\n if (!room?.peers.delete(peer.id)) return\n sendAll(deliverable(room.peers.values()), { type: 'leave', peerId: peer.id })\n void leaveRoom(room)\n }\n\n /**\n * A socket's connection: a new one, which presents a ticket before it joins, or one resumed with\n * the peer it already is.\n */\n const connectionRelay: ConnectionRelay = {\n authSecret: options.authSecret,\n documentId: options.documentId,\n maximumMessageBytes: options.maximumMessageBytes,\n authTimeoutMs,\n admit,\n refreshed: remember,\n deliver,\n depart,\n report\n }\n\n return {\n connect(socket: RelaySocket): RelayConnection {\n return openRelayConnection(socket, null, connectionRelay)\n },\n\n /**\n * Takes back a socket whose peer was admitted before the runtime set the relay aside, as the\n * peer it was, without loading the room's document until a message needs it. A peer whose\n * ticket lapsed meanwhile is closed.\n */\n resume(socket: RelaySocket, saved: RelayPeerState): RelayConnection {\n const { authorization } = saved\n const identity = { documentId: authorization.documentId, roomEpoch: authorization.roomEpoch }\n let room = rooms.get(authorization.roomId)\n if (!room) {\n room = newRoom(authorization.roomId, identity)\n rooms.set(room.id, room)\n }\n const peer: Peer = {\n id: saved.peerId,\n socket,\n authorization,\n presenceClients: new Set(saved.presenceClients)\n }\n room.peers.set(peer.id, peer)\n const connection = openRelayConnection(socket, peer, connectionRelay)\n // After the runtime holds the connection, which its socket's close reports to.\n queueMicrotask(() => current(peer))\n return connection\n },\n\n /**\n * Ends a restored document's rooms: everyone in them is told the document was restored, and\n * their edits to the replaced state are dropped rather than saved.\n */\n startOver(documentId: string) {\n // A map's iteration carries on past entries deleted during it.\n for (const room of rooms.values()) {\n if (room.identity.documentId !== documentId) continue\n rooms.delete(room.id)\n if (room.persistTimer) clearTimeout(room.persistTimer)\n for (const peer of room.peers.values()) {\n peer.socket.close(RELAY_CLOSE.restored, 'The document was restored')\n }\n room.peers.clear()\n room.content?.document.destroy()\n }\n },\n\n /** Tells everyone in a document's rooms that its version history changed. */\n announceVersions(documentId: string) {\n const frame: RelayServerFrame = {\n type: 'message',\n namespace: COLLAB_ACTIONS.versions,\n from: RELAY_SERVER_PEER,\n payload: new Uint8Array()\n }\n sendAll(\n deliverable(\n [...rooms.values()]\n .filter((room) => room.identity.documentId === documentId)\n .flatMap((room) => [...room.peers.values()])\n ),\n frame\n )\n },\n\n /** Saves every open room and closes its sockets, as the runtime shuts down. */\n async close() {\n shuttingDown = true\n await Promise.all(\n [...rooms.values()].map(async (room) => {\n for (const peer of room.peers.values()) {\n peer.socket.close(1001, 'Server shutting down')\n }\n room.peers.clear()\n await leaveRoom(room)\n })\n )\n // Rooms whose last peer left just before, or during, shutdown are still saving.\n await Promise.all(closing.values())\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { fromUint8Array } from 'js-base64'\nimport type { Kysely, Transaction } from 'kysely'\n\nexport type CollaborationRoomIdentity = {\n documentId: string\n roomEpoch: number\n}\n\n/** A room as the store keeps it: its last snapshot and the updates logged after it. */\nexport type SavedRoom = {\n snapshot: Uint8Array | null\n /** The updates after the snapshot, in the order they were logged. */\n updates: Uint8Array[]\n /** The sequence of the last update the snapshot or the log holds; 0 for a new room. */\n sequence: number\n}\n\n/**\n * The relay's saved copy of each room's document, by document and collaboration epoch: a snapshot\n * and an append-only log of the updates after it. Each room has one writer, the relay that holds\n * it, so sequences only grow.\n */\nexport type CollaborationStateStore = {\n load(room: CollaborationRoomIdentity): Promise<SavedRoom>\n /**\n * Logs one update; fails when the sequence is already taken. Writes nothing once a restore moved\n * the document past the room's epoch, since that room never opens again.\n */\n append(room: CollaborationRoomIdentity, sequence: number, update: Uint8Array): Promise<void>\n /**\n * Replaces the snapshot with `state`, which holds every update through `sequence`, and drops\n * those updates; running it again leaves the same room. Like `append`, it changes no room of an\n * epoch a restore replaced.\n */\n compact(room: CollaborationRoomIdentity, sequence: number, state: Uint8Array): Promise<void>\n}\n\n/**\n * Whether the document is still at the room's epoch, holding its row so a restore, which advances\n * the epoch and deletes the replaced rooms' rows, waits for this write or this write sees it.\n */\nasync function holdsEpoch(\n transaction: Transaction<CloudDatabase>,\n room: CollaborationRoomIdentity\n): Promise<boolean> {\n const document = await transaction\n .selectFrom('document')\n .select('collaborationEpoch')\n .where('id', '=', room.documentId)\n .forShare()\n .executeTakeFirst()\n return document?.collaborationEpoch === room.roomEpoch\n}\n\n/** A snapshot is a Yjs update, as the store hands it back. */\nconst SNAPSHOT_CONTENT_TYPE = 'application/octet-stream'\n\n/**\n * Where a room's snapshots go. Each compaction writes a new file and points the room at it; the one\n * it replaced is no longer referenced, and the object sweep removes it as it does a deleted\n * revision's file.\n */\nfunction snapshotKey(room: CollaborationRoomIdentity): string {\n return `collaboration/${room.documentId}/${room.roomEpoch}/${crypto.randomUUID()}.yjs`\n}\n\n/**\n * A store keeping each room's snapshot as a file in the object store and the updates logged after\n * it in the database, so the database holds only what changed since the last snapshot.\n */\nexport function createCollaborationStateStore(\n database: Kysely<CloudDatabase>,\n objects: Pick<ObjectStore, 'write' | 'read'>\n): CollaborationStateStore {\n return {\n async load(room) {\n const snapshot = await database\n .selectFrom('documentRoomSnapshot')\n .innerJoin('storageObject', 'storageObject.id', 'documentRoomSnapshot.snapshotObjectId')\n .select(['storageObject.objectKey', 'documentRoomSnapshot.throughSequence'])\n .where('documentRoomSnapshot.documentId', '=', room.documentId)\n .where('documentRoomSnapshot.roomEpoch', '=', room.roomEpoch)\n .executeTakeFirst()\n const state = snapshot ? await objects.read(snapshot.objectKey) : null\n if (snapshot && !state) {\n throw new Error(`The snapshot of room ${room.documentId}:${room.roomEpoch} is missing`)\n }\n const through = snapshot?.throughSequence ?? 0\n const updates = await database\n .selectFrom('documentRoomUpdate')\n .select(['sequence', 'data'])\n .where('documentId', '=', room.documentId)\n .where('roomEpoch', '=', room.roomEpoch)\n .where('sequence', '>', through)\n .orderBy('sequence')\n .execute()\n return {\n snapshot: state,\n updates: updates.map((row) => new Uint8Array(row.data)),\n sequence: updates.at(-1)?.sequence ?? through\n }\n },\n\n async append(room, sequence, update) {\n await database.transaction().execute(async (transaction) => {\n if (!(await holdsEpoch(transaction, room))) return\n await transaction\n .insertInto('documentRoomUpdate')\n .values({\n documentId: room.documentId,\n roomEpoch: room.roomEpoch,\n sequence,\n data: update\n })\n .execute()\n })\n },\n\n async compact(room, sequence, state) {\n // The file is recorded before it is written and referenced only once the room points at it,\n // so a compaction that fails anywhere leaves a file nothing refers to, which the object sweep\n // removes; none is ever deleted while a room might still point at it.\n const snapshotObjectId = crypto.randomUUID()\n const objectKey = snapshotKey(room)\n const checksum = fromUint8Array(sha256(state))\n await database\n .insertInto('storageObject')\n .values({\n id: snapshotObjectId,\n objectKey,\n checksum,\n byteSize: state.byteLength,\n contentType: SNAPSHOT_CONTENT_TYPE\n })\n .execute()\n await objects.write({\n key: objectKey,\n bytes: state,\n contentType: SNAPSHOT_CONTENT_TYPE,\n checksum\n })\n await database.transaction().execute(async (transaction) => {\n if (!(await holdsEpoch(transaction, room))) return\n await transaction\n .insertInto('documentRoomSnapshot')\n .values({\n documentId: room.documentId,\n roomEpoch: room.roomEpoch,\n snapshotObjectId,\n throughSequence: sequence,\n updatedAt: new Date()\n })\n .onConflict((conflict) =>\n conflict.columns(['documentId', 'roomEpoch']).doUpdateSet({\n snapshotObjectId,\n throughSequence: sequence,\n updatedAt: new Date()\n })\n )\n .execute()\n await transaction\n .deleteFrom('documentRoomUpdate')\n .where('documentId', '=', room.documentId)\n .where('roomEpoch', '=', room.roomEpoch)\n .where('sequence', '<=', sequence)\n .execute()\n })\n }\n }\n}\n","import {\n parseDuplicateDocumentVersion,\n parseSaveDocumentVersion,\n parseUpdateDocumentVersion\n} from '#cloud/contract'\nimport { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents/routes'\nimport {\n documentParams,\n documentVersionParams,\n validatedJSON,\n validatedQuery\n} from '#cloud/server/validation'\nimport { Hono, type Context } from 'hono'\nimport * as v from 'valibot'\n\nimport type { DocumentVersionService } from './service'\n\nconst pageSchema = v.object({\n before: v.optional(v.pipe(v.string(), v.uuid())),\n limit: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)))\n})\nconst parsePage = (input: unknown) => v.parse(pageSchema, input)\n\nasync function answer(context: Context, run: () => Promise<Response>): Promise<Response> {\n try {\n return await run()\n } catch (error) {\n const response = documentDomainError(context, error)\n if (response) return response\n throw error\n }\n}\n\n/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */\nexport function createDocumentVersionRoutes(service: DocumentVersionService) {\n return new Hono<DocumentRouteEnvironment>()\n .get('/documents/:documentId/versions', documentParams, validatedQuery(parsePage), (context) =>\n answer(context, async () =>\n context.json(\n await service.list(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('query')\n )\n )\n )\n )\n .post(\n '/documents/:documentId/versions',\n documentParams,\n validatedJSON(parseSaveDocumentVersion),\n (context) =>\n answer(context, async () =>\n context.json(\n {\n version: await service.save(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n .patch(\n '/documents/:documentId/versions/:versionId',\n documentVersionParams,\n validatedJSON(parseUpdateDocumentVersion),\n (context) =>\n answer(context, async () =>\n context.json({\n version: await service.update(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId,\n context.req.valid('json')\n )\n })\n )\n )\n .get('/documents/:documentId/versions/:versionId', documentVersionParams, (context) =>\n answer(context, async () =>\n context.json(\n await service.download(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId\n )\n )\n )\n )\n .post('/documents/:documentId/versions/:versionId/restore', documentVersionParams, (context) =>\n answer(context, async () =>\n context.json(\n await service.restore(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId\n )\n )\n )\n )\n .post(\n '/documents/:documentId/versions/:versionId/duplicate',\n documentVersionParams,\n validatedJSON(parseDuplicateDocumentVersion),\n (context) =>\n answer(context, async () =>\n context.json(\n {\n document: await service.duplicate(\n context.get('actor').userId,\n context.req.valid('param').documentId,\n context.req.valid('param').versionId,\n context.req.valid('json')\n )\n },\n 201\n )\n )\n )\n}\n","import type {\n DocumentVersionDownload,\n DocumentSummary,\n DocumentVersion,\n DocumentVersions,\n DuplicateDocumentVersionInput,\n SaveDocumentVersionInput,\n UpdateDocumentVersionInput\n} from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'\nimport { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'\nimport { copyRevisionImages, revisionImageDownloads } from '#cloud/server/documents/images'\nimport { findDocument, insertDocument, workspaceRole } from '#cloud/server/documents/repository'\nimport { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport type { CloudPolicyContext } from '#cloud/server/policy/keys'\nimport type { CloudPolicy } from '#cloud/server/policy/policy'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { announceVersions, keepRevision } from './checkpoint'\nimport { historyStart } from './history'\n\nconst DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000\nconst DEFAULT_PAGE_SIZE = 50\nconst MAXIMUM_PAGE_SIZE = 100\nconst WRITABLE_ROLES = new Set(['admin', 'editor'])\n\ntype VersionRow = {\n id: string\n revisionId: string\n kind: 'checkpoint' | 'named'\n name: string | null\n description: string | null\n createdAt: Date\n createdBy: string\n createdByName: string | null\n restoredFromVersionId: string | null\n}\n\nfunction versionOf(row: VersionRow, currentRevisionId: string | null): DocumentVersion {\n return {\n id: row.id,\n revisionId: row.revisionId,\n kind: row.kind,\n name: row.name,\n description: row.description,\n createdAt: row.createdAt.toISOString(),\n createdBy: { id: row.createdBy, name: row.createdByName },\n restoredFromVersionId: row.restoredFromVersionId,\n current: row.revisionId === currentRevisionId\n }\n}\n\n/**\n * A document's version history: its checkpoints and named versions, newest first, and what can be\n * done with one. Anyone who can open the document sees its history; editors name and restore.\n */\nexport function createDocumentVersionService(\n database: Kysely<CloudDatabase>,\n objects: ObjectStore,\n options: {\n policy?: CloudPolicy\n deploymentMode?: CloudPolicyContext['deploymentMode']\n /** Called once a restore lands, so the document's live room starts over. */\n onRestored?: (documentId: string) => void\n /** Called once the history changes: a version named, renamed, or turned back into an autosave. */\n onVersionsChanged?: (documentId: string) => void\n } = {}\n) {\n const deploymentMode = options.deploymentMode ?? 'self-hosted'\n function versions() {\n return database\n .selectFrom('documentVersion')\n .leftJoin('user', (join) =>\n join.on((expression) =>\n expression(\n expression.cast(expression.ref('user.id'), 'text'),\n '=',\n expression.ref('documentVersion.createdBy')\n )\n )\n )\n .select([\n 'documentVersion.id',\n 'documentVersion.revisionId',\n 'documentVersion.kind',\n 'documentVersion.name',\n 'documentVersion.description',\n 'documentVersion.createdAt',\n 'documentVersion.createdBy',\n 'user.name as createdByName',\n 'documentVersion.restoredFromVersionId'\n ])\n }\n\n /** The document the person may see the history of, and where that history starts. */\n async function openHistory(userId: string, documentId: string, edit: boolean) {\n const access = await resolveDocumentAccess(database, userId, documentId)\n if (!access) throw new DocumentNotFoundError()\n if (edit && !canEditDocument(access)) throw new DocumentForbiddenError()\n const document = await getDocumentSummaryRow(database, documentId)\n if (!document) throw new DocumentNotFoundError()\n return {\n document,\n start: await historyStart(options.policy, deploymentMode, document.workspaceId, new Date())\n }\n }\n\n async function findVersion(documentId: string, versionId: string, start: Date | null) {\n let query = versions()\n .where('documentVersion.documentId', '=', documentId)\n .where('documentVersion.id', '=', versionId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n const row = await query.executeTakeFirst()\n if (!row) throw new DocumentNotFoundError()\n return row\n }\n\n /** The stored file of a revision; read under the document's lock before reusing it. */\n async function storedRevision(\n source: Kysely<CloudDatabase> | Transaction<CloudDatabase>,\n revisionId: string\n ) {\n const stored = await source\n .selectFrom('documentRevision')\n .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')\n .select([\n 'documentRevision.storageObjectId',\n 'storageObject.objectKey',\n 'storageObject.byteSize',\n 'storageObject.checksum',\n 'storageObject.contentType'\n ])\n .where('documentRevision.id', '=', revisionId)\n .executeTakeFirst()\n if (!stored) throw new DocumentNotFoundError()\n return stored\n }\n\n return {\n async list(\n userId: string,\n documentId: string,\n page: { before?: string; limit?: number } = {}\n ): Promise<DocumentVersions> {\n const { document, start } = await openHistory(userId, documentId, false)\n const limit = Math.min(Math.max(page.limit ?? DEFAULT_PAGE_SIZE, 1), MAXIMUM_PAGE_SIZE)\n let query = versions().where('documentVersion.documentId', '=', documentId)\n if (start) query = query.where('documentVersion.createdAt', '>=', start)\n if (page.before) {\n const cursor = await findVersion(documentId, page.before, start)\n query = query.where((expression) =>\n expression.or([\n expression('documentVersion.createdAt', '<', cursor.createdAt),\n expression.and([\n expression('documentVersion.createdAt', '=', cursor.createdAt),\n expression('documentVersion.id', '<', cursor.id)\n ])\n ])\n )\n }\n const rows = await query\n .orderBy('documentVersion.createdAt', 'desc')\n .orderBy('documentVersion.id', 'desc')\n .limit(limit + 1)\n .execute()\n const shown = rows.slice(0, limit)\n return {\n versions: shown.map((row) => versionOf(row, document.currentRevisionId)),\n nextCursor: rows.length > limit ? (shown.at(-1)?.id ?? null) : null\n }\n },\n\n /** Names the document as it is now, as Save to version history does. */\n async save(\n userId: string,\n documentId: string,\n input: SaveDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document } = await openHistory(userId, documentId, true)\n const revisionId = document.currentRevisionId\n if (!revisionId) throw new DocumentNotFoundError()\n const description = input.description || null\n await database\n .insertInto('documentVersion')\n .values({\n id: crypto.randomUUID(),\n documentId,\n revisionId,\n kind: 'named',\n name: input.name,\n description,\n createdBy: userId,\n restoredFromVersionId: null\n })\n .onConflict((conflict) =>\n conflict\n .column('revisionId')\n .doUpdateSet({ kind: 'named', name: input.name, description })\n )\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n const row = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return versionOf(row, revisionId)\n },\n\n /** Names a version, renames it, or with a null name deletes its info so it is a checkpoint. */\n async update(\n userId: string,\n documentId: string,\n versionId: string,\n input: UpdateDocumentVersionInput\n ): Promise<DocumentVersion> {\n const { document, start } = await openHistory(userId, documentId, true)\n await findVersion(documentId, versionId, start)\n await database\n .updateTable('documentVersion')\n .set(\n input.name\n ? { kind: 'named', name: input.name, description: input.description || null }\n : { kind: 'checkpoint', name: null, description: null }\n )\n .where('id', '=', versionId)\n .execute()\n announceVersions(options.onVersionsChanged, documentId)\n return versionOf(await findVersion(documentId, versionId, start), document.currentRevisionId)\n },\n\n async download(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<DocumentVersionDownload> {\n const { document, start } = await openHistory(userId, documentId, false)\n const version = await findVersion(documentId, versionId, start)\n const stored = await storedRevision(database, version.revisionId)\n const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)\n return {\n document: {\n document: documentSummary(document),\n revisionId: version.revisionId,\n byteSize: Number(stored.byteSize),\n checksum: stored.checksum,\n contentType: stored.contentType,\n download: await objects.createDownload({ key: stored.objectKey, expiresAt }),\n images: await revisionImageDownloads(database, objects, version.revisionId, expiresAt)\n },\n version: versionOf(version, document.currentRevisionId)\n }\n },\n\n /**\n * Makes a version the document's current state without losing anything: the state it replaces\n * is kept as a checkpoint, the restored state becomes a new revision of the same stored file,\n * and the document's live room starts over so everyone has the restored version.\n */\n async restore(\n userId: string,\n documentId: string,\n versionId: string\n ): Promise<{ document: DocumentSummary; version: DocumentVersion }> {\n const { start } = await openHistory(userId, documentId, true)\n const version = await findVersion(documentId, versionId, start)\n const revisionId = crypto.randomUUID()\n const now = new Date()\n await database.transaction().execute(async (transaction) => {\n const locked = await transaction\n .selectFrom('document')\n .select(['currentRevisionId', 'deletedAt'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!locked || locked.deletedAt) throw new DocumentNotFoundError()\n // Compaction locks the document too, so the version's file cannot go while it is reused.\n const stored = await storedRevision(transaction, version.revisionId)\n if (locked.currentRevisionId) {\n const current = await transaction\n .selectFrom('documentRevision')\n .select('createdBy')\n .where('id', '=', locked.currentRevisionId)\n .executeTakeFirstOrThrow()\n await keepRevision(transaction, {\n documentId,\n revisionId: locked.currentRevisionId,\n createdBy: current.createdBy,\n createdAt: now\n })\n }\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId,\n parentRevisionId: locked.currentRevisionId,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({\n currentRevisionId: revisionId,\n version: (expression) => expression('version', '+', 1),\n collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1)\n })\n .where('id', '=', documentId)\n .execute()\n // The rooms of the replaced state never open again, so what the relay saved of them goes.\n await transaction\n .deleteFrom('documentRoomUpdate')\n .where('documentId', '=', documentId)\n .execute()\n await transaction\n .deleteFrom('documentRoomSnapshot')\n .where('documentId', '=', documentId)\n .execute()\n // A moment after the state it replaces, so the history lists it first.\n await keepRevision(transaction, {\n documentId,\n revisionId,\n createdBy: userId,\n createdAt: new Date(now.getTime() + 1),\n restoredFromVersionId: versionId\n })\n })\n // The restore stands whatever the hook does; a stale ticket is still turned away by its epoch.\n try {\n options.onRestored?.(documentId)\n } catch (error) {\n console.error('[Cloud] Ending the rooms of a restored document failed:', error)\n }\n const document = await findDocument(database, userId, documentId)\n if (!document) throw new DocumentNotFoundError()\n const restored = await versions()\n .where('documentVersion.revisionId', '=', revisionId)\n .executeTakeFirstOrThrow()\n return { document, version: versionOf(restored, revisionId) }\n },\n\n /** Makes a new document in the same workspace from a version, sharing its stored file. */\n async duplicate(\n userId: string,\n documentId: string,\n versionId: string,\n input: DuplicateDocumentVersionInput\n ): Promise<DocumentSummary> {\n const { document, start } = await openHistory(userId, documentId, false)\n const role = await workspaceRole(database, userId, document.workspaceId)\n if (!role) throw new DocumentNotFoundError()\n if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()\n const version = await findVersion(documentId, versionId, start)\n const copyId = crypto.randomUUID()\n const revisionId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n // Deleted-document cleanup removes files its document alone uses; holding the source\n // until the copy refers to the file means cleanup either finishes first or sees the copy.\n const source = await transaction\n .selectFrom('document')\n .select(['deletedAt', 'cleanupClaimId'])\n .where('id', '=', documentId)\n .forUpdate()\n .executeTakeFirst()\n if (!source || source.deletedAt || source.cleanupClaimId) throw new DocumentNotFoundError()\n const stored = await storedRevision(transaction, version.revisionId)\n await insertDocument(transaction, {\n id: copyId,\n workspaceId: document.workspaceId,\n name: input.name,\n kind: document.kind,\n createdBy: userId\n })\n await transaction\n .insertInto('documentRevision')\n .values({\n id: revisionId,\n documentId: copyId,\n parentRevisionId: null,\n storageObjectId: stored.storageObjectId,\n createdBy: userId\n })\n .execute()\n await copyRevisionImages(transaction, version.revisionId, revisionId)\n await transaction\n .updateTable('document')\n .set({ currentRevisionId: revisionId, version: 1 })\n .where('id', '=', copyId)\n .execute()\n await keepRevision(transaction, {\n documentId: copyId,\n revisionId,\n createdBy: userId,\n createdAt: new Date()\n })\n })\n const copy = await findDocument(database, userId, copyId)\n if (!copy) throw new DocumentNotFoundError()\n return copy\n }\n }\n}\n\nexport type DocumentVersionService = ReturnType<typeof createDocumentVersionService>\n","import type { CreateWorkspaceInput, WorkspaceSummary } from '#cloud/contract'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n findWorkspace,\n insertWorkspace,\n insertWorkspaceMember,\n listWorkspaces\n} from '#cloud/server/workspaces/repository'\nimport type { Kysely } from 'kysely'\n\nexport class WorkspaceSlugConflictError extends Error {\n constructor(readonly slug: string) {\n super(`Workspace slug is already in use: ${slug}`)\n this.name = 'WorkspaceSlugConflictError'\n }\n}\n\nfunction fallbackSlug(name: string): string {\n const normalized = name\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '')\n .slice(0, 48)\n return normalized.length >= 3 ? normalized : 'workspace'\n}\n\nfunction generatedSlug(name: string): string {\n return `${fallbackSlug(name)}-${crypto.randomUUID().slice(0, 8)}`\n}\n\nfunction personalWorkspaceName(name: string): string {\n const first = name.trim().split(/\\s+/)[0]\n return first ? `${first}’s workspace` : 'Personal workspace'\n}\n\nexport function createWorkspaceService(database: Kysely<CloudDatabase>) {\n return {\n list(userId: string): Promise<WorkspaceSummary[]> {\n return listWorkspaces(database, userId)\n },\n\n get(userId: string, workspaceId: string): Promise<WorkspaceSummary | undefined> {\n return findWorkspace(database, userId, workspaceId)\n },\n\n async create(userId: string, input: CreateWorkspaceInput): Promise<WorkspaceSummary> {\n const workspaceId = crypto.randomUUID()\n const slug = input.slug ?? generatedSlug(input.name)\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, userId, {\n ...input,\n id: workspaceId,\n slug\n })\n if (!inserted) throw new WorkspaceSlugConflictError(slug)\n await insertWorkspaceMember(transaction, workspaceId, userId, 'admin')\n })\n const workspace = await findWorkspace(database, userId, workspaceId)\n if (!workspace) throw new Error('Created workspace could not be read')\n return workspace\n },\n\n /**\n * Gives an active account with no workspace one of its own, so it has somewhere to save. The\n * slug is fixed per person, so concurrent calls make one workspace and later calls none.\n */\n async ensurePersonal(user: { userId: string; name: string }): Promise<void> {\n if ((await listWorkspaces(database, user.userId)).length > 0) return\n const workspaceId = crypto.randomUUID()\n await database.transaction().execute(async (transaction) => {\n const inserted = await insertWorkspace(transaction, user.userId, {\n id: workspaceId,\n name: personalWorkspaceName(user.name),\n slug: `personal-${user.userId}`\n })\n if (inserted) await insertWorkspaceMember(transaction, workspaceId, user.userId, 'admin')\n })\n }\n }\n}\n\nexport type WorkspaceService = ReturnType<typeof createWorkspaceService>\n","import {\n parseCreateWorkspace,\n parseCreateWorkspaceInvitation,\n parseUpdateWorkspace,\n parseUpdateWorkspaceMember\n} from '#cloud/contract'\nimport type { CloudActor } from '#cloud/server/auth'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport {\n CLOUD_RATE_LIMITS,\n createRouteRateLimiter,\n routeParamResource,\n createResourceRateLimiter\n} from '#cloud/server/rate-limit'\nimport {\n validatedJSON,\n workspaceInvitationParams,\n workspaceMemberParams,\n workspaceParams\n} from '#cloud/server/validation'\nimport {\n WorkspaceAlreadyMemberError,\n WorkspaceForbiddenError,\n WorkspaceLastAdminError,\n WorkspaceNotEmptyError,\n WorkspaceNotFoundError,\n type WorkspaceMemberService\n} from '#cloud/server/workspaces/members'\nimport type { WorkspaceService } from '#cloud/server/workspaces/service'\nimport { WorkspaceSlugConflictError } from '#cloud/server/workspaces/service'\nimport { Hono, type Context } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type WorkspaceRouteEnvironment = {\n Variables: {\n actor: CloudActor\n }\n}\n\n/** Runs a membership action, answering its domain errors with their HTTP codes. */\nasync function memberRoute<T>(context: Context, action: () => Promise<T>): Promise<T | Response> {\n try {\n return await action()\n } catch (error) {\n if (error instanceof WorkspaceNotFoundError) {\n return context.json({ error: { code: 'not_found' as const } }, 404)\n }\n if (error instanceof WorkspaceForbiddenError) {\n return context.json({ error: { code: 'forbidden' as const } }, 403)\n }\n if (error instanceof WorkspaceLastAdminError) {\n return context.json({ error: { code: 'last_admin' as const } }, 409)\n }\n if (error instanceof WorkspaceNotEmptyError) {\n const code = error.reason === 'documents' ? 'not_empty' : 'cleanup_pending'\n return context.json({ error: { code } }, 409)\n }\n if (error instanceof WorkspaceAlreadyMemberError) {\n return context.json({ error: { code: 'already_member' as const } }, 409)\n }\n throw error\n }\n}\n\nexport function createWorkspaceRoutes(\n service: WorkspaceService,\n members: WorkspaceMemberService,\n rateLimit?: { database: Kysely<CloudDatabase>; secret: string }\n) {\n const router = new Hono<WorkspaceRouteEnvironment>()\n if (rateLimit) {\n router.use(\n '/',\n createRouteRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.workspaceCreation,\n (context) => context.req.method !== 'POST'\n )\n )\n // Resending mails the invitation again, so it counts against the same budget as sending.\n router.use(\n '/:workspaceId/invitations/:invitationId/resend',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('workspaceId'),\n () => false\n )\n )\n router.use(\n '/:workspaceId/invitations',\n createResourceRateLimiter(\n rateLimit.database,\n rateLimit.secret,\n CLOUD_RATE_LIMITS.invitationMutation,\n routeParamResource('workspaceId'),\n (context) => context.req.method !== 'POST'\n )\n )\n }\n return router\n .get('/', async (context) => {\n const workspaces = await service.list(context.get('actor').userId)\n return context.json({ workspaces })\n })\n .post('/', validatedJSON(parseCreateWorkspace), async (context) => {\n try {\n const workspace = await service.create(\n context.get('actor').userId,\n context.req.valid('json')\n )\n return context.json({ workspace }, 201)\n } catch (error) {\n if (error instanceof WorkspaceSlugConflictError) {\n return context.json({ error: { code: 'slug_conflict' as const } }, 409)\n }\n throw error\n }\n })\n .get('/:workspaceId', workspaceParams, async (context) => {\n const workspace = await service.get(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n if (!workspace) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ workspace })\n })\n .patch('/:workspaceId', workspaceParams, validatedJSON(parseUpdateWorkspace), (context) =>\n memberRoute(context, async () =>\n context.json({\n workspace: await members.rename(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json').name\n )\n })\n )\n )\n .delete('/:workspaceId', workspaceParams, (context) =>\n memberRoute(context, async () => {\n await members.delete(context.get('actor').userId, context.req.valid('param').workspaceId)\n return context.body(null, 204)\n })\n )\n .get('/:workspaceId/members', workspaceParams, (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.list(context.get('actor').userId, context.req.valid('param').workspaceId)\n )\n )\n )\n .post(\n '/:workspaceId/invitations',\n workspaceParams,\n validatedJSON(parseCreateWorkspaceInvitation),\n (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.invite(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('json')\n ),\n 201\n )\n )\n )\n .post('/:workspaceId/invitations/:invitationId/resend', workspaceInvitationParams, (context) =>\n memberRoute(context, async () =>\n context.json(\n await members.resendInvitation(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').invitationId\n )\n )\n )\n )\n .delete('/:workspaceId/invitations/:invitationId', workspaceInvitationParams, (context) =>\n memberRoute(context, async () => {\n await members.revokeInvitation(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').invitationId\n )\n return context.body(null, 204)\n })\n )\n .patch(\n '/:workspaceId/members/:userId',\n workspaceMemberParams,\n validatedJSON(parseUpdateWorkspaceMember),\n (context) =>\n memberRoute(context, async () => {\n await members.updateRole(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').userId,\n context.req.valid('json').role\n )\n return context.body(null, 204)\n })\n )\n .delete('/:workspaceId/members/:userId', workspaceMemberParams, (context) =>\n memberRoute(context, async () => {\n await members.remove(\n context.get('actor').userId,\n context.req.valid('param').workspaceId,\n context.req.valid('param').userId\n )\n return context.body(null, 204)\n })\n )\n}\n","import { createAIRoutes, type AITokenService } from '#cloud/server/ai'\nimport type { CloudAPIEnvironment } from '#cloud/server/api/types'\nimport type { CloudSessionResolver } from '#cloud/server/auth'\nimport type { CollaborationTicketService } from '#cloud/server/collaboration'\nimport {\n createCollaborationRoutes,\n createPublicCollaborationRoutes\n} from '#cloud/server/collaboration'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentService } from '#cloud/server/documents'\nimport { createDocumentRoutes } from '#cloud/server/documents'\nimport {\n createDocumentVersionRoutes,\n type DocumentVersionService\n} from '#cloud/server/documents/versions'\nimport type { EntitlementService } from '#cloud/server/policy'\nimport type { DocumentSharingService } from '#cloud/server/sharing'\nimport {\n createDocumentSharingRoutes,\n createPublicDocumentRoutes,\n createPublicSharingRoutes\n} from '#cloud/server/sharing'\nimport { workspaceParams } from '#cloud/server/validation'\nimport type { WorkspaceMemberService, WorkspaceService } from '#cloud/server/workspaces'\nimport { createWorkspaceRoutes } from '#cloud/server/workspaces'\nimport { Hono } from 'hono'\nimport type { Kysely } from 'kysely'\n\nexport type CloudAPIServices = {\n database?: Kysely<CloudDatabase>\n rateLimitSecret?: string\n collaboration: CollaborationTicketService\n documents: DocumentService\n versions: DocumentVersionService\n sharing: DocumentSharingService\n resolveSession?: CloudSessionResolver\n entitlements?: EntitlementService\n /** Signs AI service tokens; without it the deployment has no AI service. */\n aiTokens?: AITokenService\n workspaces: WorkspaceService\n workspaceMembers: WorkspaceMemberService\n}\n\nexport function createPublicCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/', createPublicSharingRoutes(services.sharing, services.resolveSession))\n .route(\n '/',\n createPublicDocumentRoutes(services.sharing, services.documents, services.resolveSession)\n )\n .route('/', createPublicCollaborationRoutes(services.collaboration, services.resolveSession))\n}\n\nexport function createCloudAPIRouter(services: CloudAPIServices) {\n return new Hono<CloudAPIEnvironment>()\n .route('/public', createPublicCloudAPIRouter(services))\n .get('/workspaces/:workspaceId/entitlements', workspaceParams, async (context) => {\n if (!services.entitlements)\n return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({\n entitlements: await services.entitlements.workspace(\n context.get('actor').userId,\n context.req.valid('param').workspaceId\n )\n })\n })\n .get('/session', (context) => context.json({ user: context.get('actor') }))\n .route(\n '/',\n createAIRoutes(\n services.aiTokens,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createCollaborationRoutes(\n services.collaboration,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/',\n createDocumentRoutes(\n services.documents,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route('/', createDocumentVersionRoutes(services.versions))\n .route(\n '/',\n createDocumentSharingRoutes(\n services.sharing,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n .route(\n '/workspaces',\n createWorkspaceRoutes(\n services.workspaces,\n services.workspaceMembers,\n services.database && services.rateLimitSecret\n ? { database: services.database, secret: services.rateLimitSecret }\n : undefined\n )\n )\n}\n\nexport type CloudAPI = ReturnType<typeof createCloudAPIRouter>\nexport type PublicCloudAPI = ReturnType<typeof createPublicCloudAPIRouter>\n","import type { AccountSecurityErrorCode } from '#cloud/contract'\nimport type { CloudIdentityResolver, CloudSessionResolver } from '#cloud/server/auth'\nimport { APIError } from 'better-auth'\nimport type { Context } from 'hono'\n\nconst ACCOUNT_SECURITY_ERROR_CODES: Record<string, AccountSecurityErrorCode> = {\n INVALID_PASSWORD: 'current_password_invalid',\n PASSWORD_TOO_SHORT: 'password_too_short',\n PASSWORD_TOO_LONG: 'password_too_long',\n FAILED_TO_UNLINK_LAST_ACCOUNT: 'last_authentication_method',\n SESSION_NOT_FRESH: 'session_not_fresh',\n CHANGE_EMAIL_DISABLED: 'email_change_unavailable',\n CURRENT_SESSION: 'current_session',\n EMAIL_UNCHANGED: 'email_unchanged'\n}\n\nasync function accountAction<Value>(operation: () => Promise<Value>, context: Context) {\n try {\n return await operation()\n } catch (error) {\n if (!(error instanceof APIError)) throw error\n return context.json(\n {\n error: {\n code:\n ACCOUNT_SECURITY_ERROR_CODES[error.body?.code ?? ''] ?? 'authentication_method_failed'\n }\n },\n error.statusCode as 400 | 401 | 403 | 404 | 409 | 422 | 429 | 500\n )\n }\n}\n\nfunction completedMFAResponse(result: Response | undefined, context: Context): Response {\n if (!(result instanceof Response)) return context.json({ ok: true as const })\n if (!result.ok) return result\n const headers = new Headers(result.headers)\n headers.set('Content-Type', 'application/json')\n return new Response(JSON.stringify({ ok: true }), { status: 200, headers })\n}\n\nexport function createAccountActions(resolveSession: CloudSessionResolver) {\n return {\n accountAction,\n activeAccountAction: async <Value>(\n context: Context,\n operation: () => Promise<Value>\n ): Promise<Value | Response> => {\n if (!(await resolveSession(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n return accountAction(operation, context)\n },\n verifiedMFAAction: async (\n context: Context,\n identityResolver: CloudIdentityResolver,\n verify: () => Promise<Response | undefined>\n ): Promise<Response> => {\n if (!(await identityResolver(context.req.raw))) {\n return context.json({ error: { code: 'unauthorized' as const } }, 401)\n }\n const result = await accountAction(verify, context)\n return completedMFAResponse(result instanceof Response ? result : undefined, context)\n }\n }\n}\n","import type { EnrollmentService } from '#cloud/admin'\nimport {\n parseCloudPasswordChange,\n parseCloudMFAEnable,\n parseCloudMFAVerify,\n parseCloudPasskeyDelete,\n parseCloudSocialLink,\n parseCloudUnlinkAuthenticationMethod,\n parseCloudEmailChange,\n parseCloudProfileUpdate,\n parseCloudPictureUpload,\n CLOUD_PICTURE_MAX_BYTES,\n parseCloudSessionRevoke\n} from '#cloud/contract'\nimport type { CloudAPIEnvironment } from '#cloud/server/api'\nimport {\n createAccountAuthenticationService,\n type CloudAuthAdapter,\n type CloudIdentityResolver,\n type CloudSessionResolver\n} from '#cloud/server/auth'\nimport type { CloudServerConfig } from '#cloud/server/config'\nimport { PictureInvalidError, type UserPictureService } from '#cloud/server/pictures'\nimport { validatedJSON } from '#cloud/server/validation'\nimport type { WorkspaceService } from '#cloud/server/workspaces'\nimport { Hono, type MiddlewareHandler } from 'hono'\nimport { bodyLimit } from 'hono/body-limit'\nimport { toUint8Array } from 'js-base64'\n\nimport { createAccountActions } from './actions'\n\n/** Room for a Base64 picture and the JSON around it. */\nconst PICTURE_BODY_BYTES = Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4 + 1024\n\nexport type AccountRouteDependencies = {\n auth: CloudAuthAdapter\n config: CloudServerConfig\n pictures: UserPictureService\n enrollment: EnrollmentService\n workspaces: WorkspaceService\n resolveIdentity: CloudIdentityResolver\n resolveSession: CloudSessionResolver\n requireActiveSession: MiddlewareHandler<CloudAPIEnvironment>\n authenticatedMutationLimiter: MiddlewareHandler<CloudAPIEnvironment>\n}\n\nexport function createAccountRoutes(services: AccountRouteDependencies) {\n const {\n enrollment,\n workspaces,\n resolveIdentity,\n resolveSession,\n requireActiveSession,\n authenticatedMutationLimiter\n } = services\n const accountAuthentication = createAccountAuthenticationService(services.auth, services.config)\n const { accountAction, activeAccountAction, verifiedMFAAction } =\n createAccountActions(resolveSession)\n return new Hono<CloudAPIEnvironment>()\n .get('/api/account/status', async (context) => {\n const identity = await resolveIdentity(context.req.raw)\n if (!identity) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n let enrollmentStatus = await enrollment.statusForEmail(identity.email)\n if (services.config.enrollmentMode === 'approval' && !enrollmentStatus) {\n await enrollment.request({ email: identity.email, name: identity.name })\n enrollmentStatus = 'pending'\n }\n const state =\n services.config.enrollmentMode !== 'approval' || enrollmentStatus === 'approved'\n ? ('active' as const)\n : (enrollmentStatus ?? 'pending')\n if (state === 'active') await workspaces.ensurePersonal(identity)\n return context.json({ user: identity, state })\n })\n .get('/api/account/mfa', async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const mfa = await services.auth.mfaStatus(context.req.raw.headers)\n return mfa\n ? context.json({ mfa })\n : context.json({ error: { code: 'unauthorized' as const } }, 401)\n })\n .post('/api/account/mfa/totp/enable', validatedJSON(parseCloudMFAEnable), async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.enableTOTP(context.req.raw.headers, context.req.valid('json').password)\n )\n return result instanceof Response ? result : context.json(result)\n })\n .post('/api/account/mfa/totp/verify', validatedJSON(parseCloudMFAVerify), (context) =>\n verifiedMFAAction(context, resolveSession, () =>\n services.auth.verifyTOTP(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post('/api/account/mfa/recovery/verify', validatedJSON(parseCloudMFAVerify), (context) =>\n verifiedMFAAction(context, resolveIdentity, () =>\n services.auth.verifyRecoveryCode(context.req.raw.headers, context.req.valid('json').code)\n )\n )\n .post(\n '/api/account/mfa/recovery/regenerate',\n validatedJSON(parseCloudMFAEnable),\n async (context) => {\n const result = await activeAccountAction(context, () =>\n services.auth.generateRecoveryCodes(\n context.req.raw.headers,\n context.req.valid('json').password\n )\n )\n return result instanceof Response ? result : context.json({ backupCodes: result })\n }\n )\n .post('/api/account/mfa/totp/disable', validatedJSON(parseCloudMFAEnable), async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n if (passkeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () =>\n services.auth.disableTOTP(context.req.raw.headers, context.req.valid('json').password),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/mfa/passkeys', async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ passkeys: await services.auth.listPasskeys(context.req.raw.headers) })\n })\n .post(\n '/api/account/mfa/passkeys/delete',\n validatedJSON(parseCloudPasskeyDelete),\n async (context) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n const { id } = context.req.valid('json')\n if (actor.deploymentRole === 'admin' && services.config.deploymentAdminMFARequired) {\n // An administrator keeps at least one second factor: TOTP or another passkey.\n const status = await services.auth.mfaStatus(context.req.raw.headers)\n const passkeys = await services.auth.listPasskeys(context.req.raw.headers)\n const otherPasskeys = passkeys.filter((passkey) => passkey.id !== id)\n if (!status?.totpEnabled && otherPasskeys.length === 0) {\n return context.json({ error: { code: 'mfa_required' as const } }, 403)\n }\n }\n const result = await accountAction(\n () => services.auth.deletePasskey(context.req.raw.headers, id),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/authentication/*', requireActiveSession)\n .use('/api/account/authentication/*', authenticatedMutationLimiter)\n .post(\n '/api/account/authentication/change-password',\n validatedJSON(parseCloudPasswordChange),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.changePassword(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post(\n '/api/account/authentication/link-social',\n validatedJSON(parseCloudSocialLink),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.startSocialLink(\n context.req.raw.headers,\n context.req.valid('json')\n ),\n context\n )\n return result instanceof Response ? result : context.json({ url: result })\n }\n )\n .post(\n '/api/account/authentication/unlink',\n validatedJSON(parseCloudUnlinkAuthenticationMethod),\n async (context) => {\n const result = await accountAction(\n () =>\n accountAuthentication.unlink(\n context.req.raw.headers,\n context.req.valid('json').methodId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .use('/api/account/profile', requireActiveSession)\n .use('/api/account/profile/*', requireActiveSession)\n .use('/api/account/sessions', requireActiveSession)\n .use('/api/account/sessions/*', requireActiveSession)\n .use('/api/account/sign-ins', requireActiveSession)\n .use('/api/account/profile', authenticatedMutationLimiter)\n .use('/api/account/profile/*', authenticatedMutationLimiter)\n .use('/api/account/sessions/*', authenticatedMutationLimiter)\n .get('/api/account/profile', async (context) => {\n const profile = await services.auth.profile(context.req.raw.headers)\n if (!profile) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({\n profile: {\n ...profile,\n createdAt: profile.createdAt.toISOString(),\n emailChangeAvailable: services.auth.emailChangeAvailable\n }\n })\n })\n .post('/api/account/profile', validatedJSON(parseCloudProfileUpdate), async (context) => {\n const result = await accountAction(\n () => services.auth.updateProfile(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .put(\n '/api/account/profile/picture',\n bodyLimit({\n maxSize: PICTURE_BODY_BYTES,\n onError: (context) => context.json({ error: { code: 'picture_invalid' as const } }, 413)\n }),\n validatedJSON(parseCloudPictureUpload),\n async (context) => {\n const bytes = toUint8Array(context.req.valid('json').data)\n try {\n const image = await services.pictures.upload(context.get('actor').userId, bytes)\n return context.json({ image })\n } catch (error) {\n if (!(error instanceof PictureInvalidError)) throw error\n return context.json({ error: { code: 'picture_invalid' as const } }, 400)\n }\n }\n )\n .delete('/api/account/profile/picture', async (context) => {\n await services.pictures.remove(context.get('actor').userId)\n return context.json({ ok: true as const })\n })\n .post('/api/account/profile/email', validatedJSON(parseCloudEmailChange), async (context) => {\n const result = await accountAction(\n () => accountAuthentication.changeEmail(context.req.raw.headers, context.req.valid('json')),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/sessions', async (context) => {\n const sessions = await services.auth.sessions(context.req.raw.headers)\n if (!sessions) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ sessions })\n })\n .post(\n '/api/account/sessions/revoke',\n validatedJSON(parseCloudSessionRevoke),\n async (context) => {\n const result = await accountAction(\n () =>\n services.auth.revokeSession(\n context.req.raw.headers,\n context.req.valid('json').sessionId\n ),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n }\n )\n .post('/api/account/sessions/revoke-others', async (context) => {\n const result = await accountAction(\n () => services.auth.revokeOtherSessions(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json({ ok: true as const })\n })\n .get('/api/account/sign-ins', async (context) => {\n const signIns = await services.auth.signIns(context.req.raw.headers)\n if (!signIns) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n return context.json({ signIns })\n })\n .get('/api/account/authentication', async (context) => {\n const result = await accountAction(\n () => accountAuthentication.methods(context.req.raw.headers),\n context\n )\n return result instanceof Response ? result : context.json(result)\n })\n}\n\n/** The account routes' types, for the portal's typed client. */\nexport type CloudAccountRoutes = ReturnType<typeof createAccountRoutes>\n","import type { Context, ErrorHandler } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport { routePath } from 'hono/route'\n\n/** Where the server caught an error. */\nexport const CLOUD_ERROR_SOURCES = [\n 'request',\n 'background',\n 'cleanup',\n 'email',\n 'relay',\n 'scheduled',\n 'setup'\n] as const\nexport type CloudErrorSource = (typeof CLOUD_ERROR_SOURCES)[number]\n\n/** What the server knows about a caught error; never who made the request or what it carried. */\nexport type CloudErrorContext = {\n source: CloudErrorSource\n /** For a request: its method and the route pattern it matched, not the path with its IDs. */\n method?: string\n route?: string\n}\n\n/**\n * Sends a caught error to the deployment's error tracking. Runtimes create one only when the\n * deployment configures error tracking; its promise never rejects.\n */\nexport type CloudErrorReporter = (error: unknown, context: CloudErrorContext) => Promise<void>\n\n/** Logs a caught error and reports it, when the deployment reports errors. */\nexport function reportCloudError(\n reporter: CloudErrorReporter | undefined,\n message: string,\n error: unknown,\n context: CloudErrorContext\n): Promise<void> {\n console.error(`[Cloud] ${message}`, error)\n return reporter ? reporter(error, context) : Promise.resolve()\n}\n\nfunction requestContext(context: Context): CloudErrorContext {\n return { source: 'request', method: context.req.method, route: routePath(context) }\n}\n\n/**\n * The app's last error handler, as Hono's default: an `HTTPException` answers with its response,\n * anything else is logged, reported, and answered with a 500.\n */\nexport function cloudErrorHandler(reporter: CloudErrorReporter | undefined): ErrorHandler {\n return (error, context) => {\n if (error instanceof HTTPException) return error.getResponse()\n void reportCloudError(reporter, 'Request failed:', error, requestContext(context))\n return context.text('Internal Server Error', 500)\n }\n}\n","import { staticEntitlementsSchema } from '#cloud/server/policy/schema'\nimport * as v from 'valibot'\n\nexport const setWorkspaceEntitlementsSchema = v.object({\n values: staticEntitlementsSchema,\n /** Who decided these values, such as `billing`; stored as the row's source. */\n source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),\n /** Increases with every decision the writer makes, such as a billing event's timestamp. */\n externalVersion: v.pipe(v.number(), v.safeInteger(), v.minValue(0))\n})\n","import type { CloudDatabase } from '#cloud/server/db'\nimport { createWorkspaceEntitlementRepository } from '#cloud/server/policy'\nimport type { Kysely } from 'kysely'\nimport * as v from 'valibot'\n\nimport { setWorkspaceEntitlementsSchema } from './schema'\n\nexport type SetWorkspaceEntitlementsInput = v.InferInput<typeof setWorkspaceEntitlementsSchema>\n\nexport function parseSetWorkspaceEntitlements(input: unknown) {\n return v.parse(setWorkspaceEntitlementsSchema, input)\n}\n\n/**\n * What services beside Cloud, such as billing, may change. Runtimes expose it to them through\n * their own transport: an authenticated HTTP route on Node, a service binding on Workers.\n */\nexport function createInternalService(database: Kysely<CloudDatabase>) {\n const entitlements = createWorkspaceEntitlementRepository(database)\n return {\n /** `found` is false for an unknown workspace; `applied` is false for an outdated version. */\n async setWorkspaceEntitlements(\n workspaceId: string,\n input: SetWorkspaceEntitlementsInput\n ): Promise<{ found: boolean; applied: boolean }> {\n const { values, source, externalVersion } = parseSetWorkspaceEntitlements(input)\n const workspace = await database\n .selectFrom('workspace')\n .select('id')\n .where('id', '=', workspaceId)\n .executeTakeFirst()\n if (!workspace) return { found: false, applied: false }\n const { applied } = await entitlements.setVersioned(\n workspaceId,\n values,\n source,\n externalVersion\n )\n return { found: true, applied }\n }\n }\n}\n\nexport type InternalService = ReturnType<typeof createInternalService>\n","import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'\nimport { validatedJSON, workspaceParams } from '#cloud/server/validation'\nimport { Hono } from 'hono'\nimport { bearerAuth } from 'hono/bearer-auth'\n\nimport { parseSetWorkspaceEntitlements, type InternalService } from './service'\n\n/** The internal API on HTTP, for runtimes without a private transport to their services. */\nexport function createInternalRoutes(service: InternalService, serviceToken: string) {\n const digest = hashCapability(serviceToken)\n const unauthorized = { error: { code: 'unauthorized' as const } }\n return new Hono()\n .use(\n '*',\n bearerAuth({\n verifyToken: (token) => capabilityHashMatches(digest, token),\n noAuthenticationHeader: { message: unauthorized },\n invalidAuthenticationHeader: { message: unauthorized },\n invalidToken: { message: unauthorized }\n })\n )\n .put(\n '/workspaces/:workspaceId/entitlements',\n workspaceParams,\n validatedJSON(parseSetWorkspaceEntitlements),\n async (context) => {\n const { workspaceId } = context.req.valid('param')\n const result = await service.setWorkspaceEntitlements(\n workspaceId,\n context.req.valid('json')\n )\n if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)\n return context.json({ applied: result.applied })\n }\n )\n}\n","import {\n createAdminAuditService,\n createAdminEmailService,\n createAdminOperationsService,\n createAdminUserService,\n createCloudAdminRoutes,\n createEnrollmentService,\n type EnrollmentService\n} from '#cloud/admin'\nimport {\n CLOUD_AI_JWKS_PATH,\n CLOUD_DISCOVERY_PATH,\n CLOUD_PROTOCOL_VERSION,\n type CloudDiscovery\n} from '#cloud/contract'\nimport { createAccountRoutes } from '#cloud/server/account/routes'\nimport { createAITokenService, type AISigningKey } from '#cloud/server/ai'\nimport {\n createCloudAPIRouter,\n createPublicCloudAPIRouter,\n type CloudAPIEnvironment\n} from '#cloud/server/api'\nimport {\n AUTH_BASE_PATH,\n createAuthenticationEmailService,\n createCloudIdentityResolver,\n createCloudSessionResolver,\n type CloudAuthAdapter,\n type CloudIdentityResolver,\n type CloudSessionResolver\n} from '#cloud/server/auth'\nimport { createCollaborationTicketService } from '#cloud/server/collaboration'\nimport {\n CloudConfigError,\n cloudDiscoveryFromConfig,\n type CloudServerConfig\n} from '#cloud/server/config'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport { createDocumentService } from '#cloud/server/documents'\nimport { createDocumentVersionService } from '#cloud/server/documents/versions'\nimport type { TransactionalEmailService } from '#cloud/server/email'\nimport { cloudErrorHandler, type CloudErrorReporter } from '#cloud/server/errors'\nimport { createInternalRoutes, createInternalService } from '#cloud/server/internal'\nimport type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport { createPictureRoutes, createUserPictures } from '#cloud/server/pictures'\nimport {\n createConfiguredCloudPolicy,\n createDefaultCloudPolicy,\n createEntitlementService,\n EntitlementOpenFeatureProvider,\n type CloudPolicy,\n type EntitlementSource\n} from '#cloud/server/policy'\nimport {\n CLOUD_RATE_LIMITS,\n createActorRateLimiter,\n createTrustedIPRateLimiter,\n routeHasOwnBudget\n} from '#cloud/server/rate-limit'\nimport { createDocumentSharingService } from '#cloud/server/sharing'\nimport { createWorkspaceMemberService, createWorkspaceService } from '#cloud/server/workspaces'\nimport { Hono, type Context } from 'hono'\nimport { cors } from 'hono/cors'\nimport type { Kysely } from 'kysely'\n\nexport type CloudServices = {\n config: CloudServerConfig\n database: Kysely<CloudDatabase>\n auth: CloudAuthAdapter\n objects: ObjectStore\n resolveIdentity?: CloudIdentityResolver\n resolveSession?: CloudSessionResolver\n invitationDelivery?: InvitationDelivery\n invitationOutbox?: InvitationOutbox\n transactionalEmail?: TransactionalEmailService\n enrollment?: EnrollmentService\n entitlementSource?: EntitlementSource\n policy?: CloudPolicy\n /** The imported `aiSigningKey`, required when the config names one. See `loadAISigningKey`. */\n aiSigningKey?: AISigningKey\n /**\n * Where clients reach this runtime's collaboration relay. Without one, Cloud rooms fall back to\n * peer-to-peer and writes are not enforced by the server.\n */\n relayURL?: string\n /** Ends a restored document's live rooms, on the relay this runtime runs, if any. */\n onDocumentRestored?: (documentId: string) => void\n /** Tells a document's live rooms its version history changed, on the relay this runtime runs. */\n onDocumentVersionsChanged?: (documentId: string) => void\n /** Reports errors no route handled, when the deployment configures error tracking. */\n reportError?: CloudErrorReporter\n}\n\ntype CloudEnvironment = CloudAPIEnvironment\n\nfunction discoveryFromServices(services: CloudServices): CloudDiscovery {\n return cloudDiscoveryFromConfig(services.config)\n}\n\nexport function shouldPreventIndexing(path: string, policy: 'allow' | 'deny'): boolean {\n return (\n policy === 'deny' ||\n path.startsWith('/api/') ||\n path.startsWith('/admin') ||\n path.startsWith('/auth') ||\n path.startsWith('/account') ||\n path === '/app' ||\n path === '/sign-in' ||\n path === '/sign-up' ||\n path === '/join' ||\n path === CLOUD_DISCOVERY_PATH\n )\n}\n\nexport function withIndexingPolicy(\n response: Response,\n path: string,\n policy: 'allow' | 'deny'\n): Response {\n if (!shouldPreventIndexing(path, policy)) return response\n const headers = new Headers(response.headers)\n headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n })\n}\n\nexport function createCloudApp(services: CloudServices) {\n const discovery = discoveryFromServices(services)\n const resolveIdentity = services.resolveIdentity ?? createCloudIdentityResolver(services.auth)\n const resolveSession = services.resolveSession ?? createCloudSessionResolver(services.auth)\n const allowedOrigins = new Set(\n [services.config.publicURL, ...services.config.trustedOrigins].map(\n (origin) => new URL(origin).origin\n )\n )\n const cloudCORS = cors({\n origin: (origin) => (allowedOrigins.has(origin) ? origin : null),\n allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],\n allowHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n maxAge: 600\n })\n const workspaces = createWorkspaceService(services.database)\n const pictures = createUserPictures(services.database, { publicURL: services.config.publicURL })\n const workspaceMembers = createWorkspaceMemberService(services.database, {\n email: services.transactionalEmail,\n publicURL: services.config.publicURL\n })\n const enrollment =\n services.enrollment ??\n createEnrollmentService(services.database, {\n publicURL: services.config.publicURL,\n adminRecipients: services.config.enrollmentAdminNotificationEmails,\n email: services.transactionalEmail\n })\n const admin = createCloudAdminRoutes(\n {\n email: createAdminEmailService(services.database, services.transactionalEmail, {\n publicURL: services.config.publicURL\n }),\n enrollment,\n users: createAdminUserService(services.database, services.auth, {\n requireMFA: services.config.deploymentAdminMFARequired,\n pictures,\n notify: services.transactionalEmail\n ? createAuthenticationEmailService(services.transactionalEmail, services.config.publicURL)\n : undefined\n }),\n audit: createAdminAuditService(services.database),\n operations: createAdminOperationsService(services.database, services.config)\n },\n allowedOrigins,\n {\n database: services.database,\n secret: services.config.authSecret,\n auth: services.auth,\n requireMFA: services.config.deploymentAdminMFARequired\n }\n )\n const policy =\n services.policy ??\n (services.entitlementSource\n ? createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(services.entitlementSource))\n : createConfiguredCloudPolicy(services.config, services.database))\n const documents = createDocumentService(services.database, services.objects, {\n policy,\n technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes,\n onVersionsChanged: services.onDocumentVersionsChanged\n })\n const versions = createDocumentVersionService(services.database, services.objects, {\n policy,\n deploymentMode: services.config.deployment,\n onRestored: services.onDocumentRestored,\n onVersionsChanged: services.onDocumentVersionsChanged\n })\n const entitlements = createEntitlementService(\n services.database,\n policy,\n services.config.technicalLimits.maximumUploadBytes,\n services.config.technicalLimits.maximumConnectionsPerRoom\n )\n const sharing = createDocumentSharingService(services.database, {\n delivery: services.invitationDelivery,\n outbox: services.invitationOutbox,\n continuationSecret: services.config.authSecret,\n publicURL: services.config.publicURL,\n policy,\n deploymentMode: services.config.deployment,\n workspaceInvitations: workspaceMembers\n })\n const collaboration = createCollaborationTicketService({\n database: services.database,\n sharing,\n authSecret: services.config.authSecret,\n relayURL: services.relayURL,\n policy,\n deploymentMode: services.config.deployment\n })\n if (services.config.aiSigningKey && !services.aiSigningKey) {\n throw new CloudConfigError('The AI service needs the signing key imported by loadAISigningKey')\n }\n const aiTokens = services.aiSigningKey\n ? createAITokenService({\n database: services.database,\n policy,\n deploymentMode: services.config.deployment,\n issuer: new URL(services.config.publicURL).origin,\n signingKey: services.aiSigningKey,\n lifetimeSeconds: services.config.aiTokenLifetimeSeconds\n })\n : undefined\n\n const requireActiveSession = async (context: Context, next: () => Promise<void>) => {\n const actor = await resolveSession(context.req.raw)\n if (!actor) return context.json({ error: { code: 'unauthorized' as const } }, 401)\n context.set('actor', actor)\n return next()\n }\n const publicRateLimiter = createTrustedIPRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.publicCapability,\n { trustedHeaders: services.config.authTrustedIPHeaders },\n (context) => context.json({ error: { code: 'not_found' as const } }, 404),\n {\n resource: (context) => context.req.path,\n // Guests refresh collaboration tickets on their own budget, `publicCollaborationLimiter`.\n skip: routeHasOwnBudget\n }\n )\n const publicCollaborationLimiter = createTrustedIPRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.collaborationTicket,\n { trustedHeaders: services.config.authTrustedIPHeaders },\n (context) => context.json({ error: { code: 'not_found' as const } }, 404),\n { resource: (context) => context.req.path, route: true }\n )\n const authenticatedMutationLimiter = createActorRateLimiter(\n services.database,\n services.config.authSecret,\n CLOUD_RATE_LIMITS.authenticatedMutation,\n // Reads are free, and a route with a budget of its own, such as creating documents, counts\n // against that instead.\n (context) => context.req.method === 'GET' || routeHasOwnBudget(context)\n )\n\n const accountRoutes = createAccountRoutes({\n auth: services.auth,\n pictures,\n config: services.config,\n enrollment,\n workspaces,\n resolveIdentity,\n resolveSession,\n requireActiveSession,\n authenticatedMutationLimiter\n })\n const cloudAPI = createCloudAPIRouter({\n collaboration,\n database: services.database,\n rateLimitSecret: services.config.authSecret,\n documents,\n versions,\n entitlements,\n aiTokens,\n sharing,\n workspaces,\n workspaceMembers,\n resolveSession\n })\n const publicCloudAPI = createPublicCloudAPIRouter({\n collaboration,\n documents,\n versions,\n entitlements,\n sharing,\n workspaces,\n workspaceMembers,\n resolveSession\n })\n\n // Services such as billing authenticate with their own token, not a session.\n const internalAPI = services.config.internalServiceToken\n ? createInternalRoutes(\n createInternalService(services.database),\n services.config.internalServiceToken\n )\n : new Hono()\n\n return new Hono<CloudEnvironment>()\n .onError(cloudErrorHandler(services.reportError))\n .use(CLOUD_DISCOVERY_PATH, cloudCORS)\n .use('/api/*', cloudCORS)\n .use('*', async (context, next) => {\n await next()\n if (shouldPreventIndexing(context.req.path, services.config.indexingPolicy)) {\n context.header('X-Robots-Tag', 'noindex, nofollow, noarchive')\n }\n })\n .get('/robots.txt', (context) => {\n context.header('Content-Type', 'text/plain; charset=utf-8')\n return context.body(\n services.config.indexingPolicy === 'deny'\n ? 'User-agent: *\\nDisallow: /\\n'\n : 'User-agent: *\\nDisallow: /admin\\nDisallow: /account\\nDisallow: /app\\nDisallow: /api\\nDisallow: /auth\\nDisallow: /sign-in\\nDisallow: /sign-up\\nDisallow: /join\\nDisallow: /.well-known\\n'\n )\n })\n .get('/health', (context) =>\n context.json({\n status: 'ok' as const,\n protocolVersion: CLOUD_PROTOCOL_VERSION\n })\n )\n .get('/ready', async (context) => {\n try {\n await services.database.selectFrom('workspace').select('id').limit(1).execute()\n const objects = await services.objects.checkReadiness()\n if (!objects.ok) {\n return context.json(\n { status: 'unavailable' as const, dependency: 'object_storage' as const },\n 503\n )\n }\n return context.json({\n status: 'ready' as const,\n objectStorage: {\n checksumVerification: objects.checksumVerification,\n multipartUpload: services.objects.capabilities.multipartUpload\n }\n })\n } catch {\n return context.json({ status: 'unavailable' as const }, 503)\n }\n })\n .get(CLOUD_DISCOVERY_PATH, (context) => context.json(discovery))\n .get(CLOUD_AI_JWKS_PATH, async (context) =>\n aiTokens ? context.json(aiTokens.jwks()) : context.notFound()\n )\n .on(['GET', 'POST'], `${AUTH_BASE_PATH}/*`, (context) => services.auth.handler(context.req.raw))\n .route('/', accountRoutes)\n .route('/', createPictureRoutes(pictures))\n .use('/api/shares/:shareId/collaboration-ticket', publicCollaborationLimiter)\n .use('/api/public/*', publicRateLimiter)\n .use('/api/shares/*', publicRateLimiter)\n .use('/api/invitations/*', publicRateLimiter)\n .route('/api', publicCloudAPI)\n .route('/api/internal', internalAPI)\n .use('/api/*', requireActiveSession)\n .route('/api/admin', admin)\n .use('/api/*', authenticatedMutationLimiter)\n .route('/api', cloudAPI)\n}\n\nexport type CloudApp = ReturnType<typeof createCloudApp>\n","import type { Dialect } from 'kysely'\nimport { CamelCasePlugin, Kysely } from 'kysely'\n\nimport type { CloudDatabase } from './tables'\n\nexport type CloudDatabaseOptions = {\n dialect: Dialect\n}\n\nexport function createCloudDatabase(options: CloudDatabaseOptions): Kysely<CloudDatabase> {\n return new Kysely<CloudDatabase>({\n dialect: options.dialect,\n plugins: [new CamelCasePlugin()]\n })\n}\n","import {\n Body,\n Button,\n Container,\n Head,\n Heading,\n // eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.\n Html as HTML,\n Img,\n Link,\n Preview,\n Section,\n Text\n} from '@vue-email/components'\nimport { h, type VNode } from 'vue'\n\n/** The ivory app-icon tile, served as PNG because mail clients do not draw SVG. */\nconst LOGO_URL = 'https://openpencil.dev/brand/app-icon-1024.png'\nconst SITE_URL = 'https://openpencil.dev'\n\nconst FONT = '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif'\nconst INK = '#171717'\nconst MUTED = '#6B6B6B'\n/** Deep teal from the mark; white text on it passes WCAG AA. */\nconst TEAL = '#0A6C65'\n\nconst styles = {\n body: { backgroundColor: '#F5F5EF', fontFamily: FONT, margin: '0', padding: '40px 16px' },\n card: {\n maxWidth: '480px',\n margin: '0 auto',\n padding: '40px',\n backgroundColor: '#FFFFFF',\n borderRadius: '16px',\n border: '1px solid #E7E5DC'\n },\n logo: { borderRadius: '10px', margin: '0 0 28px' },\n heading: {\n color: INK,\n fontSize: '22px',\n fontWeight: '600',\n lineHeight: '1.3',\n margin: '0 0 12px'\n },\n text: { color: '#404040', fontSize: '15px', lineHeight: '1.6', margin: '0 0 24px' },\n button: {\n backgroundColor: TEAL,\n borderRadius: '10px',\n color: '#FFFFFF',\n fontSize: '15px',\n fontWeight: '600',\n padding: '12px 22px',\n textDecoration: 'none'\n },\n note: { color: MUTED, fontSize: '13px', lineHeight: '1.6', margin: '28px 0 0' },\n link: { color: TEAL, textDecoration: 'underline' },\n footer: {\n color: MUTED,\n fontSize: '12px',\n lineHeight: '1.6',\n textAlign: 'center' as const,\n margin: '24px 0 0'\n }\n}\n\nexport type EmailLayoutProps = {\n /** The line mail clients show beside the subject. */\n preview: string\n heading: string\n message: string\n actionLabel: string\n actionURL: string\n /** Small print under the button, with an optional link at its end. */\n note?: { text: string; link?: { label: string; url: string } }\n}\n\nfunction noteContent(note: NonNullable<EmailLayoutProps['note']>) {\n if (!note.link) return note.text\n const { label, url } = note.link\n return [`${note.text} `, h(Link, { href: url, style: styles.link }, () => label), '.']\n}\n\n/** The branded email every OpenPencil service sends: the waitlist and Cloud alike. */\nexport function emailLayout(props: EmailLayoutProps): VNode {\n const { note } = props\n return h(HTML, { lang: 'en' }, () => [\n h(Head),\n h(Preview, () => props.preview),\n h(Body, { style: styles.body }, () => [\n h(Container, { style: styles.card }, () => [\n h(Img, { src: LOGO_URL, width: 44, height: 44, alt: 'OpenPencil', style: styles.logo }),\n h(Heading, { as: 'h1', style: styles.heading }, () => props.heading),\n h(Text, { style: styles.text }, () => props.message),\n h(Section, () =>\n h(Button, { href: props.actionURL, style: styles.button }, () => props.actionLabel)\n ),\n note ? h(Text, { style: styles.note }, () => noteContent(note)) : null\n ]),\n h(Text, { style: styles.footer }, () => [\n 'OpenPencil, the open-source design editor · ',\n h(Link, { href: SITE_URL, style: { color: MUTED } }, () => 'openpencil.dev')\n ])\n ])\n ])\n}\n","import type { VNode } from 'vue'\n\nimport { emailLayout } from './brand'\n\nexport type TransactionalEmailLayout = {\n preview: string\n heading: string\n message: string\n actionLabel: string\n actionURL: string\n footer?: string\n}\n\n/** Cloud's mail in the same branded layout as the waitlist's, so people know who wrote. */\nexport function transactionalEmailLayout(props: TransactionalEmailLayout): VNode {\n const { footer, ...content } = props\n return emailLayout({ ...content, note: footer ? { text: footer } : undefined })\n}\n","import { defineComponent, type PropType } from 'vue'\n\nimport { transactionalEmailLayout } from './layout'\n\nexport type DocumentInvitationEmailProps = {\n inviterName: string\n documentName: string\n permissionLabel: string\n expiresAt: string\n acceptanceURL: string\n}\n\nexport const DocumentInvitationEmail = defineComponent({\n props: {\n inviterName: { type: String, required: true },\n documentName: { type: String, required: true },\n permissionLabel: { type: String, required: true },\n expiresAt: { type: String, required: true },\n acceptanceURL: { type: String, required: true }\n } satisfies Record<\n keyof DocumentInvitationEmailProps,\n { type: PropType<string>; required: true }\n >,\n setup(props) {\n return () =>\n transactionalEmailLayout({\n preview: `${props.inviterName} invited you to ${props.permissionLabel} a document`,\n heading: 'OpenPencil invitation',\n message: `${props.inviterName} invited you to ${props.permissionLabel} “${props.documentName}”.`,\n actionLabel: 'Open document',\n actionURL: props.acceptanceURL,\n footer: `This invitation expires ${props.expiresAt}.`\n })\n }\n})\n","import { defineComponent, type PropType } from 'vue'\n\nimport { transactionalEmailLayout } from './layout'\n\nexport type EnrollmentEmailProps = {\n heading: string\n preview: string\n message: string\n actionLabel: string\n actionURL: string\n /** Small print under the button. */\n footer?: string\n}\n\nexport const EnrollmentEmail = defineComponent({\n props: {\n heading: { type: String, required: true },\n preview: { type: String, required: true },\n message: { type: String, required: true },\n actionLabel: { type: String, required: true },\n actionURL: { type: String, required: true },\n footer: { type: String, required: false }\n } satisfies Record<keyof EnrollmentEmailProps, { type: PropType<string>; required: boolean }>,\n setup(props) {\n return () => transactionalEmailLayout(props)\n }\n})\n","import { render } from '@vue-email/render'\nimport { compact } from 'es-toolkit'\n\nimport type {\n AdminEnrollmentNotificationPayload,\n AuthenticationEmailPayload,\n DocumentInvitationEmailPayload,\n EmailChangeRequestedPayload,\n EnrollmentEmailPayload,\n NewSignInPayload,\n RenderedTransactionalEmail,\n TransactionalEmailContent,\n TransactionalEmailKind,\n TwoStepChange,\n TwoStepChangedPayload,\n WorkspaceInvitationEmailPayload\n} from './schema'\nimport { DocumentInvitationEmail } from './templates/document-invitation'\nimport { EnrollmentEmail } from './templates/enrollment'\n\nasync function rendered(\n component: Parameters<typeof render>[0],\n props: Record<string, string | undefined>,\n subject: string\n): Promise<RenderedTransactionalEmail> {\n const [html, text] = await Promise.all([\n render(component, props),\n render(component, props, { plainText: true })\n ])\n return { subject, html, text }\n}\n\nasync function renderDocumentInvitation(payload: DocumentInvitationEmailPayload) {\n const permissionLabel = payload.permission === 'edit' ? 'edit' : 'view'\n return rendered(\n DocumentInvitationEmail,\n {\n inviterName: payload.inviterName,\n documentName: payload.documentName,\n permissionLabel,\n expiresAt: new Date(payload.expiresAt).toUTCString(),\n acceptanceURL: payload.acceptanceURL\n },\n `${payload.inviterName} invited you to ${permissionLabel} ${payload.documentName}`\n )\n}\n\nconst WORKSPACE_ROLE_LABELS = { admin: 'manage', editor: 'edit in', viewer: 'view' } as const\n\nasync function renderWorkspaceInvitation(payload: WorkspaceInvitationEmailPayload) {\n const action = WORKSPACE_ROLE_LABELS[payload.role]\n return rendered(\n EnrollmentEmail,\n {\n heading: `Join ${payload.workspaceName}`,\n preview: `${payload.inviterName} invited you to ${payload.workspaceName}`,\n message: `${payload.inviterName} invited you to ${action} the workspace “${payload.workspaceName}” on OpenPencil Cloud. You will see its documents on Home once you join.`,\n actionLabel: 'Join workspace',\n actionURL: payload.acceptanceURL,\n footer: `This invitation expires ${new Date(payload.expiresAt).toUTCString()}.`\n },\n `${payload.inviterName} invited you to ${payload.workspaceName}`\n )\n}\n\ntype EnrollmentMessageKind = Exclude<\n TransactionalEmailKind,\n | 'document-invitation'\n | 'workspace-invitation'\n | 'admin-enrollment-notification'\n | 'email-verification'\n | 'password-reset'\n | 'password-changed'\n | 'email-change-requested'\n | 'new-sign-in'\n | 'two-step-changed'\n>\n\ntype EnrollmentCopy = {\n subject: string\n heading: string\n preview: string\n message: string\n actionLabel: string\n}\n\nconst ENROLLMENT_COPY: Record<EnrollmentMessageKind, Omit<EnrollmentCopy, 'message'>> = {\n 'enrollment-requested': {\n subject: 'We received your OpenPencil Cloud request',\n heading: 'Request received',\n preview: 'Your OpenPencil Cloud access request is awaiting review.',\n actionLabel: 'Open OpenPencil Cloud'\n },\n 'enrollment-approved': {\n subject: 'Your OpenPencil Cloud access is ready',\n heading: 'Access approved',\n preview: 'You can now sign in to OpenPencil Cloud.',\n actionLabel: 'Sign in'\n },\n 'enrollment-rejected': {\n subject: 'Your OpenPencil Cloud request was reviewed',\n heading: 'Request reviewed',\n preview: 'Your current access request was not approved.',\n actionLabel: 'Request access again'\n },\n 'enrollment-revoked': {\n subject: 'Your OpenPencil Cloud access has changed',\n heading: 'Access changed',\n preview: 'Your OpenPencil Cloud access is no longer active.',\n actionLabel: 'Open OpenPencil'\n }\n}\n\nfunction enrollmentCopy(kind: EnrollmentMessageKind, name: string): EnrollmentCopy {\n const copy = ENROLLMENT_COPY[kind]\n const messages: Record<EnrollmentMessageKind, string> = {\n 'enrollment-requested': `Hi ${name}, your request is awaiting manual review.`,\n 'enrollment-approved': `Hi ${name}, your access request was approved.`,\n 'enrollment-rejected': `Hi ${name}, your current access request was not approved.`,\n 'enrollment-revoked': `Hi ${name}, your Cloud access is no longer active.`\n }\n return { ...copy, message: messages[kind] }\n}\n\nasync function renderEnrollment(kind: EnrollmentMessageKind, payload: EnrollmentEmailPayload) {\n const copy = enrollmentCopy(kind, payload.name)\n return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL }, copy.subject)\n}\n\nasync function renderAdminNotification(payload: AdminEnrollmentNotificationPayload) {\n return rendered(\n EnrollmentEmail,\n {\n heading: 'New Cloud access request',\n preview: `${payload.requesterEmail} requested OpenPencil Cloud access.`,\n message: `${payload.requesterName} (${payload.requesterEmail}) requested access. ${payload.reason}`,\n actionLabel: 'Review request',\n actionURL: payload.actionURL\n },\n 'New OpenPencil Cloud access request'\n )\n}\n\nasync function renderAuthentication(\n kind: 'email-verification' | 'password-reset' | 'password-changed',\n payload: AuthenticationEmailPayload\n) {\n const copy = {\n 'email-verification':\n payload.purpose === 'change'\n ? {\n subject: 'Confirm your new OpenPencil Cloud email',\n heading: 'Confirm your new email',\n preview: 'One click to move your OpenPencil Cloud account to this address.',\n message: `Hi ${payload.name}, confirm this address to make it your OpenPencil Cloud account’s email. Your old address stays until you do.`,\n actionLabel: 'Confirm email',\n footer: 'Didn’t ask for this? Ignore this email and nothing changes.'\n }\n : {\n subject: 'Confirm your OpenPencil Cloud email',\n heading: 'Confirm your email',\n preview: 'One click to finish creating your OpenPencil Cloud account.',\n message: `Hi ${payload.name}, confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.`,\n actionLabel: 'Confirm email',\n footer: 'Didn’t create an account? Ignore this email and nothing happens.'\n },\n 'password-reset': {\n subject: 'Reset your OpenPencil Cloud password',\n heading: 'Reset your password',\n preview: 'Use this secure link to choose a new password.',\n message: `Hi ${payload.name}, use the link below to choose a new password.`,\n actionLabel: 'Reset password',\n footer: 'Didn’t ask for this? Ignore this email and your password stays the same.'\n },\n 'password-changed': {\n subject: 'Your OpenPencil Cloud password changed',\n heading: 'Password changed',\n preview: 'Your OpenPencil Cloud password was changed.',\n message: `Hi ${payload.name}, your password was changed. If this was not you, contact your administrator.`,\n actionLabel: 'Open OpenPencil Cloud'\n }\n }[kind]\n return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL ?? '#' }, copy.subject)\n}\n\nasync function renderEmailChangeRequested(payload: EmailChangeRequestedPayload) {\n return rendered(\n EnrollmentEmail,\n {\n heading: 'Your email is changing',\n preview: `Your OpenPencil Cloud email is changing to ${payload.newEmail}.`,\n message: `Hi ${payload.name}, someone signed in to your account asked to change its email to ${payload.newEmail}. It changes once that address confirms it. If this wasn’t you, change your password and sign out of your other sessions.`,\n actionLabel: 'Review your account',\n actionURL: payload.actionURL\n },\n 'Your OpenPencil Cloud email is changing'\n )\n}\n\nasync function renderNewSignIn(payload: NewSignInPayload) {\n const device = payload.desktop\n ? 'the OpenPencil app'\n : compact([payload.browser, payload.system]).join(' on ') || 'an unknown browser'\n const place = payload.ipAddress ? ` from ${payload.ipAddress}` : ''\n return rendered(\n EnrollmentEmail,\n {\n heading: 'New sign-in to your account',\n preview: `Your OpenPencil Cloud account was signed in to with ${device}.`,\n message: `Hi ${payload.name}, your account was signed in to with ${device}${place} on ${new Date(payload.signedInAt).toUTCString()}. If this was you, there’s nothing to do. If it wasn’t, sign that session out and change your password.`,\n actionLabel: 'Review sessions',\n actionURL: payload.actionURL\n },\n 'New sign-in to your OpenPencil Cloud account'\n )\n}\n\nconst TWO_STEP_COPY: Record<TwoStepChange, { heading: string; message: string }> = {\n 'authenticator-on': {\n heading: 'Authenticator app turned on',\n message: 'an authenticator app now confirms your sign-ins.'\n },\n 'authenticator-off': {\n heading: 'Authenticator app turned off',\n message: 'your sign-ins no longer ask for a code from an authenticator app.'\n },\n 'passkey-added': {\n heading: 'Passkey added',\n message: 'a passkey was added to your account.'\n },\n 'passkey-removed': {\n heading: 'Passkey removed',\n message: 'a passkey was removed from your account.'\n },\n 'reset-by-administrator': {\n heading: 'Two-step sign-in was reset',\n message:\n 'an administrator removed your authenticator app, recovery codes, and passkeys, so you can set them up again.'\n }\n}\n\nasync function renderTwoStepChanged(payload: TwoStepChangedPayload) {\n const copy = TWO_STEP_COPY[payload.change]\n return rendered(\n EnrollmentEmail,\n {\n heading: copy.heading,\n preview: `${copy.heading} on your OpenPencil Cloud account.`,\n message: `Hi ${payload.name}, ${copy.message} If this wasn’t you, change your password and contact your administrator.`,\n actionLabel: 'Review security',\n actionURL: payload.actionURL\n },\n `${copy.heading} on your OpenPencil Cloud account`\n )\n}\n\nexport async function renderTransactionalEmail(\n content: TransactionalEmailContent\n): Promise<RenderedTransactionalEmail> {\n if (content.kind === 'document-invitation') return renderDocumentInvitation(content.payload)\n if (content.kind === 'workspace-invitation') return renderWorkspaceInvitation(content.payload)\n if (content.kind === 'admin-enrollment-notification') {\n return renderAdminNotification(content.payload)\n }\n if (\n content.kind === 'email-verification' ||\n content.kind === 'password-reset' ||\n content.kind === 'password-changed'\n ) {\n return renderAuthentication(content.kind, content.payload)\n }\n if (content.kind === 'email-change-requested') return renderEmailChangeRequested(content.payload)\n if (content.kind === 'new-sign-in') return renderNewSignIn(content.payload)\n if (content.kind === 'two-step-changed') return renderTwoStepChanged(content.payload)\n return renderEnrollment(content.kind, content.payload)\n}\n","import { documentPermissionSchema, workspaceRoleSchema } from '#cloud/contract'\nimport * as v from 'valibot'\n\nexport type TransactionalEmailKind =\n | 'document-invitation'\n | 'workspace-invitation'\n | 'enrollment-requested'\n | 'admin-enrollment-notification'\n | 'enrollment-approved'\n | 'enrollment-rejected'\n | 'enrollment-revoked'\n | 'email-verification'\n | 'password-reset'\n | 'password-changed'\n | 'email-change-requested'\n | 'new-sign-in'\n | 'two-step-changed'\n\nconst documentInvitationEmailPayloadSchema = v.object({\n inviterName: v.string(),\n documentName: v.string(),\n permission: documentPermissionSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst workspaceInvitationEmailPayloadSchema = v.object({\n inviterName: v.string(),\n workspaceName: v.string(),\n role: workspaceRoleSchema,\n expiresAt: v.string(),\n acceptanceURL: v.string()\n})\n\nconst enrollmentEmailPayloadSchema = v.object({\n name: v.string(),\n actionURL: v.string()\n})\n\nconst adminEnrollmentNotificationPayloadSchema = v.object({\n requesterEmail: v.string(),\n requesterName: v.string(),\n reason: v.string(),\n actionURL: v.string()\n})\n\nconst authenticationEmailPayloadSchema = v.object({\n name: v.string(),\n actionURL: v.optional(v.string()),\n /** What a verification link confirms: a new account, or a new address for one. */\n purpose: v.optional(v.picklist(['account', 'change']))\n})\n\nconst emailChangeRequestedPayloadSchema = v.object({\n name: v.string(),\n newEmail: v.string(),\n actionURL: v.string()\n})\n\nconst newSignInPayloadSchema = v.object({\n name: v.string(),\n signedInAt: v.string(),\n ipAddress: v.nullable(v.string()),\n browser: v.nullable(v.string()),\n system: v.nullable(v.string()),\n desktop: v.boolean(),\n actionURL: v.string()\n})\n\n/** What changed about how an account proves it is its owner's. */\nexport const twoStepChangeSchema = v.picklist([\n 'authenticator-on',\n 'authenticator-off',\n 'passkey-added',\n 'passkey-removed',\n 'reset-by-administrator'\n])\n\nconst twoStepChangedPayloadSchema = v.object({\n name: v.string(),\n change: twoStepChangeSchema,\n actionURL: v.string()\n})\n\nfunction content<const Kind extends TransactionalEmailKind, Payload extends v.GenericSchema>(\n kind: Kind,\n payload: Payload\n) {\n return v.object({ kind: v.literal(kind), payload })\n}\n\nexport const transactionalEmailContentSchema = v.variant('kind', [\n content('document-invitation', documentInvitationEmailPayloadSchema),\n content('workspace-invitation', workspaceInvitationEmailPayloadSchema),\n content('enrollment-requested', enrollmentEmailPayloadSchema),\n content('admin-enrollment-notification', adminEnrollmentNotificationPayloadSchema),\n content('enrollment-approved', enrollmentEmailPayloadSchema),\n content('enrollment-rejected', enrollmentEmailPayloadSchema),\n content('enrollment-revoked', enrollmentEmailPayloadSchema),\n content('email-verification', authenticationEmailPayloadSchema),\n content('password-reset', authenticationEmailPayloadSchema),\n content('password-changed', authenticationEmailPayloadSchema),\n content('email-change-requested', emailChangeRequestedPayloadSchema),\n content('new-sign-in', newSignInPayloadSchema),\n content('two-step-changed', twoStepChangedPayloadSchema)\n])\n\n/** A transactional email's kind with the payload that kind renders. */\nexport type TransactionalEmailContent = v.InferOutput<typeof transactionalEmailContentSchema>\n\nexport type DocumentInvitationEmailPayload = v.InferOutput<\n typeof documentInvitationEmailPayloadSchema\n>\nexport type WorkspaceInvitationEmailPayload = v.InferOutput<\n typeof workspaceInvitationEmailPayloadSchema\n>\nexport type EnrollmentEmailPayload = v.InferOutput<typeof enrollmentEmailPayloadSchema>\nexport type AdminEnrollmentNotificationPayload = v.InferOutput<\n typeof adminEnrollmentNotificationPayloadSchema\n>\nexport type AuthenticationEmailPayload = v.InferOutput<typeof authenticationEmailPayloadSchema>\nexport type EmailChangeRequestedPayload = v.InferOutput<typeof emailChangeRequestedPayloadSchema>\nexport type NewSignInPayload = v.InferOutput<typeof newSignInPayloadSchema>\nexport type TwoStepChange = v.InferOutput<typeof twoStepChangeSchema>\nexport type TwoStepChangedPayload = v.InferOutput<typeof twoStepChangedPayloadSchema>\n\nexport type TransactionalEmailPayloadByKind = {\n [Kind in TransactionalEmailKind]: Extract<TransactionalEmailContent, { kind: Kind }>['payload']\n}\n\nexport type TransactionalEmailMessage<\n Kind extends TransactionalEmailKind = TransactionalEmailKind\n> = {\n id: string\n kind: Kind\n recipientEmail: string\n payload: TransactionalEmailPayloadByKind[Kind]\n}\n\nexport type RenderedTransactionalEmail = {\n subject: string\n html: string\n text: string\n}\n","import {\n transactionalEmailContentSchema,\n type TransactionalEmailContent,\n type TransactionalEmailKind,\n type TransactionalEmailPayloadByKind\n} from '#cloud/email'\nimport { hkdf } from '@noble/hashes/hkdf.js'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { utf8ToBytes } from '@noble/hashes/utils.js'\nimport { compactDecrypt, CompactEncrypt } from 'jose'\nimport * as v from 'valibot'\n\nconst EMAIL_PAYLOAD_SALT = utf8ToBytes('openpencil-cloud-transactional-email')\nconst EMAIL_PAYLOAD_HEADER = { alg: 'dir', enc: 'A256GCM' } as const\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nfunction emailPayloadKey(secret: string, id: string, kind: TransactionalEmailKind): Uint8Array {\n return hkdf(\n sha256,\n utf8ToBytes(secret),\n EMAIL_PAYLOAD_SALT,\n encoder.encode(`openpencil-cloud-email:${kind}:${id}`),\n 32\n )\n}\n\nexport async function encryptTransactionalEmailPayload<Kind extends TransactionalEmailKind>(\n secret: string,\n id: string,\n kind: Kind,\n payload: TransactionalEmailPayloadByKind[Kind]\n): Promise<string> {\n return new CompactEncrypt(encoder.encode(JSON.stringify(payload)))\n .setProtectedHeader(EMAIL_PAYLOAD_HEADER)\n .encrypt(emailPayloadKey(secret, id, kind))\n}\n\nexport async function decryptTransactionalEmailPayload(\n secret: string,\n id: string,\n kind: TransactionalEmailKind,\n value: string\n): Promise<TransactionalEmailContent> {\n const { plaintext, protectedHeader } = await compactDecrypt(\n value,\n emailPayloadKey(secret, id, kind)\n )\n if (\n protectedHeader.alg !== EMAIL_PAYLOAD_HEADER.alg ||\n protectedHeader.enc !== EMAIL_PAYLOAD_HEADER.enc\n ) {\n throw new Error('Unsupported transactional email payload encryption')\n }\n const payload = v.parse(v.pipe(v.string(), v.parseJson()), decoder.decode(plaintext))\n return v.parse(transactionalEmailContentSchema, { kind, payload })\n}\n","import { renderTransactionalEmail } from '#cloud/email'\nimport type { TransactionalEmailKind } from '#cloud/email'\nimport type { CloudDatabase, TransactionalEmailStatus } from '#cloud/server/db'\nimport type { Kysely, Transaction } from 'kysely'\n\nimport { decryptTransactionalEmailPayload, encryptTransactionalEmailPayload } from './crypto'\nimport type {\n EnqueueTransactionalEmailInput,\n TransactionalEmailDeliveryOptions,\n TransactionalEmailDeliveryResult,\n TransactionalEmailService,\n TransactionalEmailTransport\n} from './types'\n\nconst DEFAULT_MAXIMUM_ATTEMPTS = 5\nconst MAXIMUM_RETRY_DELAY_MS = 60 * 60_000\n\nexport type TransactionalEmailTransportErrorKind =\n | 'configuration'\n | 'suppressed'\n | 'permanent'\n | 'rate-limited'\n | 'transient'\n\nexport class TransactionalEmailTransportError extends Error {\n override readonly name = 'TransactionalEmailTransportError'\n\n constructor(\n readonly kind: TransactionalEmailTransportErrorKind,\n readonly code: string,\n message: string,\n options?: ErrorOptions\n ) {\n super(message, options)\n }\n}\n\ntype ClaimedTransactionalEmail = {\n id: string\n kind: TransactionalEmailKind\n recipientEmailNormalized: string\n payloadEncrypted: string\n attemptCount: number\n}\n\nfunction normalizedEmail(value: string): string {\n return value.trim().toLowerCase()\n}\n\nfunction retryDelayMilliseconds(attemptCount: number): number {\n return Math.min(MAXIMUM_RETRY_DELAY_MS, 2 ** Math.max(0, attemptCount - 1) * 30_000)\n}\n\nfunction transportFailure(error: unknown): TransactionalEmailTransportError {\n return error instanceof TransactionalEmailTransportError\n ? error\n : new TransactionalEmailTransportError(\n 'transient',\n 'transport_error',\n 'Transactional email transport failed',\n { cause: error }\n )\n}\n\nfunction failureStatus(\n error: TransactionalEmailTransportError,\n attemptCount: number,\n maximumAttempts: number\n): TransactionalEmailStatus {\n if (error.kind === 'suppressed') return 'suppressed'\n if (error.kind === 'configuration' || error.kind === 'permanent') return 'failed'\n return attemptCount >= maximumAttempts ? 'failed' : 'pending'\n}\n\nexport function createTransactionalEmailService(\n database: Kysely<CloudDatabase>,\n options: {\n encryptionSecret: string\n from: string\n transport?: TransactionalEmailTransport\n }\n): TransactionalEmailService {\n return {\n async enqueue<Kind extends TransactionalEmailKind>(\n input: EnqueueTransactionalEmailInput<Kind>,\n transaction: Transaction<CloudDatabase> | undefined\n ): Promise<string> {\n const id = crypto.randomUUID()\n const payloadEncrypted = await encryptTransactionalEmailPayload(\n options.encryptionSecret,\n id,\n input.kind,\n input.payload\n )\n const executor = transaction ?? database\n const row = await executor\n .insertInto('transactionalEmail')\n .values({\n id,\n idempotencyKey: input.idempotencyKey,\n kind: input.kind,\n recipientEmailNormalized: normalizedEmail(input.recipientEmail),\n payloadEncrypted,\n status: 'pending',\n nextAttemptAt: new Date(),\n claimId: null,\n claimedAt: null,\n transport: null,\n transportMessageId: null,\n lastErrorCode: null,\n acceptedAt: null\n })\n .onConflict((conflict) => conflict.column('idempotencyKey').doNothing())\n .returning('id')\n .executeTakeFirst()\n if (row) return row.id\n return (\n await executor\n .selectFrom('transactionalEmail')\n .select('id')\n .where('idempotencyKey', '=', input.idempotencyKey)\n .executeTakeFirstOrThrow()\n ).id\n },\n\n async deliverPending(\n deliveryOptions: TransactionalEmailDeliveryOptions\n ): Promise<TransactionalEmailDeliveryResult> {\n if (!options.transport) {\n return { claimed: 0, accepted: 0, retrying: 0, failed: 0, suppressed: 0 }\n }\n const now = deliveryOptions.now ?? new Date()\n const maximumAttempts = deliveryOptions.maximumAttempts ?? DEFAULT_MAXIMUM_ATTEMPTS\n const staleBefore = new Date(now.getTime() - deliveryOptions.leaseDurationMs)\n const claimId = crypto.randomUUID()\n const claimed = await database.transaction().execute(async (transaction) => {\n const candidates = await transaction\n .selectFrom('transactionalEmail')\n .select(['id', 'kind', 'recipientEmailNormalized', 'payloadEncrypted', 'attemptCount'])\n .where('payloadEncrypted', 'is not', null)\n .where((expression) =>\n expression.or([\n expression.and([\n expression('status', '=', 'pending'),\n expression('nextAttemptAt', '<=', now)\n ]),\n expression.and([\n expression('status', '=', 'sending'),\n expression('claimedAt', '<=', staleBefore)\n ])\n ])\n )\n .orderBy('nextAttemptAt')\n .limit(deliveryOptions.batchSize)\n .forUpdate()\n .skipLocked()\n .execute()\n if (candidates.length === 0) return []\n await transaction\n .updateTable('transactionalEmail')\n .set({ status: 'sending', claimId, claimedAt: now, updatedAt: now })\n .where(\n 'id',\n 'in',\n candidates.map((candidate) => candidate.id)\n )\n .execute()\n return candidates.filter(\n (candidate): candidate is ClaimedTransactionalEmail => candidate.payloadEncrypted !== null\n )\n })\n\n const result: TransactionalEmailDeliveryResult = {\n claimed: claimed.length,\n accepted: 0,\n retrying: 0,\n failed: 0,\n suppressed: 0\n }\n for (const message of claimed) {\n const attemptCount = message.attemptCount + 1\n try {\n const content = await decryptTransactionalEmailPayload(\n options.encryptionSecret,\n message.id,\n message.kind,\n message.payloadEncrypted\n )\n const rendered = await renderTransactionalEmail(content)\n const sent = await options.transport.send({\n deliveryId: message.id,\n from: options.from,\n to: message.recipientEmailNormalized,\n subject: rendered.subject,\n html: rendered.html,\n text: rendered.text,\n headers: { 'X-OpenPencil-Delivery-ID': message.id }\n })\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: null,\n status: 'accepted',\n attemptCount,\n transport: options.transport.id,\n transportMessageId: sent.transportMessageId,\n lastErrorCode: null,\n acceptedAt: new Date(sent.acceptedAt),\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n result.accepted++\n } catch (unknownError) {\n const error = transportFailure(unknownError)\n const status = failureStatus(error, attemptCount, maximumAttempts)\n const terminal = status === 'failed' || status === 'suppressed'\n await database\n .updateTable('transactionalEmail')\n .set({\n payloadEncrypted: terminal ? null : message.payloadEncrypted,\n status,\n attemptCount,\n nextAttemptAt: new Date(now.getTime() + retryDelayMilliseconds(attemptCount)),\n transport: options.transport.id,\n lastErrorCode: error.code,\n claimId: null,\n claimedAt: null,\n updatedAt: now\n })\n .where('id', '=', message.id)\n .where('claimId', '=', claimId)\n .execute()\n if (status === 'suppressed') result.suppressed++\n else if (status === 'failed') result.failed++\n else result.retrying++\n }\n }\n return result\n }\n }\n}\n","import type { CloudDatabase } from '#cloud/server/db'\nimport type { DocumentInvitationMessage, InvitationOutbox } from '#cloud/server/invitations'\nimport type { Transaction } from 'kysely'\n\nimport type { TransactionalEmailService } from './types'\n\nexport function createInvitationOutbox(email: TransactionalEmailService): InvitationOutbox {\n return {\n enqueueDocumentInvitation(\n message: DocumentInvitationMessage,\n transaction?: Transaction<CloudDatabase>\n ): Promise<string> {\n return email.enqueue(\n {\n idempotencyKey: `document-invitation/${message.deliveryId}`,\n kind: 'document-invitation',\n recipientEmail: message.recipientEmail,\n payload: {\n inviterName: message.inviterName,\n documentName: message.documentName,\n permission: message.permission,\n expiresAt: message.expiresAt,\n acceptanceURL: message.acceptanceURL\n }\n },\n transaction\n )\n }\n }\n}\n","import { startPeriodicWorker } from '../worker/periodic'\nimport type { TransactionalEmailDeliveryResult, TransactionalEmailService } from './types'\n\nexport type TransactionalEmailWorkerOptions = {\n batchSize: number\n intervalMs: number\n leaseDurationMs: number\n maximumAttempts: number\n signal?: AbortSignal\n onError?: (error: unknown) => void\n}\n\nexport type TransactionalEmailWorker = {\n runOnce(): Promise<TransactionalEmailDeliveryResult>\n stop(): Promise<void>\n}\n\nexport function startTransactionalEmailWorker(\n email: TransactionalEmailService,\n options: TransactionalEmailWorkerOptions\n): TransactionalEmailWorker {\n return startPeriodicWorker({\n intervalMs: options.intervalMs,\n signal: options.signal,\n onError: options.onError,\n run: () =>\n email.deliverPending({\n batchSize: options.batchSize,\n leaseDurationMs: options.leaseDurationMs,\n maximumAttempts: options.maximumAttempts\n })\n })\n}\n","import { createCloudDatabase } from '#cloud/server'\nimport { PostgresDialect } from 'kysely'\nimport { Pool, type PoolConfig } from 'pg'\n\nexport type PostgresCloudDatabaseOptions = {\n connectionString: string\n pool?: Omit<PoolConfig, 'connectionString'>\n}\n\nexport function createPostgresCloudDatabase(options: PostgresCloudDatabaseOptions) {\n return createCloudDatabase({\n dialect: new PostgresDialect({\n pool: new Pool({\n ...options.pool,\n connectionString: options.connectionString\n })\n })\n })\n}\n","import { readFile } from 'node:fs/promises'\n\nimport {\n CloudConfigError,\n parseCloudDeploymentTOML,\n type CloudEnvironment,\n type CloudServerConfig\n} from '#cloud/server'\n\nexport async function loadNodeCloudServerConfig(\n environment: CloudEnvironment\n): Promise<CloudServerConfig> {\n const path = environment.OPENPENCIL_CLOUD_CONFIG\n if (!path) throw new CloudConfigError('OPENPENCIL_CLOUD_CONFIG must name a deployment TOML file')\n return parseCloudDeploymentTOML(await readFile(path, 'utf8'), environment)\n}\n","import { createPostgresCloudDatabase } from '#cloud/runtime/postgres/database'\nimport {\n createBetterAuthAdapter,\n migrateCloudDatabase,\n type CloudServerConfig\n} from '#cloud/server'\n\nimport { loadNodeCloudServerConfig } from './config'\n\n/** The deployment's database, migrated to this version before anything uses it. */\nexport async function migratedNodeCloudDatabase(config: CloudServerConfig) {\n const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })\n const auth = createBetterAuthAdapter(config, database)\n await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })\n return { database, auth }\n}\n\nexport async function createMigratedNodeCloudDatabase(\n environment: Readonly<Record<string, string | undefined>>\n): Promise<{\n config: CloudServerConfig\n database: ReturnType<typeof createPostgresCloudDatabase>\n auth: ReturnType<typeof createBetterAuthAdapter>\n}> {\n const config = await loadNodeCloudServerConfig(environment)\n return { config, ...(await migratedNodeCloudDatabase(config)) }\n}\n","import type { CloudServerConfig } from '#cloud/server'\nimport type { ObjectStore } from '#cloud/server/objects'\nimport {\n AbortMultipartUploadCommand,\n CompleteMultipartUploadCommand,\n CreateMultipartUploadCommand,\n DeleteObjectCommand,\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n S3Client,\n UploadPartCommand\n} from '@aws-sdk/client-s3'\n// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.\nimport { getSignedUrl as getSignedURL } from '@aws-sdk/s3-request-presigner'\n\nconst CHECKSUM_METADATA_KEY = 'openpencil-sha256'\nconst READINESS_BODY = new TextEncoder().encode('openpencil-ready')\nconst READINESS_CHECKSUM = 'Hq6g3mmWpyBNobXoWZIz/d0/d8KLjJyEKqNnJh6KXjA='\nconst MULTIPART_THRESHOLD = 32 * 1024 * 1024\nconst MULTIPART_PART_SIZE = 16 * 1024 * 1024\nconst MAX_MULTIPART_PARTS = 10_000\n\ntype S3ErrorMetadata = {\n $metadata?: {\n httpStatusCode?: number\n }\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n '$metadata' in error &&\n (error as S3ErrorMetadata).$metadata?.httpStatusCode === 404\n )\n}\n\nfunction encryption(config: CloudServerConfig) {\n return config.s3ServerSideEncryption\n ? {\n ServerSideEncryption: config.s3ServerSideEncryption,\n ...(config.s3KmsKeyId ? { SSEKMSKeyId: config.s3KmsKeyId } : {})\n }\n : {}\n}\n\nexport function createS3ObjectStore(config: CloudServerConfig): ObjectStore {\n const client = new S3Client({\n endpoint: config.s3Endpoint,\n region: config.s3Region,\n forcePathStyle: config.s3ForcePathStyle,\n requestChecksumCalculation: 'WHEN_REQUIRED',\n responseChecksumValidation: 'WHEN_REQUIRED',\n credentials: {\n accessKeyId: config.s3AccessKeyId,\n secretAccessKey: config.s3SecretAccessKey,\n ...(config.s3SessionToken ? { sessionToken: config.s3SessionToken } : {})\n }\n })\n const nativeSHA256 = config.s3ChecksumVerification === 'native'\n\n async function headObject(key: string) {\n return client.send(\n new HeadObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n ...(nativeSHA256 ? { ChecksumMode: 'ENABLED' as const } : {})\n })\n )\n }\n\n return {\n capabilities: {\n nativeSHA256,\n multipartUpload: true,\n conditionalWrites: false\n },\n\n async checkReadiness() {\n const key = `.openpencil/readiness/${crypto.randomUUID()}`\n try {\n await client.send(\n new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: key,\n Body: READINESS_BODY,\n ContentType: 'application/octet-stream',\n ChecksumSHA256: nativeSHA256 ? READINESS_CHECKSUM : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: READINESS_CHECKSUM },\n ...encryption(config)\n })\n )\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n return {\n ok: object.ContentLength === READINESS_BODY.byteLength && checksum === READINESS_CHECKSUM,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata'\n }\n } finally {\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n }\n },\n\n async createDownload(input) {\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const url = await getSignedURL(\n client,\n new GetObjectCommand({ Bucket: config.s3Bucket, Key: input.key }),\n { expiresIn }\n )\n return {\n url,\n method: 'GET',\n headers: {},\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async createUpload(input) {\n if (input.byteSize > MULTIPART_THRESHOLD) {\n const created = await client.send(\n new CreateMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n )\n if (!created.UploadId) throw new Error('S3 did not return a multipart upload ID')\n const partCount = Math.ceil(input.byteSize / MULTIPART_PART_SIZE)\n if (partCount > MAX_MULTIPART_PARTS) throw new Error('Object requires too many S3 parts')\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const parts = await Promise.all(\n Array.from({ length: partCount }, async (_, index) => {\n const partNumber = index + 1\n return {\n partNumber,\n url: await getSignedURL(\n client,\n new UploadPartCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: created.UploadId,\n PartNumber: partNumber\n }),\n { expiresIn }\n ),\n method: 'PUT' as const,\n headers: {}\n }\n })\n )\n return {\n kind: 'multipart',\n uploadId: created.UploadId,\n partSize: MULTIPART_PART_SIZE,\n parts,\n expiresAt: input.expiresAt.toISOString()\n }\n }\n const expiresIn = Math.max(1, Math.floor((input.expiresAt.getTime() - Date.now()) / 1000))\n const command = new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n ContentType: input.contentType,\n ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n const url = await getSignedURL(client, command, {\n expiresIn,\n unhoistableHeaders: new Set([\n ...(nativeSHA256 ? ['x-amz-checksum-sha256'] : []),\n `x-amz-meta-${CHECKSUM_METADATA_KEY}`\n ])\n })\n return {\n kind: 'single',\n url,\n method: 'PUT',\n headers: {\n 'Content-Type': input.contentType,\n ...(nativeSHA256 ? { 'x-amz-checksum-sha256': input.checksum } : {}),\n [`x-amz-meta-${CHECKSUM_METADATA_KEY}`]: input.checksum\n },\n expiresAt: input.expiresAt.toISOString()\n }\n },\n\n async completeUpload(input) {\n await client.send(\n new CompleteMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId,\n MultipartUpload: {\n Parts: input.parts.map((part) => ({ ETag: part.etag, PartNumber: part.partNumber }))\n }\n })\n )\n },\n\n async abortUpload(input) {\n try {\n await client.send(\n new AbortMultipartUploadCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n UploadId: input.uploadId\n })\n )\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n },\n\n async head(key) {\n try {\n const object = await headObject(key)\n const checksum = nativeSHA256\n ? object.ChecksumSHA256\n : object.Metadata?.[CHECKSUM_METADATA_KEY]\n if (object.ContentLength == null || !checksum || !object.ContentType) return null\n return {\n byteSize: object.ContentLength,\n checksum,\n checksumVerification: nativeSHA256 ? 'native' : 'metadata',\n contentType: object.ContentType\n }\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n },\n\n async delete(key) {\n await client.send(new DeleteObjectCommand({ Bucket: config.s3Bucket, Key: key }))\n },\n\n async write(input) {\n await client.send(\n new PutObjectCommand({\n Bucket: config.s3Bucket,\n Key: input.key,\n Body: input.bytes,\n ContentType: input.contentType,\n ChecksumSHA256: nativeSHA256 ? input.checksum : undefined,\n Metadata: { [CHECKSUM_METADATA_KEY]: input.checksum },\n ...encryption(config)\n })\n )\n },\n\n async read(key) {\n try {\n const object = await client.send(\n new GetObjectCommand({ Bucket: config.s3Bucket, Key: key })\n )\n return object.Body ? await object.Body.transformToByteArray() : null\n } catch (error) {\n if (isNotFoundError(error)) return null\n throw error\n }\n }\n }\n}\n","import { renderTransactionalEmail } from '#cloud/email'\nimport type { TransactionalEmailTransport } from '#cloud/server/email'\nimport type { DocumentInvitationMessage, InvitationDelivery } from '#cloud/server/invitations'\nimport nodemailer, { type Transporter } from 'nodemailer'\nimport type Mail from 'nodemailer/lib/mailer/index.js'\n\nexport type NodemailerTransporter = {\n sendMail(mail: Mail.Options): Promise<unknown>\n}\n\nexport type NodemailerTransactionalEmailTransportOptions = {\n transporter: NodemailerTransporter\n}\n\nexport function createNodemailerTransactionalEmailTransport(\n options: NodemailerTransactionalEmailTransportOptions\n): TransactionalEmailTransport {\n return {\n id: 'smtp',\n async send(message) {\n const result = (await options.transporter.sendMail({\n from: message.from,\n to: message.to,\n subject: message.subject,\n html: message.html,\n text: message.text,\n headers: message.headers,\n messageId: `<${message.deliveryId}@openpencil.cloud>`\n })) as { messageId?: unknown }\n if (typeof result.messageId !== 'string') {\n throw new TypeError('SMTP transport returned no message ID')\n }\n return {\n transportMessageId: result.messageId,\n acceptedAt: new Date().toISOString()\n }\n }\n }\n}\n\nexport type SMTPTransactionalEmailTransportOptions = {\n host: string\n port: number\n secure: boolean\n user?: string\n password?: string\n}\n\nfunction createSMTPTransporter(options: SMTPTransactionalEmailTransportOptions): Transporter {\n return nodemailer.createTransport({\n host: options.host,\n port: options.port,\n secure: options.secure,\n connectionTimeout: 10_000,\n greetingTimeout: 10_000,\n socketTimeout: 30_000,\n auth:\n options.user && options.password ? { user: options.user, pass: options.password } : undefined\n })\n}\n\nexport function createSMTPTransactionalEmailTransport(\n options: SMTPTransactionalEmailTransportOptions\n): TransactionalEmailTransport {\n return createNodemailerTransactionalEmailTransport({\n transporter: createSMTPTransporter(options)\n })\n}\n\nexport type NodemailerInvitationDeliveryOptions = NodemailerTransactionalEmailTransportOptions & {\n from: string\n}\n\nexport function createNodemailerInvitationDelivery(\n options: NodemailerInvitationDeliveryOptions\n): InvitationDelivery {\n const transport = createNodemailerTransactionalEmailTransport(options)\n return {\n async sendDocumentInvitation(message: DocumentInvitationMessage): Promise<void> {\n const rendered = await renderTransactionalEmail({\n kind: 'document-invitation',\n payload: {\n inviterName: message.inviterName,\n documentName: message.documentName,\n permission: message.permission,\n expiresAt: message.expiresAt,\n acceptanceURL: message.acceptanceURL\n }\n })\n await transport.send({\n deliveryId: message.deliveryId,\n from: options.from,\n to: message.recipientEmail,\n ...rendered,\n headers: { 'X-OpenPencil-Delivery-ID': message.deliveryId }\n })\n }\n }\n}\n\nexport type SMTPInvitationDeliveryOptions = SMTPTransactionalEmailTransportOptions & {\n from: string\n}\n\nexport function createSMTPInvitationDelivery(\n options: SMTPInvitationDeliveryOptions\n): InvitationDelivery {\n return createNodemailerInvitationDelivery({\n transporter: createSMTPTransporter(options),\n from: options.from\n })\n}\n","import {\n createInvitationOutbox,\n createTransactionalEmailService,\n type CloudServerConfig,\n type TransactionalEmailService,\n type TransactionalEmailTransport\n} from '#cloud/server'\nimport type { CloudDatabase } from '#cloud/server/db'\nimport type { Kysely } from 'kysely'\n\nimport { createSMTPTransactionalEmailTransport } from './transport'\n\nexport type NodeTransactionalEmailRuntime = {\n email: TransactionalEmailService\n transport?: TransactionalEmailTransport\n invitationOutbox?: ReturnType<typeof createInvitationOutbox>\n}\n\nexport function createNodeTransactionalEmailRuntime(\n config: CloudServerConfig,\n database: Kysely<CloudDatabase>\n): NodeTransactionalEmailRuntime {\n const transport =\n config.emailTransport === 'smtp' && config.smtpHost && config.smtpPort\n ? createSMTPTransactionalEmailTransport({\n host: config.smtpHost,\n port: config.smtpPort,\n secure: config.smtpSecure ?? config.smtpPort === 465,\n user: config.smtpUser,\n password: config.smtpPassword\n })\n : undefined\n const email = createTransactionalEmailService(database, {\n encryptionSecret: config.authSecret,\n from: config.emailFrom ?? '',\n transport\n })\n return {\n email,\n transport,\n invitationOutbox: transport ? createInvitationOutbox(email) : undefined\n }\n}\n","import type { IncomingMessage, Server } from 'node:http'\nimport type { Duplex } from 'node:stream'\n\nimport { RELAY_PATH } from '#cloud/contract'\nimport type { CollaborationRelay } from '#cloud/server'\nimport { WebSocketServer, type RawData } from 'ws'\n\nfunction bytes(data: RawData): Uint8Array {\n if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data))\n return data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data)\n}\n\n/**\n * Accepts WebSocket upgrades on the relay path of an HTTP server and hands each socket to the\n * relay. Other upgrade requests are refused.\n */\nexport function attachCollaborationRelay(\n server: Pick<Server, 'on' | 'off'>,\n relay: CollaborationRelay,\n maximumMessageBytes: number\n) {\n // ws enforces the limit before buffering; the relay checks again for other runtimes.\n const sockets = new WebSocketServer({ noServer: true, maxPayload: maximumMessageBytes })\n\n function upgrade(request: IncomingMessage, socket: Duplex, head: Buffer) {\n const path = new URL(request.url ?? '/', 'http://relay').pathname\n if (path !== RELAY_PATH) {\n socket.destroy()\n return\n }\n sockets.handleUpgrade(request, socket, head, (webSocket) => {\n webSocket.binaryType = 'nodebuffer'\n const connection = relay.connect({\n send: (data) => webSocket.send(data),\n close: (code, reason) => webSocket.close(code, reason)\n })\n webSocket.on('message', (data) => connection.receive(bytes(data)))\n webSocket.on('close', () => connection.closed())\n webSocket.on('error', () => webSocket.terminate())\n })\n }\n\n server.on('upgrade', upgrade)\n return {\n async close() {\n server.off('upgrade', upgrade)\n await relay.close()\n for (const client of sockets.clients) client.terminate()\n await new Promise<void>((resolve) => {\n sockets.close(() => resolve())\n })\n }\n }\n}\n","import type { CloudServerConfig } from '#cloud/server'\nimport type { CloudErrorReporter } from '#cloud/server/errors'\nimport { PostHog, type PostHogOptions } from 'posthog-node'\n\n/** Which runtime serves the deployment, as its error reports name it. */\nexport type CloudRuntimeName = 'node' | 'cloudflare'\n\n/**\n * Reports server errors to the PostHog project the deployment's `[error_tracking]` names, or\n * returns nothing when it names none. Each error is sent as it is caught, as a `$exception` with\n * no person profile: reports carry the runtime, the deployment, and where the error was caught,\n * never who made the request or what it carried.\n */\nexport function createPostHogErrorReporter(\n config: CloudServerConfig,\n runtime: CloudRuntimeName,\n options: Pick<PostHogOptions, 'fetch'> = {}\n): CloudErrorReporter | undefined {\n const tracking = config.errorTracking\n if (!tracking) return undefined\n const client = new PostHog(tracking.projectAPIKey, {\n host: tracking.host,\n disableGeoip: true,\n ...options\n })\n // The SDK resolves a capture that PostHog refused and emits the refusal instead.\n client.on('error', (failure: unknown) => {\n console.error('[Cloud] PostHog refused an error report:', failure)\n })\n const deployment = {\n cloud_runtime: runtime,\n cloud_deployment: config.deployment,\n cloud_host: new URL(config.publicURL).host\n }\n return async (error, context) => {\n try {\n // Undefined request fields are left out of the event's JSON.\n await client.captureExceptionImmediate(error, undefined, {\n ...deployment,\n cloud_source: context.source,\n http_method: context.method,\n http_route: context.route\n })\n } catch (failure) {\n console.error('[Cloud] Reporting an error failed:', failure)\n }\n }\n}\n","import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'\nimport { cloudErrorHandler, withIndexingPolicy, type CloudErrorReporter } from '#cloud/server'\nimport { Hono } from 'hono'\n\n/** A file of the Cloud site (`bun run build:cloud`): the editor and the portal. */\nexport type SiteFile = {\n body: ReadableStream | Uint8Array<ArrayBuffer>\n type: string\n /** Overrides the cache policy built files get, for a site whose files change in place. */\n cacheControl?: string\n}\n\n/** Reads the built site's file at a URL path, or null when there is none. */\nexport type SiteFiles = (path: string, request: Request) => Promise<SiteFile | null>\n\nconst PORTAL_PAGE = '/cloud.html'\nconst EDITOR_PAGE = '/index.html'\n\nconst PAGE_HEADERS = {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Cache-Control': 'no-cache',\n // Desktop sign-in approval and the editor must never be framed by another site.\n 'Content-Security-Policy': \"frame-ancestors 'none'\",\n 'Referrer-Policy': 'no-referrer',\n 'X-Content-Type-Options': 'nosniff'\n}\n\nexport type CloudServerOptions = {\n /** The built site; without it, the server answers only its API. */\n site?: SiteFiles\n indexingPolicy: 'allow' | 'deny'\n /** Reports errors reading the site's files, when the deployment configures error tracking. */\n reportError?: CloudErrorReporter\n}\n\nfunction cacheControl(path: string): string {\n if (path.startsWith('/assets/')) return 'public, max-age=31536000, immutable'\n return 'public, max-age=3600'\n}\n\n/**\n * A Cloud server as every runtime serves it: the portal's `cloud.html` at portal pages, the API\n * everywhere else, and, where the API has nothing, the site's files, or the editor's\n * `index.html` for any other page, whose router knows the editor's own addresses.\n */\nexport function createCloudServer(\n api: { fetch(request: Request): Response | Promise<Response> },\n { site, indexingPolicy, reportError }: CloudServerOptions\n) {\n const server = new Hono().onError(cloudErrorHandler(reportError))\n server.use(async (c, next) => {\n await next()\n c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)\n })\n if (site) {\n const pages = CLOUD_PORTAL_PAGE_ROOTS.flatMap((root) => [root, `${root}/*`])\n server.on(['GET', 'HEAD'], pages, async (c) => {\n const page = await site(PORTAL_PAGE, c.req.raw)\n return page ? c.body(page.body, 200, PAGE_HEADERS) : c.notFound()\n })\n server.on(['GET', 'HEAD'], '*', async (c, next) => {\n await next()\n if (c.res.status !== 404) return\n const file = await site(c.req.path, c.req.raw)\n if (file) {\n c.res = file.type.startsWith('text/html')\n ? new Response(file.body, { headers: PAGE_HEADERS })\n : new Response(file.body, {\n headers: {\n 'Content-Type': file.type,\n 'Cache-Control': file.cacheControl ?? cacheControl(c.req.path),\n 'X-Content-Type-Options': 'nosniff'\n }\n })\n return\n }\n if (!c.req.header('Accept')?.includes('text/html')) return\n const editor = await site(EDITOR_PAGE, c.req.raw)\n if (editor) c.res = new Response(editor.body, { headers: PAGE_HEADERS })\n })\n }\n server.all('*', (c) => api.fetch(c.req.raw))\n return server\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve, sep } from 'node:path'\n\nimport type { SiteFiles } from '#cloud/runtime/site/server'\nimport { getMimeType } from 'hono/utils/mime'\n\n/**\n * The only request headers Vite reads to pick a reply: which module, style, or page form to send.\n * Others stay behind, such as credentials, ranges, and validators that would get a partial or 304.\n */\nconst FORWARDED_HEADERS = ['accept', 'sec-fetch-dest']\n\n/** The built site's files in `directory`, never anything outside it. */\nexport function nodeSiteFiles(directory: string): SiteFiles {\n const root = resolve(directory)\n return async (path) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(path)\n } catch {\n return null\n }\n const file = resolve(root, `.${decoded}`)\n if (!file.startsWith(`${root}${sep}`)) return null\n try {\n return {\n body: new Uint8Array(await readFile(file)),\n // Documents such as the editor's demo `.fig` have no registered type.\n type: getMimeType(decoded) ?? 'application/octet-stream'\n }\n } catch {\n return null\n }\n }\n}\n\n/**\n * The site as the Vite development server at `origin` serves it, for `bun run cloud:dev`: pages,\n * modules, and styles come from source as they are now, so an edit shows without a build.\n */\nexport function developmentSiteFiles(origin: string): SiteFiles {\n return async (path, request) => {\n const url = new URL(path, origin)\n const requested = new URL(request.url)\n // Vite tells module requests apart by their query, such as `?import` or `?t=`.\n if (requested.pathname === path) url.search = requested.search\n const headers = new Headers()\n for (const name of FORWARDED_HEADERS) {\n const value = request.headers.get(name)\n if (value !== null) headers.set(name, value)\n }\n try {\n const response = await fetch(url, { headers })\n if (!response.ok || !response.body) return null\n return {\n body: response.body,\n type: response.headers.get('Content-Type') ?? 'application/octet-stream',\n cacheControl: 'no-cache'\n }\n } catch {\n return null\n }\n }\n}\n","import { defaultRelayURL } from '#cloud/contract'\nimport { createPostHogErrorReporter } from '#cloud/runtime/posthog/errors'\nimport { createS3ObjectStore } from '#cloud/runtime/s3/objects'\nimport { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'\nimport {\n createCloudApp,\n loadAISigningKey,\n createCloudAuthenticationRuntime,\n createCollaborationRelay,\n createCollaborationStateStore,\n cleanupPassOptions,\n createCleanupServices,\n createConfiguredCloudPolicy,\n relayDocumentLookups,\n reportCloudError,\n startCleanupWorker,\n startTransactionalEmailWorker,\n type CloudErrorReporter,\n type CloudServerConfig\n} from '#cloud/server'\n\nimport { migratedNodeCloudDatabase } from './bootstrap'\nimport { loadNodeCloudServerConfig } from './config'\nimport { createNodeTransactionalEmailRuntime } from './email/runtime'\nimport { listen } from './listen'\nimport { attachCollaborationRelay } from './relay'\nimport { developmentSiteFiles, nodeSiteFiles } from './site'\n\nexport type NodeCloudServerOptions = {\n environment?: Readonly<Record<string, string | undefined>>\n port?: number\n}\n\n/** The site the server serves: a build, or in `cloud:dev` a development server's source. */\nfunction siteFiles(\n environment: Readonly<Record<string, string | undefined>>\n): SiteFiles | undefined {\n const developmentSite = environment.OPENPENCIL_CLOUD_DEV_SITE_URL\n if (developmentSite) return developmentSiteFiles(developmentSite)\n const siteDirectory = environment.OPENPENCIL_CLOUD_SITE_DIR\n if (siteDirectory) return nodeSiteFiles(siteDirectory)\n console.warn(\n '[Cloud] OPENPENCIL_CLOUD_SITE_DIR is not set; the editor and sign-in pages are off.'\n )\n return undefined\n}\n\n/**\n * Starts the server. Once the config parses, a startup that fails, such as a migration, a signing\n * key, or a port that cannot be bound, is reported before it is thrown; a config that does not\n * parse has no error tracking to report to.\n */\nexport async function startNodeCloudServer(options: NodeCloudServerOptions = {}) {\n const environment = options.environment ?? process.env\n const config = await loadNodeCloudServerConfig(environment)\n const reportError = createPostHogErrorReporter(config, 'node')\n try {\n return await startConfiguredServer(config, environment, options, reportError)\n } catch (error) {\n await reportCloudError(reportError, 'Starting the server failed:', error, { source: 'setup' })\n throw error\n }\n}\n\nasync function startConfiguredServer(\n config: CloudServerConfig,\n environment: Readonly<Record<string, string | undefined>>,\n options: NodeCloudServerOptions,\n reportError: CloudErrorReporter | undefined\n) {\n const { database } = await migratedNodeCloudDatabase(config)\n // Before any worker starts, so a key that cannot sign leaves nothing running.\n const aiSigningKey = await loadAISigningKey(config).catch(async (error: unknown) => {\n await database.destroy()\n throw error\n })\n const objects = createS3ObjectStore(config)\n const {\n email,\n invitationOutbox,\n transport: emailTransport\n } = createNodeTransactionalEmailRuntime(config, database)\n const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)\n const policy = createConfiguredCloudPolicy(config, database)\n const cleanup = config.cleanupEnabled\n ? startCleanupWorker(createCleanupServices(config, database, objects, policy), {\n ...cleanupPassOptions(config),\n intervalMs: config.cleanupIntervalMs,\n onError: (error) =>\n void reportCloudError(reportError, 'Cleanup worker failed:', error, { source: 'cleanup' })\n })\n : undefined\n const relay = createCollaborationRelay({\n authSecret: config.authSecret,\n store: createCollaborationStateStore(database, objects),\n maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,\n maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,\n onError: (message, error) =>\n void reportCloudError(reportError, message, error, { source: 'relay' }),\n ...relayDocumentLookups(database, policy, config.deployment)\n })\n const app = createCloudApp({\n config,\n database,\n auth,\n objects,\n invitationOutbox,\n transactionalEmail: email,\n enrollment,\n aiSigningKey,\n relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),\n onDocumentRestored: (documentId) => relay.startOver(documentId),\n onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId),\n reportError\n })\n const emailWorker = emailTransport\n ? startTransactionalEmailWorker(email, {\n batchSize: config.emailBatchSize,\n intervalMs: config.emailIntervalMs,\n leaseDurationMs: config.emailLeaseDurationMs,\n maximumAttempts: config.emailMaximumAttempts,\n onError: (error) =>\n void reportCloudError(reportError, 'Email worker failed:', error, { source: 'email' })\n })\n : undefined\n const cloudServer = createCloudServer(app, {\n site: siteFiles(environment),\n indexingPolicy: config.indexingPolicy,\n reportError\n })\n const server = await listen(\n async (request) => cloudServer.fetch(request),\n options.port ?? Number(environment.PORT ?? 8787),\n environment.HOST ?? '0.0.0.0'\n )\n const relayListener = attachCollaborationRelay(\n server.http,\n relay,\n config.technicalLimits.maximumCollaborationMessageBytes\n )\n return {\n app,\n database,\n url: server.url,\n async stop() {\n await relayListener.close()\n await server.close()\n await cleanup?.stop()\n await emailWorker?.stop()\n await database.destroy()\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAa,0BAA0B,EAAE,SAAS;CAAC;CAAU;CAAW;CAAY;AAAS,CAAC;AAC9F,MAAa,sBAAsB,EAAE,OAAO;CAC1C,QAAQ,EAAE,OAAO;CACjB,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,MAAM,CAAC;CACnC,MAAM,EAAE,OAAO;;CAEf,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;CACxC,gBAAgB,EAAE,SAAS,EAAE,SAAS,CAAC,QAAQ,OAAO,CAAC,CAAC;AAC1D,CAAC;AAE+C,EAAE,OAAO;CACvD,MAAM;CACN,OAAO;AACT,CAAC;AAED,MAAa,oCAAoC,EAAE,SAAS;CAAC;CAAc;CAAU;AAAO,CAAC;AAC7F,MAAa,kCAAkC,EAAE,OAAO;CACtD,IAAI,EAAE,OAAO;CACb,UAAU;CACV,WAAW,EAAE,OAAO;CACpB,WAAW,EAAE,QAAQ;AACvB,CAAC;AACuD,EAAE,OAAO;CAC/D,SAAS,EAAE,MAAM,+BAA+B;CAChD,0BAA0B,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