@open-pencil/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 (279) 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 +1520 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +1917 -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 +1453 -0
  18. package/dist/contract2.js.map +1 -0
  19. package/dist/email.d.ts +169 -0
  20. package/dist/email.d.ts.map +1 -0
  21. package/dist/email.js +670 -0
  22. package/dist/email.js.map +1 -0
  23. package/dist/index.d.ts +1755 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/listen.mjs +1881 -0
  26. package/dist/listen.mjs.map +1 -0
  27. package/dist/runtime-node.d.mts +10040 -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 +12792 -0
  32. package/dist/server.d.ts.map +1 -0
  33. package/dist/server.js +8475 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/server.mjs +8324 -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 +124 -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 +28 -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 +528 -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/response.ts +51 -0
  75. package/src/client/workspaces.ts +142 -0
  76. package/src/contract/account.ts +204 -0
  77. package/src/contract/admin/index.ts +187 -0
  78. package/src/contract/ai.ts +150 -0
  79. package/src/contract/collaboration.ts +45 -0
  80. package/src/contract/discovery.ts +81 -0
  81. package/src/contract/documents.ts +265 -0
  82. package/src/contract/entitlements.ts +28 -0
  83. package/src/contract/index.ts +204 -0
  84. package/src/contract/links.ts +87 -0
  85. package/src/contract/portal.ts +11 -0
  86. package/src/contract/relay.ts +368 -0
  87. package/src/contract/sharing.ts +191 -0
  88. package/src/contract/versions.ts +87 -0
  89. package/src/contract/workspaces.ts +100 -0
  90. package/src/email/index.ts +14 -0
  91. package/src/email/render.ts +276 -0
  92. package/src/email/schema.ts +144 -0
  93. package/src/email/templates/brand.ts +105 -0
  94. package/src/email/templates/document-invitation.ts +35 -0
  95. package/src/email/templates/enrollment.ts +27 -0
  96. package/src/email/templates/layout.ts +18 -0
  97. package/src/runtime/cloudflare/email.ts +70 -0
  98. package/src/runtime/cloudflare/environment.ts +57 -0
  99. package/src/runtime/cloudflare/index.ts +3 -0
  100. package/src/runtime/cloudflare/relay.ts +136 -0
  101. package/src/runtime/cloudflare/site.ts +13 -0
  102. package/src/runtime/cloudflare/tsconfig.json +21 -0
  103. package/src/runtime/cloudflare/worker.ts +160 -0
  104. package/src/runtime/node/admin.ts +59 -0
  105. package/src/runtime/node/ai-relay/main.ts +35 -0
  106. package/src/runtime/node/ai-relay/server.ts +63 -0
  107. package/src/runtime/node/application.ts +50 -0
  108. package/src/runtime/node/bootstrap.ts +22 -0
  109. package/src/runtime/node/cleanup.ts +24 -0
  110. package/src/runtime/node/command.ts +17 -0
  111. package/src/runtime/node/config.ts +16 -0
  112. package/src/runtime/node/email/runtime.ts +43 -0
  113. package/src/runtime/node/email/transport.ts +112 -0
  114. package/src/runtime/node/entitlements/main.ts +41 -0
  115. package/src/runtime/node/entitlements/refusal.ts +15 -0
  116. package/src/runtime/node/index.ts +25 -0
  117. package/src/runtime/node/listen.ts +35 -0
  118. package/src/runtime/node/main.ts +29 -0
  119. package/src/runtime/node/migrate.ts +13 -0
  120. package/src/runtime/node/quota-reconcile.ts +9 -0
  121. package/src/runtime/node/relay.ts +54 -0
  122. package/src/runtime/node/server.ts +121 -0
  123. package/src/runtime/node/site.ts +64 -0
  124. package/src/runtime/postgres/database.ts +19 -0
  125. package/src/runtime/s3/objects.ts +244 -0
  126. package/src/runtime/site/server.ts +82 -0
  127. package/src/server/account/actions.ts +66 -0
  128. package/src/server/account/routes.ts +300 -0
  129. package/src/server/ai/errors.ts +7 -0
  130. package/src/server/ai/index.ts +4 -0
  131. package/src/server/ai/keys.ts +43 -0
  132. package/src/server/ai/routes.ts +43 -0
  133. package/src/server/ai/service.ts +70 -0
  134. package/src/server/api/index.ts +8 -0
  135. package/src/server/api/router.ts +117 -0
  136. package/src/server/api/types.ts +7 -0
  137. package/src/server/app.ts +375 -0
  138. package/src/server/auth/account.ts +73 -0
  139. package/src/server/auth/activity.ts +213 -0
  140. package/src/server/auth/adapter.ts +79 -0
  141. package/src/server/auth/email.ts +125 -0
  142. package/src/server/auth/endpoints.ts +57 -0
  143. package/src/server/auth/factory.ts +583 -0
  144. package/src/server/auth/index.ts +17 -0
  145. package/src/server/auth/mfa-assurance.ts +55 -0
  146. package/src/server/auth/runtime.ts +26 -0
  147. package/src/server/auth/session.ts +19 -0
  148. package/src/server/auth/social-providers.ts +55 -0
  149. package/src/server/auth/user-agent.ts +16 -0
  150. package/src/server/auth/workspace-access.ts +23 -0
  151. package/src/server/cleanup/configured.ts +38 -0
  152. package/src/server/cleanup/documents.ts +231 -0
  153. package/src/server/cleanup/index.ts +29 -0
  154. package/src/server/cleanup/objects.ts +27 -0
  155. package/src/server/cleanup/revisions.ts +232 -0
  156. package/src/server/cleanup/uploads.ts +129 -0
  157. package/src/server/cleanup/worker.ts +79 -0
  158. package/src/server/collaboration/index.ts +28 -0
  159. package/src/server/collaboration/relay/authorize.ts +53 -0
  160. package/src/server/collaboration/relay/awareness.ts +104 -0
  161. package/src/server/collaboration/relay/documents.ts +39 -0
  162. package/src/server/collaboration/relay/hub.ts +524 -0
  163. package/src/server/collaboration/relay/index.ts +15 -0
  164. package/src/server/collaboration/relay/persistence.ts +48 -0
  165. package/src/server/collaboration/routes.ts +77 -0
  166. package/src/server/collaboration/service.ts +188 -0
  167. package/src/server/config/deployment.ts +178 -0
  168. package/src/server/config/index.ts +20 -0
  169. package/src/server/config/limits.ts +8 -0
  170. package/src/server/config/public.ts +66 -0
  171. package/src/server/config/schema.ts +512 -0
  172. package/src/server/db/database.ts +15 -0
  173. package/src/server/db/expressions.ts +13 -0
  174. package/src/server/db/index.ts +21 -0
  175. package/src/server/db/migrate.ts +177 -0
  176. package/src/server/db/migrations/001_foundation.ts +164 -0
  177. package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
  178. package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
  179. package/src/server/db/migrations/004_document_sharing.ts +82 -0
  180. package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
  181. package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
  182. package/src/server/db/migrations/007_collaboration_state.ts +25 -0
  183. package/src/server/db/migrations/008_storage_reservations.ts +37 -0
  184. package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
  185. package/src/server/db/migrations/010_upload_finalization.ts +22 -0
  186. package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
  187. package/src/server/db/migrations/012_transactional_email.ts +48 -0
  188. package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
  189. package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
  190. package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
  191. package/src/server/db/migrations/016_auth_schema.ts +16 -0
  192. package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
  193. package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
  194. package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
  195. package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
  196. package/src/server/db/migrations/021_document_versions.ts +66 -0
  197. package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
  198. package/src/server/db/migrations/023_document_images.ts +61 -0
  199. package/src/server/db/migrations/024_account_activity.ts +66 -0
  200. package/src/server/db/migrations/025_table_names.ts +58 -0
  201. package/src/server/db/migrations/026_user_picture.ts +30 -0
  202. package/src/server/db/migrations/027_document_kind.ts +19 -0
  203. package/src/server/db/migrations/helpers.ts +78 -0
  204. package/src/server/db/tables.ts +394 -0
  205. package/src/server/documents/access.ts +103 -0
  206. package/src/server/documents/errors.ts +16 -0
  207. package/src/server/documents/images.ts +407 -0
  208. package/src/server/documents/index.ts +14 -0
  209. package/src/server/documents/limits.ts +57 -0
  210. package/src/server/documents/repository.ts +141 -0
  211. package/src/server/documents/routes.ts +239 -0
  212. package/src/server/documents/service.ts +597 -0
  213. package/src/server/documents/summary.ts +37 -0
  214. package/src/server/documents/types.ts +14 -0
  215. package/src/server/documents/versions/checkpoint.ts +98 -0
  216. package/src/server/documents/versions/history.ts +25 -0
  217. package/src/server/documents/versions/index.ts +4 -0
  218. package/src/server/documents/versions/routes.ts +112 -0
  219. package/src/server/documents/versions/service.ts +397 -0
  220. package/src/server/email/crypto.ts +57 -0
  221. package/src/server/email/index.ts +18 -0
  222. package/src/server/email/invitations.ts +30 -0
  223. package/src/server/email/service.ts +245 -0
  224. package/src/server/email/types.ts +56 -0
  225. package/src/server/email/worker.ts +33 -0
  226. package/src/server/index.ts +279 -0
  227. package/src/server/internal/index.ts +8 -0
  228. package/src/server/internal/routes.ts +41 -0
  229. package/src/server/internal/schema.ts +10 -0
  230. package/src/server/internal/service.ts +44 -0
  231. package/src/server/invitations/index.ts +6 -0
  232. package/src/server/invitations/types.ts +30 -0
  233. package/src/server/objects/index.ts +16 -0
  234. package/src/server/objects/types.ts +81 -0
  235. package/src/server/pictures/index.ts +9 -0
  236. package/src/server/pictures/provider.ts +61 -0
  237. package/src/server/pictures/routes.ts +21 -0
  238. package/src/server/pictures/service.ts +235 -0
  239. package/src/server/policy/configured.ts +23 -0
  240. package/src/server/policy/database.ts +108 -0
  241. package/src/server/policy/entitlements.ts +29 -0
  242. package/src/server/policy/index.ts +17 -0
  243. package/src/server/policy/keys.ts +23 -0
  244. package/src/server/policy/policy.ts +117 -0
  245. package/src/server/policy/provider.ts +67 -0
  246. package/src/server/policy/schema.ts +69 -0
  247. package/src/server/policy/service.ts +85 -0
  248. package/src/server/policy/static.ts +62 -0
  249. package/src/server/quota/index.ts +7 -0
  250. package/src/server/quota/reconcile.ts +61 -0
  251. package/src/server/quota/storage.ts +165 -0
  252. package/src/server/rate-limit/cleanup.ts +16 -0
  253. package/src/server/rate-limit/index.ts +12 -0
  254. package/src/server/rate-limit/keys.ts +38 -0
  255. package/src/server/rate-limit/middleware.ts +137 -0
  256. package/src/server/rate-limit/postgres.ts +79 -0
  257. package/src/server/sharing/access.ts +29 -0
  258. package/src/server/sharing/actor.ts +12 -0
  259. package/src/server/sharing/capabilities/service.ts +262 -0
  260. package/src/server/sharing/continuation.ts +85 -0
  261. package/src/server/sharing/contracts.ts +80 -0
  262. package/src/server/sharing/crypto.ts +48 -0
  263. package/src/server/sharing/document-routes.ts +41 -0
  264. package/src/server/sharing/errors.ts +12 -0
  265. package/src/server/sharing/grants/service.ts +79 -0
  266. package/src/server/sharing/http.ts +41 -0
  267. package/src/server/sharing/index.ts +39 -0
  268. package/src/server/sharing/invitations/service.ts +315 -0
  269. package/src/server/sharing/policy.ts +44 -0
  270. package/src/server/sharing/routes.ts +251 -0
  271. package/src/server/sharing/service.ts +117 -0
  272. package/src/server/validation.ts +24 -0
  273. package/src/server/worker/interval.ts +23 -0
  274. package/src/server/worker/periodic.ts +42 -0
  275. package/src/server/workspaces/index.ts +16 -0
  276. package/src/server/workspaces/members.ts +502 -0
  277. package/src/server/workspaces/repository.ts +91 -0
  278. package/src/server/workspaces/routes.ts +198 -0
  279. package/src/server/workspaces/service.ts +84 -0
