@pairdraw/cloud 0.0.0-stage → 0.16.0

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 (286) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +7 -0
  4. package/README.md +37 -2
  5. package/dist/bin/ai-relay.d.mts +1 -0
  6. package/dist/bin/ai-relay.mjs +31 -0
  7. package/dist/bin/ai-relay.mjs.map +1 -0
  8. package/dist/bin/server.d.mts +1 -0
  9. package/dist/bin/server.mjs +29 -0
  10. package/dist/bin/server.mjs.map +1 -0
  11. package/dist/client.d.ts +1578 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +2008 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/contract.d.ts +2 -0
  16. package/dist/contract.js +2 -0
  17. package/dist/contract2.js +1673 -0
  18. package/dist/contract2.js.map +1 -0
  19. package/dist/email.d.ts +155 -0
  20. package/dist/email.d.ts.map +1 -0
  21. package/dist/email.js +700 -0
  22. package/dist/email.js.map +1 -0
  23. package/dist/index.d.ts +1945 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/listen.mjs +1905 -0
  26. package/dist/listen.mjs.map +1 -0
  27. package/dist/runtime-node.d.mts +10715 -0
  28. package/dist/runtime-node.d.mts.map +1 -0
  29. package/dist/runtime-node.mjs +32 -0
  30. package/dist/runtime-node.mjs.map +1 -0
  31. package/dist/server.d.ts +13772 -0
  32. package/dist/server.d.ts.map +1 -0
  33. package/dist/server.js +8856 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/server.mjs +8836 -0
  36. package/dist/server.mjs.map +1 -0
  37. package/dist/server2.mjs +505 -0
  38. package/dist/server2.mjs.map +1 -0
  39. package/package.json +120 -4
  40. package/src/admin/api/routes.ts +223 -0
  41. package/src/admin/api/security.ts +12 -0
  42. package/src/admin/audit/service.ts +138 -0
  43. package/src/admin/email/service.ts +140 -0
  44. package/src/admin/enrollment/email.ts +77 -0
  45. package/src/admin/enrollment/service.ts +308 -0
  46. package/src/admin/errors.ts +20 -0
  47. package/src/admin/index.ts +19 -0
  48. package/src/admin/list.ts +61 -0
  49. package/src/admin/operations/service.ts +70 -0
  50. package/src/admin/schema.ts +26 -0
  51. package/src/admin/users/service.ts +369 -0
  52. package/src/ai-relay/app.ts +251 -0
  53. package/src/ai-relay/config.ts +120 -0
  54. package/src/ai-relay/db/index.ts +10 -0
  55. package/src/ai-relay/db/migrate.ts +32 -0
  56. package/src/ai-relay/db/migrations/001_usage.ts +26 -0
  57. package/src/ai-relay/db/schema.ts +20 -0
  58. package/src/ai-relay/index.ts +18 -0
  59. package/src/ai-relay/metering.ts +68 -0
  60. package/src/ai-relay/usage.ts +115 -0
  61. package/src/client/ai.ts +96 -0
  62. package/src/client/api.ts +530 -0
  63. package/src/client/auth/client.ts +188 -0
  64. package/src/client/auth/failure.ts +54 -0
  65. package/src/client/auth/navigation.ts +45 -0
  66. package/src/client/device-authorization.ts +134 -0
  67. package/src/client/discovery.ts +105 -0
  68. package/src/client/images.ts +81 -0
  69. package/src/client/index.ts +53 -0
  70. package/src/client/portal/account.ts +183 -0
  71. package/src/client/portal/administration.ts +130 -0
  72. package/src/client/portal/client.ts +18 -0
  73. package/src/client/portal/request.ts +115 -0
  74. package/src/client/profiles.ts +79 -0
  75. package/src/client/response.ts +51 -0
  76. package/src/client/workspaces.ts +142 -0
  77. package/src/contract/account.ts +204 -0
  78. package/src/contract/admin/index.ts +187 -0
  79. package/src/contract/ai.ts +150 -0
  80. package/src/contract/collaboration.ts +45 -0
  81. package/src/contract/comments.ts +149 -0
  82. package/src/contract/discovery.ts +81 -0
  83. package/src/contract/documents.ts +263 -0
  84. package/src/contract/entitlements.ts +28 -0
  85. package/src/contract/index.ts +210 -0
  86. package/src/contract/links.ts +108 -0
  87. package/src/contract/portal.ts +11 -0
  88. package/src/contract/profiles.ts +88 -0
  89. package/src/contract/relay.ts +370 -0
  90. package/src/contract/sharing.ts +215 -0
  91. package/src/contract/versions.ts +87 -0
  92. package/src/contract/workspaces.ts +100 -0
  93. package/src/email/index.ts +13 -0
  94. package/src/email/render.ts +304 -0
  95. package/src/email/schema.ts +144 -0
  96. package/src/email/templates/brand.ts +125 -0
  97. package/src/email/templates/document-invitation.ts +39 -0
  98. package/src/email/templates/enrollment.ts +30 -0
  99. package/src/email/templates/layout.ts +20 -0
  100. package/src/runtime/cloudflare/email.ts +70 -0
  101. package/src/runtime/cloudflare/environment.ts +57 -0
  102. package/src/runtime/cloudflare/index.ts +3 -0
  103. package/src/runtime/cloudflare/relay.ts +136 -0
  104. package/src/runtime/cloudflare/site.ts +13 -0
  105. package/src/runtime/cloudflare/tsconfig.json +21 -0
  106. package/src/runtime/cloudflare/worker.ts +161 -0
  107. package/src/runtime/node/admin.ts +59 -0
  108. package/src/runtime/node/ai-relay/main.ts +35 -0
  109. package/src/runtime/node/ai-relay/server.ts +63 -0
  110. package/src/runtime/node/application.ts +50 -0
  111. package/src/runtime/node/bootstrap.ts +22 -0
  112. package/src/runtime/node/cleanup.ts +24 -0
  113. package/src/runtime/node/command.ts +17 -0
  114. package/src/runtime/node/config.ts +16 -0
  115. package/src/runtime/node/email/runtime.ts +44 -0
  116. package/src/runtime/node/email/transport.ts +112 -0
  117. package/src/runtime/node/entitlements/main.ts +41 -0
  118. package/src/runtime/node/entitlements/refusal.ts +15 -0
  119. package/src/runtime/node/index.ts +25 -0
  120. package/src/runtime/node/listen.ts +35 -0
  121. package/src/runtime/node/main.ts +29 -0
  122. package/src/runtime/node/migrate.ts +13 -0
  123. package/src/runtime/node/quota-reconcile.ts +9 -0
  124. package/src/runtime/node/relay.ts +54 -0
  125. package/src/runtime/node/server.ts +119 -0
  126. package/src/runtime/node/site.ts +64 -0
  127. package/src/runtime/postgres/database.ts +19 -0
  128. package/src/runtime/s3/objects.ts +244 -0
  129. package/src/runtime/site/server.ts +82 -0
  130. package/src/server/account/actions.ts +66 -0
  131. package/src/server/account/routes.ts +300 -0
  132. package/src/server/ai/errors.ts +7 -0
  133. package/src/server/ai/index.ts +4 -0
  134. package/src/server/ai/keys.ts +43 -0
  135. package/src/server/ai/routes.ts +43 -0
  136. package/src/server/ai/service.ts +70 -0
  137. package/src/server/api/index.ts +8 -0
  138. package/src/server/api/router.ts +129 -0
  139. package/src/server/api/types.ts +7 -0
  140. package/src/server/app.ts +385 -0
  141. package/src/server/auth/account.ts +73 -0
  142. package/src/server/auth/activity.ts +213 -0
  143. package/src/server/auth/adapter.ts +79 -0
  144. package/src/server/auth/email.ts +125 -0
  145. package/src/server/auth/endpoints.ts +57 -0
  146. package/src/server/auth/factory.ts +583 -0
  147. package/src/server/auth/index.ts +17 -0
  148. package/src/server/auth/mfa-assurance.ts +55 -0
  149. package/src/server/auth/runtime.ts +26 -0
  150. package/src/server/auth/session.ts +19 -0
  151. package/src/server/auth/social-providers.ts +55 -0
  152. package/src/server/auth/user-agent.ts +16 -0
  153. package/src/server/auth/workspace-access.ts +23 -0
  154. package/src/server/cleanup/configured.ts +38 -0
  155. package/src/server/cleanup/documents.ts +231 -0
  156. package/src/server/cleanup/index.ts +29 -0
  157. package/src/server/cleanup/objects.ts +27 -0
  158. package/src/server/cleanup/revisions.ts +246 -0
  159. package/src/server/cleanup/uploads.ts +129 -0
  160. package/src/server/cleanup/worker.ts +79 -0
  161. package/src/server/collaboration/index.ts +28 -0
  162. package/src/server/collaboration/relay/authorize.ts +54 -0
  163. package/src/server/collaboration/relay/awareness.ts +104 -0
  164. package/src/server/collaboration/relay/comments.ts +86 -0
  165. package/src/server/collaboration/relay/documents.ts +39 -0
  166. package/src/server/collaboration/relay/hub.ts +567 -0
  167. package/src/server/collaboration/relay/index.ts +15 -0
  168. package/src/server/collaboration/relay/persistence.ts +48 -0
  169. package/src/server/collaboration/routes.ts +77 -0
  170. package/src/server/collaboration/service.ts +190 -0
  171. package/src/server/config/deployment.ts +178 -0
  172. package/src/server/config/index.ts +20 -0
  173. package/src/server/config/limits.ts +8 -0
  174. package/src/server/config/public.ts +66 -0
  175. package/src/server/config/schema.ts +512 -0
  176. package/src/server/db/database.ts +15 -0
  177. package/src/server/db/expressions.ts +13 -0
  178. package/src/server/db/index.ts +21 -0
  179. package/src/server/db/migrate.ts +177 -0
  180. package/src/server/db/migrations/001_foundation.ts +164 -0
  181. package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
  182. package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
  183. package/src/server/db/migrations/004_document_sharing.ts +82 -0
  184. package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
  185. package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
  186. package/src/server/db/migrations/007_collaboration_state.ts +25 -0
  187. package/src/server/db/migrations/008_storage_reservations.ts +37 -0
  188. package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
  189. package/src/server/db/migrations/010_upload_finalization.ts +22 -0
  190. package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
  191. package/src/server/db/migrations/012_transactional_email.ts +48 -0
  192. package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
  193. package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
  194. package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
  195. package/src/server/db/migrations/016_auth_schema.ts +16 -0
  196. package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
  197. package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
  198. package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
  199. package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
  200. package/src/server/db/migrations/021_document_versions.ts +66 -0
  201. package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
  202. package/src/server/db/migrations/023_document_images.ts +61 -0
  203. package/src/server/db/migrations/024_account_activity.ts +66 -0
  204. package/src/server/db/migrations/025_table_names.ts +58 -0
  205. package/src/server/db/migrations/026_user_picture.ts +30 -0
  206. package/src/server/db/migrations/027_sharing_comments_snapshots_profiles.ts +74 -0
  207. package/src/server/db/migrations/helpers.ts +78 -0
  208. package/src/server/db/tables.ts +399 -0
  209. package/src/server/documents/access.ts +103 -0
  210. package/src/server/documents/errors.ts +16 -0
  211. package/src/server/documents/images.ts +405 -0
  212. package/src/server/documents/index.ts +14 -0
  213. package/src/server/documents/limits.ts +57 -0
  214. package/src/server/documents/repository.ts +131 -0
  215. package/src/server/documents/routes.ts +239 -0
  216. package/src/server/documents/service.ts +607 -0
  217. package/src/server/documents/summary.ts +36 -0
  218. package/src/server/documents/types.ts +13 -0
  219. package/src/server/documents/versions/checkpoint.ts +98 -0
  220. package/src/server/documents/versions/history.ts +25 -0
  221. package/src/server/documents/versions/index.ts +4 -0
  222. package/src/server/documents/versions/routes.ts +112 -0
  223. package/src/server/documents/versions/service.ts +396 -0
  224. package/src/server/email/crypto.ts +57 -0
  225. package/src/server/email/index.ts +18 -0
  226. package/src/server/email/invitations.ts +30 -0
  227. package/src/server/email/service.ts +247 -0
  228. package/src/server/email/types.ts +56 -0
  229. package/src/server/email/worker.ts +33 -0
  230. package/src/server/index.ts +288 -0
  231. package/src/server/internal/index.ts +8 -0
  232. package/src/server/internal/routes.ts +41 -0
  233. package/src/server/internal/schema.ts +10 -0
  234. package/src/server/internal/service.ts +44 -0
  235. package/src/server/invitations/index.ts +6 -0
  236. package/src/server/invitations/types.ts +30 -0
  237. package/src/server/objects/index.ts +16 -0
  238. package/src/server/objects/types.ts +81 -0
  239. package/src/server/pictures/index.ts +9 -0
  240. package/src/server/pictures/provider.ts +61 -0
  241. package/src/server/pictures/routes.ts +21 -0
  242. package/src/server/pictures/service.ts +235 -0
  243. package/src/server/policy/configured.ts +23 -0
  244. package/src/server/policy/database.ts +108 -0
  245. package/src/server/policy/entitlements.ts +29 -0
  246. package/src/server/policy/index.ts +17 -0
  247. package/src/server/policy/keys.ts +23 -0
  248. package/src/server/policy/policy.ts +117 -0
  249. package/src/server/policy/provider.ts +67 -0
  250. package/src/server/policy/schema.ts +69 -0
  251. package/src/server/policy/service.ts +85 -0
  252. package/src/server/policy/static.ts +62 -0
  253. package/src/server/profiles/index.ts +12 -0
  254. package/src/server/profiles/routes.ts +103 -0
  255. package/src/server/profiles/service.ts +266 -0
  256. package/src/server/quota/index.ts +7 -0
  257. package/src/server/quota/reconcile.ts +61 -0
  258. package/src/server/quota/storage.ts +165 -0
  259. package/src/server/rate-limit/cleanup.ts +16 -0
  260. package/src/server/rate-limit/index.ts +12 -0
  261. package/src/server/rate-limit/keys.ts +38 -0
  262. package/src/server/rate-limit/middleware.ts +137 -0
  263. package/src/server/rate-limit/postgres.ts +79 -0
  264. package/src/server/sharing/access.ts +29 -0
  265. package/src/server/sharing/actor.ts +12 -0
  266. package/src/server/sharing/capabilities/service.ts +318 -0
  267. package/src/server/sharing/continuation.ts +83 -0
  268. package/src/server/sharing/contracts.ts +82 -0
  269. package/src/server/sharing/crypto.ts +48 -0
  270. package/src/server/sharing/document-routes.ts +41 -0
  271. package/src/server/sharing/errors.ts +20 -0
  272. package/src/server/sharing/grants/service.ts +79 -0
  273. package/src/server/sharing/http.ts +45 -0
  274. package/src/server/sharing/index.ts +40 -0
  275. package/src/server/sharing/invitations/service.ts +315 -0
  276. package/src/server/sharing/policy.ts +42 -0
  277. package/src/server/sharing/routes.ts +251 -0
  278. package/src/server/sharing/service.ts +117 -0
  279. package/src/server/validation.ts +24 -0
  280. package/src/server/worker/interval.ts +23 -0
  281. package/src/server/worker/periodic.ts +42 -0
  282. package/src/server/workspaces/index.ts +16 -0
  283. package/src/server/workspaces/members.ts +502 -0
  284. package/src/server/workspaces/repository.ts +91 -0
  285. package/src/server/workspaces/routes.ts +198 -0
  286. package/src/server/workspaces/service.ts +84 -0