@@ -0,0 +1,369 @@
1
+ import { AdminDomainError } from '#cloud/admin/errors'
2
+ import {
3
+ containsPattern,
4
+ countEachFilter,
5
+ listSearch,
6
+ listWindow,
7
+ type AdminListQuery,
8
+ type ListFilters
9
+ } from '#cloud/admin/list'
10
+ import {
11
+ cloudAdminUserFilterSchema,
12
+ type CloudAdminUser,
13
+ type CloudAdminUserDetail,
14
+ type CloudAdminUserFilter
15
+ } from '#cloud/contract'
16
+ import {
17
+ createSignInActivity,
18
+ type AuthenticationEmailService,
19
+ type CloudAuthAdapter
20
+ } from '#cloud/server/auth'
21
+ import type { CloudDatabase } from '#cloud/server/db'
22
+ import type { UserPictureService } from '#cloud/server/pictures'
23
+ import { dateString } from '#cloud/server/sharing/contracts'
24
+ import { countBy, keyBy } from 'es-toolkit'
25
+ import type { ExpressionBuilder, Kysely } from 'kysely'
26
+
27
+ /** The sign-ins a person's page lists. */
28
+ const DETAIL_SIGN_INS = 20
29
+
30
+ type UserExpression = ExpressionBuilder<CloudDatabase, 'user'>
31
+
32
+ /** A search for part of a name or email, matched literally and without case. */
33
+ function searchCondition(search: string) {
34
+ const pattern = containsPattern(search)
35
+ return (expression: UserExpression) =>
36
+ expression.or([
37
+ expression('user.email', 'ilike', pattern),
38
+ expression('user.name', 'ilike', pattern)
39
+ ])
40
+ }
41
+
42
+ const FILTERS: ListFilters<CloudAdminUserFilter, 'user'> = {
43
+ all: (expression) => expression.lit(true),
44
+ administrators: (expression) => expression('user.role', '=', 'admin'),
45
+ suspended: (expression) => expression('user.banned', '=', true),
46
+ 'without-two-step': (expression) =>
47
+ expression.and([
48
+ // Better Auth leaves the flag unset on accounts that never turned it on.
49
+ expression('user.twoFactorEnabled', 'is not', true),
50
+ expression.not(
51
+ expression.exists(
52
+ expression
53
+ .selectFrom('passkey')
54
+ .select('passkey.id')
55
+ .whereRef('passkey.userId', '=', 'user.id')
56
+ )
57
+ )
58
+ ])
59
+ }
60
+
61
+ export type AdminUserQuery = AdminListQuery<CloudAdminUserFilter>
62
+
63
+ type UserRow = {
64
+ id: string
65
+ name: string
66
+ email: string
67
+ image: string | null
68
+ role: string | null
69
+ banned: boolean | null
70
+ banReason: string | null
71
+ twoFactorEnabled: boolean | null
72
+ createdAt: Date | string
73
+ }
74
+
75
+ export function createAdminUserService(
76
+ database: Kysely<CloudDatabase>,
77
+ auth: CloudAuthAdapter,
78
+ options: {
79
+ requireMFA?: boolean
80
+ notify?: AuthenticationEmailService
81
+ /** Takes down a person's picture; without it, `removePicture` refuses. */
82
+ pictures?: UserPictureService
83
+ } = {}
84
+ ) {
85
+ const activity = createSignInActivity(database)
86
+
87
+ async function audit(
88
+ actorId: string,
89
+ action: string,
90
+ userId: string,
91
+ metadata: Record<string, unknown> = {}
92
+ ): Promise<void> {
93
+ await database
94
+ .insertInto('adminAuditEvent')
95
+ .values({
96
+ id: crypto.randomUUID(),
97
+ actorUserId: actorId,
98
+ action,
99
+ subjectType: 'user',
100
+ subjectId: userId,
101
+ metadata
102
+ })
103
+ .execute()
104
+ }
105
+
106
+ function refuseSelf(actorId: string, userId: string, action: string): void {
107
+ if (actorId === userId) {
108
+ throw new AdminDomainError(
109
+ 'self_admin_action_forbidden',
110
+ `Administrators cannot ${action} themselves`
111
+ )
112
+ }
113
+ }
114
+
115
+ async function requireSafeTarget(
116
+ actorId: string,
117
+ userId: string,
118
+ action: 'ban' | 'demote'
119
+ ): Promise<void> {
120
+ refuseSelf(actorId, userId, action)
121
+ const target = await database
122
+ .selectFrom('user')
123
+ .select('role')
124
+ .where('id', '=', userId)
125
+ .executeTakeFirst()
126
+ if (target?.role !== 'admin') return
127
+ const count = await database
128
+ .selectFrom('user')
129
+ .select(({ fn }) => fn.countAll<number>().as('count'))
130
+ .where('role', '=', 'admin')
131
+ .where((expression) =>
132
+ expression.or([expression('banned', '=', false), expression('banned', 'is', null)])
133
+ )
134
+ .executeTakeFirstOrThrow()
135
+ if (Number(count.count) <= 1) {
136
+ throw new AdminDomainError(
137
+ 'last_admin_required',
138
+ 'Cannot remove the last deployment administrator'
139
+ )
140
+ }
141
+ }
142
+
143
+ /** What the list shows about each account beyond its own row. */
144
+ async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {
145
+ const ids = rows.map((row) => row.id)
146
+ if (ids.length === 0) return []
147
+ const [passkeys, sessions, memberships] = await Promise.all([
148
+ database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),
149
+ database
150
+ .selectFrom('session')
151
+ .select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])
152
+ .where('session.userId', 'in', ids)
153
+ .where('session.expiresAt', '>', new Date())
154
+ .groupBy('session.userId')
155
+ .execute(),
156
+ database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute()
157
+ ])
158
+ const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))
159
+ const lastActive = keyBy(sessions, (session) => session.userId)
160
+ const workspaceCounts = countBy(memberships, (membership) => membership.userId)
161
+ return rows.map((row) => ({
162
+ id: row.id,
163
+ name: row.name,
164
+ email: row.email,
165
+ image: row.image,
166
+ role: row.role ?? undefined,
167
+ banned: row.banned,
168
+ banReason: row.banReason,
169
+ createdAt: dateString(row.createdAt) ?? '',
170
+ twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),
171
+ lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),
172
+ workspaceCount: workspaceCounts[row.id] ?? 0
173
+ }))
174
+ }
175
+
176
+ const userColumns = [
177
+ 'user.id',
178
+ 'user.name',
179
+ 'user.email',
180
+ 'user.image',
181
+ 'user.role',
182
+ 'user.banned',
183
+ 'user.banReason',
184
+ 'user.twoFactorEnabled',
185
+ 'user.emailVerified',
186
+ 'user.createdAt'
187
+ ] as const
188
+
189
+ return {
190
+ /** A page of accounts in sign-up order, with how many match the search under each filter. */
191
+ async list(query: AdminUserQuery = {}) {
192
+ const search = listSearch(query)
193
+ const filter = query.filter ?? 'all'
194
+ const { limit, offset } = listWindow(query)
195
+ let searched = database.selectFrom('user')
196
+ if (search) searched = searched.where(searchCondition(search))
197
+ const counts = await countEachFilter(searched, cloudAdminUserFilterSchema.options, FILTERS)
198
+ const rows = await searched
199
+ .where(FILTERS[filter])
200
+ .select(userColumns)
201
+ .orderBy('user.createdAt')
202
+ .orderBy('user.id')
203
+ .limit(limit)
204
+ .offset(offset)
205
+ .execute()
206
+ return { users: await accountSummaries(rows), total: counts[filter], counts }
207
+ },
208
+
209
+ /** Everything an administrator reads about one account; null when there is none. */
210
+ async detail(userId: string): Promise<CloudAdminUserDetail | null> {
211
+ const row = await database
212
+ .selectFrom('user')
213
+ .select(userColumns)
214
+ .where('user.id', '=', userId)
215
+ .executeTakeFirst()
216
+ if (!row) return null
217
+ const [[summary], methods, passkeys, sessions, signIns, workspaces] = await Promise.all([
218
+ accountSummaries([row]),
219
+ database
220
+ .selectFrom('account')
221
+ .select(['providerId', 'createdAt'])
222
+ .where('userId', '=', userId)
223
+ .orderBy('createdAt')
224
+ .execute(),
225
+ database
226
+ .selectFrom('passkey')
227
+ .select(({ fn }) => fn.countAll<number>().as('count'))
228
+ .where('userId', '=', userId)
229
+ .executeTakeFirstOrThrow(),
230
+ activity.sessions(userId, ''),
231
+ activity.signIns(userId, DETAIL_SIGN_INS),
232
+ database
233
+ .selectFrom('workspaceMember')
234
+ .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')
235
+ .select((expression) => [
236
+ 'workspace.id',
237
+ 'workspace.name',
238
+ 'workspaceMember.role',
239
+ 'workspaceMember.createdAt',
240
+ expression
241
+ .selectFrom('workspaceMember as member')
242
+ .select(({ fn }) => fn.countAll<number>().as('count'))
243
+ .whereRef('member.workspaceId', '=', 'workspace.id')
244
+ .as('memberCount')
245
+ ])
246
+ .where('workspaceMember.userId', '=', userId)
247
+ .orderBy('workspaceMember.createdAt')
248
+ .execute()
249
+ ])
250
+ if (!summary) return null
251
+ return {
252
+ user: { ...summary, emailVerified: row.emailVerified },
253
+ methods: methods.map((method) => ({
254
+ provider: method.providerId,
255
+ createdAt: dateString(method.createdAt) ?? ''
256
+ })),
257
+ authenticator: row.twoFactorEnabled === true,
258
+ passkeyCount: Number(passkeys.count),
259
+ sessions,
260
+ signIns,
261
+ workspaces: workspaces.map((workspace) => ({
262
+ id: workspace.id,
263
+ name: workspace.name,
264
+ role: workspace.role,
265
+ memberCount: Number(workspace.memberCount ?? 0),
266
+ joinedAt: dateString(workspace.createdAt) ?? ''
267
+ }))
268
+ }
269
+ },
270
+
271
+ async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {
272
+ await requireSafeTarget(actorId, userId, 'ban')
273
+ await auth.banUser(headers, userId, reason)
274
+ await audit(actorId, 'user.banned', userId, reason ? { reason } : {})
275
+ },
276
+ async unban(headers: Headers, actorId: string, userId: string): Promise<void> {
277
+ await auth.unbanUser(headers, userId)
278
+ await audit(actorId, 'user.unbanned', userId)
279
+ },
280
+ async revokeSessions(headers: Headers, actorId: string, userId: string): Promise<void> {
281
+ await auth.revokeUserSessions(headers, userId)
282
+ await audit(actorId, 'user.sessions-revoked', userId)
283
+ },
284
+ async setAdmin(
285
+ headers: Headers,
286
+ actorId: string,
287
+ userId: string,
288
+ enabled: boolean
289
+ ): Promise<void> {
290
+ if (!enabled) await requireSafeTarget(actorId, userId, 'demote')
291
+ if (enabled && options.requireMFA) {
292
+ const user = await database
293
+ .selectFrom('user')
294
+ .select('twoFactorEnabled')
295
+ .where('id', '=', userId)
296
+ .executeTakeFirst()
297
+ const passkey = await database
298
+ .selectFrom('passkey')
299
+ .select('id')
300
+ .where('userId', '=', userId)
301
+ .executeTakeFirst()
302
+ if (!user?.twoFactorEnabled && !passkey) {
303
+ throw new AdminDomainError(
304
+ 'mfa_required',
305
+ 'Users must enroll MFA before becoming deployment administrators'
306
+ )
307
+ }
308
+ }
309
+ await auth.setRole(headers, userId, enabled ? 'admin' : 'user')
310
+ await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)
311
+ },
312
+
313
+ /**
314
+ * Removes an account's authenticator app, recovery codes, and passkeys, for someone who lost
315
+ * them; they sign in with their password or a linked account and set them up again.
316
+ */
317
+ async resetTwoStep(actorId: string, userId: string): Promise<void> {
318
+ refuseSelf(actorId, userId, 'reset two-step sign-in for')
319
+ const user = await database.transaction().execute(async (transaction) => {
320
+ const target = await transaction
321
+ .selectFrom('user')
322
+ .select(['id', 'email', 'name'])
323
+ .where('id', '=', userId)
324
+ .forUpdate()
325
+ .executeTakeFirstOrThrow()
326
+ await transaction.deleteFrom('twoFactor').where('userId', '=', userId).execute()
327
+ await transaction.deleteFrom('passkey').where('userId', '=', userId).execute()
328
+ await transaction.deleteFrom('mfaAssurance').where('userId', '=', userId).execute()
329
+ await transaction
330
+ .updateTable('user')
331
+ .set({ twoFactorEnabled: false, updatedAt: new Date() })
332
+ .where('id', '=', userId)
333
+ .execute()
334
+ await transaction
335
+ .insertInto('adminAuditEvent')
336
+ .values({
337
+ id: crypto.randomUUID(),
338
+ actorUserId: actorId,
339
+ action: 'user.two-step-reset',
340
+ subjectType: 'user',
341
+ subjectId: userId,
342
+ metadata: {}
343
+ })
344
+ .execute()
345
+ return target
346
+ })
347
+ await options.notify?.sendTwoStepChanged({
348
+ email: user.email,
349
+ name: user.name,
350
+ userId: user.id,
351
+ change: 'reset-by-administrator'
352
+ })
353
+ },
354
+
355
+ /** Takes down a person's picture, such as one that should not be shown; initials replace it. */
356
+ async removePicture(actorId: string, userId: string): Promise<void> {
357
+ if (!options.pictures) throw new Error('Pictures are not available')
358
+ await database
359
+ .selectFrom('user')
360
+ .select('id')
361
+ .where('id', '=', userId)
362
+ .executeTakeFirstOrThrow()
363
+ await options.pictures.remove(userId)
364
+ await audit(actorId, 'user.picture-removed', userId)
365
+ }
366
+ }
367
+ }
368
+
369
+ export type AdminUserService = ReturnType<typeof createAdminUserService>
@@ -0,0 +1,251 @@
1
+ import {
2
+ AI_ERROR_STATUS,
3
+ aiTokenClaimsSchema,
4
+ CLOUD_AI_API_PATHS,
5
+ CLOUD_AI_TOKEN_AUDIENCE,
6
+ parseAIUsageQuery,
7
+ type AIError,
8
+ type AIErrorCode,
9
+ type AITokenClaims
10
+ } from '#cloud/contract'
11
+ import { validatedQuery } from '#cloud/server/validation'
12
+ import { pick } from 'es-toolkit'
13
+ import { Hono, type Context } from 'hono'
14
+ import { bodyLimit } from 'hono/body-limit'
15
+ import { cors } from 'hono/cors'
16
+ import { jwtVerify, type JWTVerifyGetKey } from 'jose'
17
+ import type { Kysely } from 'kysely'
18
+ import * as v from 'valibot'
19
+
20
+ import type { AIRelayConfig } from './config'
21
+ import type { AIRelayDatabase } from './db'
22
+ import { creditsFor, meteredUsage } from './metering'
23
+ import { AIUsageCursorError, createAIUsageStore } from './usage'
24
+
25
+ export type AIRelayServices = {
26
+ config: AIRelayConfig
27
+ database: Kysely<AIRelayDatabase>
28
+ /** Resolves Cloud's signing keys, normally `createRemoteJWKSet` on Cloud's JWKS. */
29
+ keys: JWTVerifyGetKey
30
+ /** Reaches the upstream model API. */
31
+ fetch?: (input: string, init: RequestInit) => Promise<Response>
32
+ now?: () => Date
33
+ /**
34
+ * Keeps metering alive after the answer is returned, as Workers' `waitUntil` does. Node runs the
35
+ * promise to completion on its own.
36
+ */
37
+ waitUntil?: (promise: Promise<unknown>) => void
38
+ onBackgroundError?: (error: unknown) => void
39
+ upstreamTimeoutMs?: number
40
+ }
41
+
42
+ type AIRelayEnvironment = { Variables: { claims: AITokenClaims } }
43
+
44
+ const chatRequestSchema = v.looseObject({
45
+ model: v.pipe(v.string(), v.minLength(1)),
46
+ stream: v.optional(v.boolean())
47
+ })
48
+ const chatRequestBodySchema = v.pipe(v.string(), v.parseJson(), chatRequestSchema)
49
+
50
+ /**
51
+ * The chat completion fields sent upstream. Routing and extension fields, such as OpenRouter's
52
+ * `models` fallbacks, `provider`, and `plugins`, are dropped, so the relay's key runs only the
53
+ * catalog model it charges for.
54
+ */
55
+ const FORWARDED_FIELDS = [
56
+ 'model',
57
+ 'messages',
58
+ 'stream',
59
+ 'max_tokens',
60
+ 'max_completion_tokens',
61
+ 'temperature',
62
+ 'top_p',
63
+ 'frequency_penalty',
64
+ 'presence_penalty',
65
+ 'stop',
66
+ 'seed',
67
+ 'tools',
68
+ 'tool_choice',
69
+ 'parallel_tool_calls',
70
+ 'response_format',
71
+ 'reasoning_effort',
72
+ 'reasoning'
73
+ ] as const
74
+
75
+ /** How long an upstream answer may take in all, streamed or not, so a stalled one cannot hold a request slot forever. */
76
+ const DEFAULT_UPSTREAM_TIMEOUT_MS = 10 * 60_000
77
+
78
+ function aiError(
79
+ context: Context,
80
+ code: AIErrorCode,
81
+ details: Omit<AIError['error'], 'code'> = {}
82
+ ) {
83
+ return context.json({ error: { code, ...details } }, AI_ERROR_STATUS[code])
84
+ }
85
+
86
+ /** Counts each workspace's model requests in flight, within one process. */
87
+ function concurrencyLimiter(maximum: number) {
88
+ const inFlight = new Map<string, number>()
89
+ return {
90
+ acquire(workspaceId: string): (() => void) | null {
91
+ const count = inFlight.get(workspaceId) ?? 0
92
+ if (count >= maximum) return null
93
+ inFlight.set(workspaceId, count + 1)
94
+ let released = false
95
+ return () => {
96
+ if (released) return
97
+ released = true
98
+ const remaining = (inFlight.get(workspaceId) ?? 1) - 1
99
+ if (remaining > 0) inFlight.set(workspaceId, remaining)
100
+ else inFlight.delete(workspaceId)
101
+ }
102
+ }
103
+ }
104
+ }
105
+
106
+ /**
107
+ * The reference AI service: it verifies Cloud-signed tokens, proxies chat completions to one
108
+ * OpenAI-compatible upstream with one key, and holds each workspace to its monthly allowance.
109
+ * A request is admitted while the workspace has credits left and charged once its usage is known,
110
+ * so concurrent requests can overdraw the allowance by what they cost.
111
+ */
112
+ export function createAIRelayApp(services: AIRelayServices) {
113
+ const { config } = services
114
+ const upstreamFetch = services.fetch ?? ((input, init) => fetch(input, init))
115
+ const now = services.now ?? (() => new Date())
116
+ const usage = createAIUsageStore(services.database)
117
+ const models = new Map(config.catalog.models.map((model) => [model.id, model]))
118
+ const limiter = concurrencyLimiter(config.maximumConcurrentRequests)
119
+ const allowedOrigins = new Set(config.allowedOrigins)
120
+ const reportBackgroundError =
121
+ services.onBackgroundError ??
122
+ ((error: unknown) => console.error('[AI relay] Metering failed:', error))
123
+
124
+ const requireToken = async (context: Context<AIRelayEnvironment>, next: () => Promise<void>) => {
125
+ const header = context.req.header('Authorization')
126
+ const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined
127
+ if (!token) return aiError(context, 'unauthorized')
128
+ try {
129
+ const { payload } = await jwtVerify(token, services.keys, {
130
+ issuer: config.cloudURL,
131
+ audience: CLOUD_AI_TOKEN_AUDIENCE,
132
+ algorithms: ['ES256']
133
+ })
134
+ context.set('claims', v.parse(aiTokenClaimsSchema, payload))
135
+ } catch {
136
+ return aiError(context, 'unauthorized')
137
+ }
138
+ return next()
139
+ }
140
+
141
+ return new Hono<AIRelayEnvironment>()
142
+ .use(
143
+ '*',
144
+ cors({
145
+ origin: (origin) => (allowedOrigins.has(origin) ? origin : null),
146
+ allowMethods: ['GET', 'POST', 'OPTIONS'],
147
+ allowHeaders: ['Content-Type', 'Authorization'],
148
+ maxAge: 600
149
+ })
150
+ )
151
+ .use(`${CLOUD_AI_API_PATHS.base}/*`, requireToken)
152
+ .get(CLOUD_AI_API_PATHS.catalog, (context) => context.json(config.catalog))
153
+ .get(CLOUD_AI_API_PATHS.wallet, async (context) => {
154
+ const claims = context.get('claims')
155
+ return context.json(
156
+ await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())
157
+ )
158
+ })
159
+ .get(CLOUD_AI_API_PATHS.usage, validatedQuery(parseAIUsageQuery), async (context) => {
160
+ try {
161
+ return context.json(
162
+ await usage.page(context.get('claims').workspaceId, context.req.valid('query').cursor)
163
+ )
164
+ } catch (error) {
165
+ if (error instanceof AIUsageCursorError) {
166
+ return context.json({ error: { code: 'invalid_request' as const } }, 400)
167
+ }
168
+ throw error
169
+ }
170
+ })
171
+ .post(
172
+ CLOUD_AI_API_PATHS.chatCompletions,
173
+ // Counted as it streams in, so a body without Content-Length is bounded too.
174
+ bodyLimit({
175
+ maxSize: config.maximumRequestBytes,
176
+ onError: (context) => context.json({ error: { code: 'invalid_request' as const } }, 413)
177
+ }),
178
+ async (context) => {
179
+ const claims = context.get('claims')
180
+ const parsed = v.safeParse(chatRequestBodySchema, await context.req.text())
181
+ if (!parsed.success)
182
+ return context.json({ error: { code: 'invalid_request' as const } }, 400)
183
+ const request = pick(parsed.output, FORWARDED_FIELDS)
184
+ const model = models.get(request.model)
185
+ if (!model) return aiError(context, 'model_not_allowed')
186
+ const wallet = await usage.wallet(claims.workspaceId, claims.monthlyCreditAllowance, now())
187
+ if (wallet.balance === 0) {
188
+ return aiError(context, 'insufficient_credits', {
189
+ resetsAt: wallet.buckets[0]?.expiresAt ?? undefined
190
+ })
191
+ }
192
+ const release = limiter.acquire(claims.workspaceId)
193
+ if (!release) return aiError(context, 'rate_limited')
194
+
195
+ const streamed = request.stream === true
196
+ let upstream: Response
197
+ try {
198
+ upstream = await upstreamFetch(`${config.upstreamURL}/chat/completions`, {
199
+ method: 'POST',
200
+ headers: {
201
+ 'Content-Type': 'application/json',
202
+ Authorization: `Bearer ${config.upstreamKey}`
203
+ },
204
+ body: JSON.stringify(
205
+ streamed ? { ...request, stream_options: { include_usage: true } } : request
206
+ ),
207
+ // Aborting also errors a stream in progress, so metering ends and frees the slot.
208
+ signal: AbortSignal.timeout(services.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS)
209
+ })
210
+ } catch (error) {
211
+ release()
212
+ throw error
213
+ }
214
+ const headers = new Headers()
215
+ const contentType = upstream.headers.get('Content-Type')
216
+ if (contentType) headers.set('Content-Type', contentType)
217
+ if (streamed) headers.set('Cache-Control', 'no-cache')
218
+ if (!upstream.ok || !upstream.body) {
219
+ release()
220
+ return new Response(upstream.body, { status: upstream.status, headers })
221
+ }
222
+
223
+ // The metering branch reads to the end even if the editor disconnects, so the request is
224
+ // still charged for what the upstream generated.
225
+ const [answer, metered] = upstream.body.tee()
226
+ const settle = async () => {
227
+ const tokens = await meteredUsage(metered, streamed)
228
+ // An upstream that reports no usage leaves the request uncharged, so operators hear of it.
229
+ if (!tokens)
230
+ throw new Error(`The upstream reported no usage for ${model.id}; not charged`)
231
+ await usage.record({
232
+ id: crypto.randomUUID(),
233
+ workspaceId: claims.workspaceId,
234
+ userId: claims.sub,
235
+ modelId: model.id,
236
+ inputTokens: tokens.inputTokens,
237
+ outputTokens: tokens.outputTokens,
238
+ credits: creditsFor(model, tokens),
239
+ createdAt: now()
240
+ })
241
+ }
242
+ const settled = settle().catch(reportBackgroundError).finally(release)
243
+ services.waitUntil?.(settled)
244
+ // The answer ends once its charge is recorded, so a wallet read after it includes the charge.
245
+ const charged = answer.pipeThrough(new TransformStream({ flush: () => settled }))
246
+ return new Response(charged, { status: upstream.status, headers })
247
+ }
248
+ )
249
+ }
250
+
251
+ export type AIRelayApp = ReturnType<typeof createAIRelayApp>