@@ -0,0 +1,103 @@
1
+ import {
2
+ isPublicProfileHandle,
3
+ parsePublishWorkspace,
4
+ parseUpdatePublicProfile
5
+ } from '#cloud/contract'
6
+ import type { CloudActor } from '#cloud/server/auth'
7
+ import type { DocumentService } from '#cloud/server/documents'
8
+ import { DocumentNotFoundError } from '#cloud/server/documents/errors'
9
+ import { validatedJSON } from '#cloud/server/validation'
10
+ import { Hono, type Context } from 'hono'
11
+
12
+ import {
13
+ PublicProfileForbiddenError,
14
+ PublicProfileHandleTakenError,
15
+ type PublicProfileService
16
+ } from './service'
17
+
18
+ export type PublicProfileRouteEnvironment = {
19
+ Variables: { actor: CloudActor }
20
+ }
21
+
22
+ /** Runs a profile action, answering its domain errors with their HTTP codes. */
23
+ async function profileRoute<T>(context: Context, action: () => Promise<T>): Promise<T | Response> {
24
+ try {
25
+ return await action()
26
+ } catch (error) {
27
+ if (error instanceof DocumentNotFoundError) {
28
+ return context.json({ error: { code: 'not_found' as const } }, 404)
29
+ }
30
+ if (error instanceof PublicProfileForbiddenError) {
31
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
32
+ }
33
+ if (error instanceof PublicProfileHandleTakenError) {
34
+ return context.json({ error: { code: 'handle_taken' as const } }, 409)
35
+ }
36
+ throw error
37
+ }
38
+ }
39
+
40
+ /** The service, or a 404 answer where the deployment serves no public profiles. */
41
+ function required(service: PublicProfileService | undefined): PublicProfileService {
42
+ if (!service) throw new DocumentNotFoundError()
43
+ return service
44
+ }
45
+
46
+ /**
47
+ * The signed-in person's own public profile and which of their workspaces it lists. Without a
48
+ * service every route answers 404.
49
+ */
50
+ export function createPublicProfileSettingsRoutes(service?: PublicProfileService) {
51
+ return new Hono<PublicProfileRouteEnvironment>()
52
+ .get('/profile', (context) =>
53
+ profileRoute(context, async () =>
54
+ context.json({ profile: await required(service).settings(context.get('actor').userId) })
55
+ )
56
+ )
57
+ .put('/profile', validatedJSON(parseUpdatePublicProfile), (context) =>
58
+ profileRoute(context, async () =>
59
+ context.json({
60
+ profile: await required(service).update(
61
+ context.get('actor').userId,
62
+ context.req.valid('json')
63
+ )
64
+ })
65
+ )
66
+ )
67
+ .put('/workspaces/:workspaceId/public', validatedJSON(parsePublishWorkspace), (context) =>
68
+ profileRoute(context, async () =>
69
+ context.json({
70
+ profile: await required(service).publishWorkspace(
71
+ context.get('actor').userId,
72
+ context.req.param('workspaceId'),
73
+ context.req.valid('json').public
74
+ )
75
+ })
76
+ )
77
+ )
78
+ }
79
+
80
+ /** What anyone may read without signing in: profiles and the documents they list. */
81
+ export function createPublicProfileRoutes(
82
+ service: PublicProfileService | undefined,
83
+ documents: DocumentService
84
+ ) {
85
+ return new Hono()
86
+ .get('/profiles/:handle', (context) =>
87
+ profileRoute(context, async () => {
88
+ const handle = context.req.param('handle').toLowerCase()
89
+ const profile = isPublicProfileHandle(handle)
90
+ ? await required(service).publicProfile(handle)
91
+ : null
92
+ if (!profile) throw new DocumentNotFoundError()
93
+ return context.json({ profile })
94
+ })
95
+ )
96
+ .post('/documents/:documentId/document', (context) =>
97
+ profileRoute(context, async () => {
98
+ const documentId = context.req.param('documentId')
99
+ await required(service).requirePublicDocument(documentId)
100
+ return context.json({ document: await documents.downloadShared(documentId) })
101
+ })
102
+ )
103
+ }
@@ -0,0 +1,266 @@
1
+ import type {
2
+ PublicProfile,
3
+ PublicProfileSettings,
4
+ PublicWorkspace,
5
+ UpdatePublicProfileInput
6
+ } from '#cloud/contract'
7
+ import type { CloudDatabase } from '#cloud/server/db'
8
+ import { DocumentNotFoundError } from '#cloud/server/documents/errors'
9
+ import { workspaceRole } from '#cloud/server/documents/repository'
10
+ import { CLOUD_FEATURE_KEYS, type CloudPolicy } from '#cloud/server/policy'
11
+ import { groupBy } from 'es-toolkit'
12
+ import type { Kysely } from 'kysely'
13
+
14
+ /** The handle belongs to someone else's public profile. */
15
+ export class PublicProfileHandleTakenError extends Error {
16
+ override readonly name = 'PublicProfileHandleTakenError'
17
+ }
18
+
19
+ /** Only a workspace's administrators put it on their public profile or take it off. */
20
+ export class PublicProfileForbiddenError extends Error {
21
+ override readonly name = 'PublicProfileForbiddenError'
22
+ }
23
+
24
+ export type PublicProfileServiceOptions = {
25
+ policy?: CloudPolicy
26
+ deploymentMode?: 'official' | 'self-hosted'
27
+ /**
28
+ * Whether an account's enrollment is approved, where the server admits accounts by approval;
29
+ * a profile whose owner is no longer approved goes dark with them.
30
+ */
31
+ isApproved?: (email: string) => Promise<boolean>
32
+ }
33
+
34
+ /**
35
+ * Public profiles, `/u/<handle>`: a person claims a handle and lists the workspaces they
36
+ * administer and made public themselves. Anyone may read a public workspace's documents while the
37
+ * administrator who published it still administers it and may use the server, and while the
38
+ * workspace's policy allows links and guest viewing, checked when it is published and when read.
39
+ */
40
+ export function createPublicProfileService(
41
+ database: Kysely<CloudDatabase>,
42
+ options: PublicProfileServiceOptions = {}
43
+ ) {
44
+ async function guestsMayView(workspaceId: string, actorId?: string): Promise<boolean> {
45
+ const { policy } = options
46
+ if (!policy) return true
47
+ const context = {
48
+ targetingKey: workspaceId,
49
+ ...(actorId ? { actorId } : {}),
50
+ workspaceId,
51
+ deploymentMode: options.deploymentMode ?? 'self-hosted'
52
+ }
53
+ return (
54
+ (await policy.boolean(CLOUD_FEATURE_KEYS.links, false, context)) &&
55
+ (await policy.boolean(CLOUD_FEATURE_KEYS.guestView, false, context))
56
+ )
57
+ }
58
+
59
+ /** Whether an account exists, is not banned, and, where approval admits accounts, is approved. */
60
+ async function accountActive(userId: string): Promise<boolean> {
61
+ const account = await database
62
+ .selectFrom('user')
63
+ .select(['email', 'banned'])
64
+ .where('id', '=', userId)
65
+ .executeTakeFirst()
66
+ if (!account || account.banned === true) return false
67
+ return options.isApproved ? options.isApproved(account.email) : true
68
+ }
69
+
70
+ async function adminWorkspaces(userId: string) {
71
+ return database
72
+ .selectFrom('workspace')
73
+ .innerJoin('workspaceMember', 'workspaceMember.workspaceId', 'workspace.id')
74
+ .select([
75
+ 'workspace.id',
76
+ 'workspace.name',
77
+ 'workspace.slug',
78
+ 'workspace.publicAt',
79
+ 'workspace.publicBy'
80
+ ])
81
+ .where('workspaceMember.userId', '=', userId)
82
+ .where('workspaceMember.role', '=', 'admin')
83
+ .orderBy('workspace.name')
84
+ .execute()
85
+ }
86
+
87
+ async function settings(userId: string): Promise<PublicProfileSettings> {
88
+ const profile = await database
89
+ .selectFrom('publicProfile')
90
+ .select(['handle', 'bio'])
91
+ .where('userId', '=', userId)
92
+ .executeTakeFirst()
93
+ const workspaces = await adminWorkspaces(userId)
94
+ return {
95
+ handle: profile?.handle ?? null,
96
+ bio: profile?.bio ?? null,
97
+ workspaces: workspaces.map((workspace) => ({
98
+ id: workspace.id,
99
+ name: workspace.name,
100
+ public: listedBy(workspace, userId)
101
+ }))
102
+ }
103
+ }
104
+
105
+ return {
106
+ settings,
107
+
108
+ /** Claims or changes the person's handle and bio; a null handle removes the profile. */
109
+ async update(userId: string, input: UpdatePublicProfileInput): Promise<PublicProfileSettings> {
110
+ const { handle } = input
111
+ if (handle === null) {
112
+ await database.deleteFrom('publicProfile').where('userId', '=', userId).execute()
113
+ return settings(userId)
114
+ }
115
+ // A handle whose account was deleted is free again.
116
+ await database
117
+ .deleteFrom('publicProfile')
118
+ .where('handle', '=', handle)
119
+ .where('userId', 'not in', database.selectFrom('user').select('id'))
120
+ .execute()
121
+ const taken = await database
122
+ .selectFrom('publicProfile')
123
+ .select('userId')
124
+ .where('handle', '=', handle)
125
+ .where('userId', '!=', userId)
126
+ .executeTakeFirst()
127
+ if (taken) throw new PublicProfileHandleTakenError()
128
+ const bio = input.bio === undefined ? undefined : input.bio || null
129
+ try {
130
+ await database
131
+ .insertInto('publicProfile')
132
+ .values({ userId, handle, bio: bio ?? null })
133
+ .onConflict((conflict) =>
134
+ conflict.column('userId').doUpdateSet({
135
+ handle,
136
+ ...(bio === undefined ? {} : { bio }),
137
+ updatedAt: new Date()
138
+ })
139
+ )
140
+ .execute()
141
+ } catch (error) {
142
+ // Someone took the handle between the check and the write.
143
+ const again = await database
144
+ .selectFrom('publicProfile')
145
+ .select('userId')
146
+ .where('handle', '=', handle)
147
+ .executeTakeFirst()
148
+ if (again && again.userId !== userId) throw new PublicProfileHandleTakenError()
149
+ throw error
150
+ }
151
+ return settings(userId)
152
+ },
153
+
154
+ /**
155
+ * Makes a workspace public on this administrator's profile, taking it off any other's, or
156
+ * makes it private again.
157
+ */
158
+ async publishWorkspace(userId: string, workspaceId: string, published: boolean) {
159
+ const role = await workspaceRole(database, userId, workspaceId)
160
+ if (!role) throw new DocumentNotFoundError()
161
+ if (role !== 'admin') throw new PublicProfileForbiddenError()
162
+ if (published && !(await guestsMayView(workspaceId, userId))) {
163
+ throw new PublicProfileForbiddenError()
164
+ }
165
+ await database
166
+ .updateTable('workspace')
167
+ .set({
168
+ publicAt: published ? new Date() : null,
169
+ publicBy: published ? userId : null,
170
+ updatedAt: new Date()
171
+ })
172
+ .where('id', '=', workspaceId)
173
+ .execute()
174
+ return settings(userId)
175
+ },
176
+
177
+ /** What anyone sees at `/u/<handle>`, or null when no profile has it. */
178
+ async publicProfile(handle: string): Promise<PublicProfile | null> {
179
+ const profile = await database
180
+ .selectFrom('publicProfile')
181
+ .innerJoin('user', 'user.id', 'publicProfile.userId')
182
+ .select([
183
+ 'publicProfile.userId',
184
+ 'publicProfile.handle',
185
+ 'publicProfile.bio',
186
+ 'user.name',
187
+ 'user.image'
188
+ ])
189
+ .where('publicProfile.handle', '=', handle.toLowerCase())
190
+ .executeTakeFirst()
191
+ if (!profile || !(await accountActive(profile.userId))) return null
192
+ const listed = (await adminWorkspaces(profile.userId)).filter((workspace) =>
193
+ listedBy(workspace, profile.userId)
194
+ )
195
+ const open = []
196
+ for (const workspace of listed) {
197
+ if (await guestsMayView(workspace.id)) open.push(workspace)
198
+ }
199
+ const documents =
200
+ open.length === 0
201
+ ? []
202
+ : await database
203
+ .selectFrom('document')
204
+ .select(['id', 'workspaceId', 'name', 'updatedAt'])
205
+ .where(
206
+ 'workspaceId',
207
+ 'in',
208
+ open.map((workspace) => workspace.id)
209
+ )
210
+ .where('deletedAt', 'is', null)
211
+ .where('currentRevisionId', 'is not', null)
212
+ .orderBy('updatedAt', 'desc')
213
+ .execute()
214
+ const byWorkspace = groupBy(documents, (document) => document.workspaceId)
215
+ const workspaces: PublicWorkspace[] = open.map((workspace) => ({
216
+ id: workspace.id,
217
+ name: workspace.name,
218
+ slug: workspace.slug,
219
+ documents: (byWorkspace[workspace.id] ?? []).map((document) => ({
220
+ id: document.id,
221
+ name: document.name,
222
+ updatedAt: new Date(document.updatedAt).toISOString()
223
+ }))
224
+ }))
225
+ return {
226
+ handle: profile.handle,
227
+ name: profile.name,
228
+ image: profile.image ?? null,
229
+ bio: profile.bio,
230
+ workspaces
231
+ }
232
+ },
233
+
234
+ /** Lets anyone in to a document of a public workspace; throws for any other document. */
235
+ async requirePublicDocument(documentId: string): Promise<void> {
236
+ const document = await database
237
+ .selectFrom('document')
238
+ .innerJoin('workspace', 'workspace.id', 'document.workspaceId')
239
+ .select(['document.workspaceId', 'workspace.publicBy'])
240
+ .where('document.id', '=', documentId)
241
+ .where('document.deletedAt', 'is', null)
242
+ .where('workspace.publicAt', 'is not', null)
243
+ .executeTakeFirst()
244
+ const publisher = document?.publicBy
245
+ if (
246
+ !document ||
247
+ !publisher ||
248
+ (await workspaceRole(database, publisher, document.workspaceId)) !== 'admin' ||
249
+ !(await accountActive(publisher)) ||
250
+ !(await guestsMayView(document.workspaceId))
251
+ ) {
252
+ throw new DocumentNotFoundError()
253
+ }
254
+ }
255
+ }
256
+ }
257
+
258
+ export type PublicProfileService = ReturnType<typeof createPublicProfileService>
259
+
260
+ /** Whether `userId`'s profile lists the workspace: it is public, and they made it so. */
261
+ function listedBy(
262
+ workspace: { publicAt: Date | null; publicBy: string | null },
263
+ userId: string
264
+ ): boolean {
265
+ return workspace.publicAt !== null && workspace.publicBy === userId
266
+ }
@@ -0,0 +1,7 @@
1
+ export { createStorageReconciliationService, type StorageReconciliation } from './reconcile'
2
+ export {
3
+ createStorageQuotaService,
4
+ StorageQuotaExceededError,
5
+ type StorageQuotaService,
6
+ type StorageQuotaSnapshot
7
+ } from './storage'
@@ -0,0 +1,61 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import { sumBy } from 'es-toolkit'
3
+ import type { Kysely } from 'kysely'
4
+
5
+ export type StorageReconciliation = {
6
+ workspaceId: string
7
+ recordedBytes: number
8
+ calculatedBytes: number
9
+ corrected: boolean
10
+ }
11
+
12
+ export function createStorageReconciliationService(database: Kysely<CloudDatabase>) {
13
+ return {
14
+ async reconcile(options: { dryRun: boolean }): Promise<StorageReconciliation[]> {
15
+ const workspaces = await database.selectFrom('workspace').select('id').execute()
16
+ const results: StorageReconciliation[] = []
17
+ for (const workspace of workspaces) {
18
+ const [recorded, objects] = await Promise.all([
19
+ database
20
+ .selectFrom('workspaceStorageUsage')
21
+ .select('committedBytes')
22
+ .where('workspaceId', '=', workspace.id)
23
+ .executeTakeFirst(),
24
+ database
25
+ .selectFrom('storageObject')
26
+ .innerJoin('documentRevision', 'documentRevision.storageObjectId', 'storageObject.id')
27
+ .innerJoin('document', 'document.id', 'documentRevision.documentId')
28
+ .select(['storageObject.id', 'storageObject.byteSize'])
29
+ .distinct()
30
+ .where('document.workspaceId', '=', workspace.id)
31
+ // Images are the workspace's once, whichever revisions use them.
32
+ .union((union) =>
33
+ union
34
+ .selectFrom('storageObject')
35
+ .innerJoin('workspaceImage', 'workspaceImage.storageObjectId', 'storageObject.id')
36
+ .select(['storageObject.id', 'storageObject.byteSize'])
37
+ .where('workspaceImage.workspaceId', '=', workspace.id)
38
+ )
39
+ .execute()
40
+ ])
41
+ const recordedBytes = Number(recorded?.committedBytes ?? 0)
42
+ const calculatedBytes = sumBy(objects, (object) => Number(object.byteSize))
43
+ const corrected = recordedBytes !== calculatedBytes
44
+ if (corrected && !options.dryRun) {
45
+ await database
46
+ .insertInto('workspaceStorageUsage')
47
+ .values({ workspaceId: workspace.id, committedBytes: calculatedBytes })
48
+ .onConflict((conflict) =>
49
+ conflict.column('workspaceId').doUpdateSet({
50
+ committedBytes: calculatedBytes,
51
+ updatedAt: new Date()
52
+ })
53
+ )
54
+ .execute()
55
+ }
56
+ results.push({ workspaceId: workspace.id, recordedBytes, calculatedBytes, corrected })
57
+ }
58
+ return results
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,165 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import type { Kysely, Transaction } from 'kysely'
3
+
4
+ export class StorageQuotaExceededError extends Error {
5
+ override readonly name = 'StorageQuotaExceededError'
6
+ }
7
+
8
+ export type StorageQuotaSnapshot = {
9
+ committedBytes: number
10
+ reservedBytes: number
11
+ }
12
+
13
+ type StorageDatabase = Kysely<CloudDatabase> | Transaction<CloudDatabase>
14
+
15
+ export function createStorageQuotaService(database: Kysely<CloudDatabase>) {
16
+ async function snapshot(
17
+ executor: StorageDatabase,
18
+ workspaceId: string,
19
+ now = new Date()
20
+ ): Promise<StorageQuotaSnapshot> {
21
+ const [usage, reservation] = await Promise.all([
22
+ executor
23
+ .selectFrom('workspaceStorageUsage')
24
+ .select('committedBytes')
25
+ .where('workspaceId', '=', workspaceId)
26
+ .executeTakeFirst(),
27
+ executor
28
+ .selectFrom('uploadStorageReservation')
29
+ .select((expression) =>
30
+ expression.fn.coalesce(expression.fn.sum('bytes'), expression.val(0)).as('reservedBytes')
31
+ )
32
+ .where('workspaceId', '=', workspaceId)
33
+ .where('committedAt', 'is', null)
34
+ .where('releasedAt', 'is', null)
35
+ .where('expiresAt', '>', now)
36
+ .executeTakeFirstOrThrow()
37
+ ])
38
+ return {
39
+ committedBytes: Number(usage?.committedBytes ?? 0),
40
+ reservedBytes: Number(reservation.reservedBytes)
41
+ }
42
+ }
43
+
44
+ async function reserve(
45
+ executor: StorageDatabase,
46
+ input: {
47
+ workspaceId: string
48
+ uploadId: string
49
+ bytes: number
50
+ expiresAt: Date
51
+ maximumBytes: number | null
52
+ }
53
+ ): Promise<void> {
54
+ await executor
55
+ .insertInto('workspaceStorageUsage')
56
+ .values({ workspaceId: input.workspaceId, committedBytes: 0 })
57
+ .onConflict((conflict) => conflict.column('workspaceId').doNothing())
58
+ .execute()
59
+ await executor
60
+ .selectFrom('workspaceStorageUsage')
61
+ .select('workspaceId')
62
+ .where('workspaceId', '=', input.workspaceId)
63
+ .forUpdate()
64
+ .executeTakeFirstOrThrow()
65
+ const usage = await snapshot(executor, input.workspaceId)
66
+ if (
67
+ input.maximumBytes !== null &&
68
+ usage.committedBytes + usage.reservedBytes + input.bytes > input.maximumBytes
69
+ ) {
70
+ throw new StorageQuotaExceededError('Workspace storage quota exceeded')
71
+ }
72
+ await executor
73
+ .insertInto('uploadStorageReservation')
74
+ .values({
75
+ id: crypto.randomUUID(),
76
+ workspaceId: input.workspaceId,
77
+ uploadId: input.uploadId,
78
+ bytes: input.bytes,
79
+ expiresAt: input.expiresAt,
80
+ committedAt: null,
81
+ releasedAt: null
82
+ })
83
+ .onConflict((conflict) => conflict.column('uploadId').doNothing())
84
+ .execute()
85
+ }
86
+
87
+ async function commit(executor: StorageDatabase, uploadId: string): Promise<void> {
88
+ const reservation = await executor
89
+ .selectFrom('uploadStorageReservation')
90
+ .select(['id', 'workspaceId', 'bytes', 'committedAt', 'releasedAt'])
91
+ .where('uploadId', '=', uploadId)
92
+ .forUpdate()
93
+ .executeTakeFirst()
94
+ if (!reservation || reservation.committedAt || reservation.releasedAt) return
95
+ await executor
96
+ .updateTable('workspaceStorageUsage')
97
+ .set({
98
+ committedBytes: (expression) =>
99
+ expression('committedBytes', '+', Number(reservation.bytes)),
100
+ updatedAt: new Date()
101
+ })
102
+ .where('workspaceId', '=', reservation.workspaceId)
103
+ .execute()
104
+ await executor
105
+ .updateTable('uploadStorageReservation')
106
+ .set({ committedAt: new Date() })
107
+ .where('id', '=', reservation.id)
108
+ .execute()
109
+ }
110
+
111
+ async function release(executor: StorageDatabase, uploadId: string): Promise<void> {
112
+ await executor
113
+ .updateTable('uploadStorageReservation')
114
+ .set({ releasedAt: new Date() })
115
+ .where('uploadId', '=', uploadId)
116
+ .where('committedAt', 'is', null)
117
+ .where('releasedAt', 'is', null)
118
+ .execute()
119
+ }
120
+
121
+ return {
122
+ snapshot: (workspaceId: string) => snapshot(database, workspaceId),
123
+
124
+ async reserve(input: {
125
+ workspaceId: string
126
+ uploadId: string
127
+ bytes: number
128
+ expiresAt: Date
129
+ maximumBytes: number | null
130
+ }): Promise<void> {
131
+ await database.transaction().execute((transaction) => reserve(transaction, input))
132
+ },
133
+
134
+ reserveInTransaction(
135
+ transaction: Transaction<CloudDatabase>,
136
+ input: {
137
+ workspaceId: string
138
+ uploadId: string
139
+ bytes: number
140
+ expiresAt: Date
141
+ maximumBytes: number | null
142
+ }
143
+ ): Promise<void> {
144
+ return reserve(transaction, input)
145
+ },
146
+
147
+ async commit(uploadId: string): Promise<void> {
148
+ await database.transaction().execute((transaction) => commit(transaction, uploadId))
149
+ },
150
+
151
+ commitInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {
152
+ return commit(transaction, uploadId)
153
+ },
154
+
155
+ async release(uploadId: string): Promise<void> {
156
+ await release(database, uploadId)
157
+ },
158
+
159
+ releaseInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {
160
+ return release(transaction, uploadId)
161
+ }
162
+ }
163
+ }
164
+
165
+ export type StorageQuotaService = ReturnType<typeof createStorageQuotaService>
@@ -0,0 +1,16 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import type { Kysely } from 'kysely'
3
+
4
+ export function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {
5
+ return {
6
+ async cleanupExpired(before: Date): Promise<number> {
7
+ const result = await database
8
+ .deleteFrom('apiRateLimit')
9
+ .where('windowStartedAt', '<', before)
10
+ .executeTakeFirst()
11
+ return Number(result.numDeletedRows)
12
+ }
13
+ }
14
+ }
15
+
16
+ export type RateLimitCleanupService = ReturnType<typeof createRateLimitCleanupService>
@@ -0,0 +1,12 @@
1
+ export { createRateLimitCleanupService, type RateLimitCleanupService } from './cleanup'
2
+ export { rateLimitKey, trustedClientIP, type ClientIdentityOptions } from './keys'
3
+ export {
4
+ CLOUD_RATE_LIMITS,
5
+ createActorRateLimiter,
6
+ createCloudRateLimiter,
7
+ createRouteRateLimiter,
8
+ createTrustedIPRateLimiter,
9
+ routeHasOwnBudget,
10
+ type RateLimitPolicy
11
+ } from './middleware'
12
+ export { PostgresRateLimitStore } from './postgres'
@@ -0,0 +1,38 @@
1
+ import type { CloudActor } from '#cloud/server/auth'
2
+ import type { Context } from 'hono'
3
+
4
+ export type ClientIdentityOptions = {
5
+ trustedHeaders: string[]
6
+ }
7
+
8
+ /**
9
+ * The client address a trusted proxy reported. List-valued headers such as `X-Forwarded-For` carry
10
+ * whatever the client sent followed by what each proxy appended, so only the right-most entry,
11
+ * the one the trusted proxy wrote, identifies the client.
12
+ */
13
+ export function trustedClientIP(context: Context, options: ClientIdentityOptions): string | null {
14
+ for (const header of options.trustedHeaders) {
15
+ const value = context.req
16
+ .header(header)
17
+ ?.split(',')
18
+ .map((entry) => entry.trim())
19
+ .findLast((entry) => entry.length > 0)
20
+ if (value) return value
21
+ }
22
+ return null
23
+ }
24
+
25
+ export const rateLimitKey = {
26
+ email(email: string): string {
27
+ return `email:${email.trim().toLowerCase()}`
28
+ },
29
+ ip(ip: string): string {
30
+ return `ip:${ip}`
31
+ },
32
+ actor(actor: CloudActor): string {
33
+ return `actor:${actor.userId}`
34
+ },
35
+ resource(resourceId: string, identity: string): string {
36
+ return `resource:${resourceId}:${identity}`
37
+ }
38
+ }