@open-pencil/cloud 0.0.0-stage → 0.17.0-beta.1

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,583 @@
1
+ import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'
2
+ import type { CloudServerConfig } from '#cloud/server/config'
3
+ import type { CloudDatabase } from '#cloud/server/db'
4
+ import { createUserPictures, providerPictures } from '#cloud/server/pictures'
5
+ import { passkey } from '@better-auth/passkey'
6
+ import { APIError, betterAuth } from 'better-auth'
7
+ import { getMigrations } from 'better-auth/db/migration'
8
+ import {
9
+ admin,
10
+ bearer,
11
+ captcha,
12
+ deviceAuthorization,
13
+ haveIBeenPwned,
14
+ twoFactor
15
+ } from 'better-auth/plugins'
16
+ import type { Kysely } from 'kysely'
17
+
18
+ import { accountActivity, createSignInActivity } from './activity'
19
+ import type { CloudAuthAdapter } from './adapter'
20
+ import type { AuthenticationEmailService } from './email'
21
+ import { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'
22
+ import { createMFAAssuranceService } from './mfa-assurance'
23
+ import { APPLE_AUDIENCE, socialProviders } from './social-providers'
24
+
25
+ const BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'
26
+ const ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60
27
+
28
+ async function recordResponseAssurance(
29
+ response: Response,
30
+ method: 'totp' | 'recovery-code' | 'passkey',
31
+ database: Kysely<CloudDatabase>,
32
+ assurance: ReturnType<typeof createMFAAssuranceService>
33
+ ): Promise<void> {
34
+ const signedToken = response.headers.get('set-auth-token')
35
+ const token = signedToken?.split('.', 1)[0]
36
+ if (!token) return
37
+ const session = await database
38
+ .selectFrom('session')
39
+ .select(['id', 'userId'])
40
+ .where('token', '=', token)
41
+ .executeTakeFirst()
42
+ if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })
43
+ }
44
+
45
+ async function verifySecondFactor(
46
+ auth: { handler(request: Request): Promise<Response> },
47
+ config: CloudServerConfig,
48
+ database: Kysely<CloudDatabase>,
49
+ assurance: ReturnType<typeof createMFAAssuranceService>,
50
+ headers: Headers,
51
+ code: string,
52
+ method: 'totp' | 'recovery-code',
53
+ /** The two-step plugin's endpoint that checks this kind of code. */
54
+ endpoint: { path: string }
55
+ ): Promise<Response> {
56
+ const response = await auth.handler(
57
+ new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
58
+ method: 'POST',
59
+ headers: new Headers({
60
+ ...Object.fromEntries(headers),
61
+ 'Content-Type': 'application/json'
62
+ }),
63
+ body: JSON.stringify({ code, trustDevice: false })
64
+ })
65
+ )
66
+ if (!response.ok) throw APIError.fromStatus(response.status as 401)
67
+ await recordResponseAssurance(response, method, database, assurance)
68
+ return response
69
+ }
70
+
71
+ export type CloudAuthRuntimeOptions = {
72
+ email?: AuthenticationEmailService
73
+ runInBackground?: (promise: Promise<unknown>) => void
74
+ /**
75
+ * Whether Better Auth checks the database schema when it starts. Runtimes that start it for
76
+ * every request turn this off; `migrateCloudDatabase` has already checked the recorded version.
77
+ */
78
+ validateSchema?: boolean
79
+ }
80
+
81
+ export function createBetterAuthAdapter(
82
+ config: CloudServerConfig,
83
+ database: Kysely<CloudDatabase>,
84
+ enrollment: EnrollmentService = createEnrollmentService(database),
85
+ runtime: CloudAuthRuntimeOptions = {}
86
+ ): CloudAuthAdapter {
87
+ const authenticationEmail = runtime.email
88
+ const assurance = createMFAAssuranceService(database, config)
89
+ const activity = createSignInActivity(database, authenticationEmail)
90
+ // A new address is confirmed through a link sent to it, so changing one needs email delivery.
91
+ const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)
92
+ // The plugins are built first, so the options below name their endpoints by the paths they declare.
93
+ const twoStep = twoFactor({
94
+ issuer: 'OpenPencil Cloud',
95
+ trustDeviceMaxAge: config.mfaTrustedDeviceDays * 24 * 60 * 60,
96
+ allowPasswordless: true,
97
+ totpOptions: { disable: !config.totpEnabled, allowPasswordless: true },
98
+ backupCodeOptions: {
99
+ disable: !config.totpEnabled || !config.recoveryCodesEnabled,
100
+ storeBackupCodes: 'encrypted'
101
+ }
102
+ })
103
+ const passkeys = passkey({
104
+ rpID: new URL(config.publicURL).hostname,
105
+ rpName: config.passkeyRPName,
106
+ origin: new URL(config.publicURL).origin
107
+ })
108
+ const devices = deviceAuthorization({
109
+ verificationUri: new URL('/auth/device', config.publicURL).href,
110
+ validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
111
+ })
112
+ const administration = admin()
113
+ const auth = betterAuth({
114
+ appName: 'OpenPencil Cloud',
115
+ baseURL: config.publicURL,
116
+ basePath: AUTH_BASE_PATH,
117
+ // Clients never reach Better Auth's own administration, which `/api/admin` replaces with MFA,
118
+ // origin, last-administrator, and audit checks, nor the two endpoints Cloud's policy manages
119
+ // through its account routes; the server still calls them itself.
120
+ disabledPaths: [
121
+ ...Object.values(administration.endpoints).map((endpoint) => endpoint.path),
122
+ passkeys.endpoints.deletePasskey.path,
123
+ twoStep.endpoints.disableTwoFactor.path
124
+ ],
125
+ secret: config.authSecret,
126
+ database: {
127
+ db: database,
128
+ type: 'postgres',
129
+ casing: 'camel',
130
+ transaction: true
131
+ },
132
+ account: {
133
+ accountLinking: {
134
+ enabled: true,
135
+ disableImplicitLinking: false,
136
+ trustedProviders: ['google', 'apple'],
137
+ allowDifferentEmails: false,
138
+ allowUnlinkingAll: false,
139
+ requireLocalEmailVerified: true
140
+ }
141
+ },
142
+ session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },
143
+ advanced: {
144
+ database: { generateId: 'uuid', validateSchema: runtime.validateSchema },
145
+ ipAddress: {
146
+ ipAddressHeaders: config.authTrustedIPHeaders,
147
+ trustedProxies: config.authTrustedProxies
148
+ },
149
+ ...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})
150
+ },
151
+ rateLimit: {
152
+ enabled: true,
153
+ storage: 'database',
154
+ window: 60,
155
+ max: 100,
156
+ customRules: {
157
+ [devices.endpoints.deviceCode.path]: { window: 60, max: 10 },
158
+ [devices.endpoints.deviceToken.path]: { window: 60, max: 60 },
159
+ [devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },
160
+ [devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },
161
+ [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
162
+ [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },
163
+ [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },
164
+ [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
165
+ }
166
+ },
167
+ emailAndPassword: config.emailPasswordEnabled
168
+ ? {
169
+ enabled: true,
170
+ disableSignUp: !config.emailPasswordSignUpEnabled,
171
+ requireEmailVerification: true,
172
+ minPasswordLength: config.emailPasswordMinimumLength,
173
+ maxPasswordLength: config.emailPasswordMaximumLength,
174
+ autoSignIn: false,
175
+ resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,
176
+ revokeSessionsOnPasswordReset: true,
177
+ sendResetPassword: authenticationEmail
178
+ ? ({ user, url, token }) =>
179
+ authenticationEmail.sendPasswordReset({
180
+ email: user.email,
181
+ name: user.name,
182
+ url,
183
+ token
184
+ })
185
+ : undefined,
186
+ onPasswordReset: authenticationEmail
187
+ ? ({ user }) =>
188
+ authenticationEmail.sendPasswordChanged({
189
+ email: user.email,
190
+ name: user.name,
191
+ userId: user.id,
192
+ url: config.publicURL
193
+ })
194
+ : undefined
195
+ }
196
+ : undefined,
197
+ emailVerification:
198
+ config.emailPasswordEnabled && authenticationEmail
199
+ ? {
200
+ expiresIn: config.emailVerificationExpiresIn,
201
+ sendOnSignUp: true,
202
+ // Signing in unverified only says so; people ask for another link with Send again.
203
+ sendOnSignIn: false,
204
+ autoSignInAfterVerification: true,
205
+ // A change of address sends the link to the new address as `user.email`, on the
206
+ // account it already confirmed; a new account has not confirmed one yet. This runs
207
+ // inside sign-up's transaction, so it must not query the database itself.
208
+ sendVerificationEmail: ({ user, url, token }) =>
209
+ authenticationEmail.sendVerification({
210
+ email: user.email,
211
+ name: user.name,
212
+ url,
213
+ token,
214
+ purpose: user.emailVerified ? 'change' : 'account'
215
+ }),
216
+ afterEmailVerification: async (user) => {
217
+ await enrollment.followEmailChange(user.id, user.email)
218
+ if (config.enrollmentMode === 'approval') {
219
+ await enrollment.request({ email: user.email, name: user.name })
220
+ }
221
+ await enrollment.bindApprovedUser(user.email, user.id)
222
+ }
223
+ }
224
+ : undefined,
225
+ user: {
226
+ changeEmail: { enabled: emailChangeAvailable },
227
+ validateUserInfo: ({ source }) => {
228
+ if (source.action === 'create-user' && config.enrollmentMode === 'closed') {
229
+ return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }
230
+ }
231
+ return undefined
232
+ }
233
+ },
234
+ databaseHooks: {
235
+ user: {
236
+ create: {
237
+ after: async (user) => {
238
+ if (!user.emailVerified) return
239
+ if (config.enrollmentMode === 'approval') {
240
+ await enrollment.request({ email: user.email, name: user.name })
241
+ }
242
+ await enrollment.bindApprovedUser(user.email, user.id)
243
+ }
244
+ }
245
+ }
246
+ },
247
+ plugins: [
248
+ ...(config.captchaProvider && config.captchaSecretKey
249
+ ? [
250
+ captcha({
251
+ provider: config.captchaProvider,
252
+ secretKey: config.captchaSecretKey,
253
+ allowedHostnames: config.captchaAllowedHostnames,
254
+ endpoints: [
255
+ CORE_AUTH_PATHS.signUpEmail,
256
+ CORE_AUTH_PATHS.signInEmail,
257
+ CORE_AUTH_PATHS.requestPasswordReset
258
+ ]
259
+ })
260
+ ]
261
+ : []),
262
+ ...(config.compromisedPasswordCheck ? [haveIBeenPwned()] : []),
263
+ twoStep,
264
+ passkeys,
265
+ administration,
266
+ // Device authorization returns opaque database session tokens, not signed cookies.
267
+ bearer(),
268
+ devices,
269
+ // After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.
270
+ accountActivity(
271
+ activity,
272
+ { twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },
273
+ (user) => notifyTwoStep(user, 'passkey-added')
274
+ ),
275
+ providerPictures(createUserPictures(database, { publicURL: config.publicURL }))
276
+ ],
277
+ socialProviders: socialProviders(config),
278
+ trustedOrigins: [
279
+ config.publicURL,
280
+ ...config.trustedOrigins,
281
+ ...(config.appleClientId ? [APPLE_AUDIENCE] : [])
282
+ ]
283
+ })
284
+
285
+ // Administrators are granted only through the `admin` command or by another administrator.
286
+ const deploymentRole = (user: { id: string; role?: string | null }) =>
287
+ user.role === 'admin' ? ('admin' as const) : ('user' as const)
288
+
289
+ const resolveIdentity = async (headers: Headers) => {
290
+ const session = await auth.api.getSession({ headers })
291
+ if (!session) return null
292
+ return {
293
+ userId: session.user.id,
294
+ email: session.user.email,
295
+ name: session.user.name,
296
+ image: session.user.image ?? null,
297
+ deploymentRole: deploymentRole(session.user)
298
+ }
299
+ }
300
+
301
+ /** The signed-in person, read past the cookie cache, for changes about their own account. */
302
+ const currentSession = (headers: Headers) =>
303
+ auth.api.getSession({ headers, query: { disableCookieCache: true } })
304
+
305
+ /** The current session when it signed in recently enough to change how the account is reached. */
306
+ async function freshSession(headers: Headers) {
307
+ const session = await currentSession(headers)
308
+ const createdAt = session?.session.createdAt
309
+ if (
310
+ !session ||
311
+ !createdAt ||
312
+ Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000
313
+ ) {
314
+ throw APIError.from('FORBIDDEN', {
315
+ code: 'SESSION_NOT_FRESH',
316
+ message: 'Session is not fresh'
317
+ })
318
+ }
319
+ return session
320
+ }
321
+
322
+ async function notifyTwoStep(
323
+ user: { id: string; email: string; name: string },
324
+ change: Parameters<AuthenticationEmailService['sendTwoStepChanged']>[0]['change']
325
+ ): Promise<void> {
326
+ await authenticationEmail?.sendTwoStepChanged({
327
+ email: user.email,
328
+ name: user.name,
329
+ userId: user.id,
330
+ change
331
+ })
332
+ }
333
+
334
+ /** The signed-in person while their account may use the server, which awaiting approval it may not. */
335
+ async function resolveSession(headers: Headers) {
336
+ const identity = await resolveIdentity(headers)
337
+ if (!identity) return null
338
+ if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {
339
+ return null
340
+ }
341
+ return identity
342
+ }
343
+
344
+ /**
345
+ * The endpoints that read or change an account, which only an account that may use the server
346
+ * reaches; one awaiting approval still signs in and out. Better Auth checks the session inside
347
+ * most of these endpoints rather than declaring it, so they are listed by their own objects.
348
+ */
349
+ const activeAccountPaths = new Set(
350
+ [
351
+ auth.api.generatePasskeyRegistrationOptions,
352
+ auth.api.listPasskeys,
353
+ auth.api.updatePasskey,
354
+ auth.api.verifyPasskeyRegistration,
355
+ auth.api.enableTwoFactor,
356
+ auth.api.generateBackupCodes,
357
+ auth.api.getTOTPURI,
358
+ auth.api.accountInfo,
359
+ auth.api.changeEmail,
360
+ auth.api.changePassword,
361
+ auth.api.deleteUser,
362
+ auth.api.getAccessToken,
363
+ auth.api.linkSocialAccount,
364
+ auth.api.listUserAccounts,
365
+ auth.api.listSessions,
366
+ auth.api.refreshToken,
367
+ auth.api.revokeOtherSessions,
368
+ auth.api.revokeSession,
369
+ auth.api.revokeSessions,
370
+ auth.api.unlinkAccount
371
+ ].map((endpoint) => authRequestPath(endpoint.path))
372
+ )
373
+ /** The second factor a request proves, by the endpoint it is for. */
374
+ const assuranceMethods = new Map<string, 'totp' | 'recovery-code' | 'passkey'>([
375
+ [authRequestPath(twoStep.endpoints.verifyTOTP.path), 'totp'],
376
+ [authRequestPath(twoStep.endpoints.verifyBackupCode.path), 'recovery-code'],
377
+ [authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path), 'passkey']
378
+ ])
379
+
380
+ return {
381
+ handler: async (request) => {
382
+ const path = new URL(request.url).pathname
383
+ if (activeAccountPaths.has(path) && !(await resolveSession(request.headers))) {
384
+ return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })
385
+ }
386
+ const response = await auth.handler(request)
387
+ const method = assuranceMethods.get(path)
388
+ if (response.ok && method)
389
+ await recordResponseAssurance(response, method, database, assurance)
390
+ return response
391
+ },
392
+ resolveIdentity,
393
+ resolveSession,
394
+ async listAuthenticationMethods(headers) {
395
+ const accounts = await auth.api.listUserAccounts({ headers })
396
+ return accounts.map((account) => ({
397
+ id: account.id,
398
+ providerId: account.providerId,
399
+ createdAt: account.createdAt
400
+ }))
401
+ },
402
+ async changePassword(headers, input) {
403
+ const session = authenticationEmail ? await auth.api.getSession({ headers }) : null
404
+ await auth.api.changePassword({
405
+ headers,
406
+ body: { ...input, revokeOtherSessions: false }
407
+ })
408
+ await auth.api.revokeOtherSessions({ headers })
409
+ if (authenticationEmail && session) {
410
+ await authenticationEmail.sendPasswordChanged({
411
+ email: session.user.email,
412
+ name: session.user.name,
413
+ userId: session.user.id,
414
+ url: config.publicURL
415
+ })
416
+ }
417
+ },
418
+ async startSocialLink(headers, input) {
419
+ await freshSession(headers)
420
+ const response = await auth.api.linkSocialAccount({
421
+ headers,
422
+ body: {
423
+ provider: input.provider,
424
+ callbackURL: input.callbackURL,
425
+ errorCallbackURL: input.callbackURL,
426
+ disableRedirect: true
427
+ }
428
+ })
429
+ return response.url
430
+ },
431
+ async unlinkAuthenticationMethod(headers, methodId) {
432
+ await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })
433
+ },
434
+ async banUser(headers, userId, reason) {
435
+ await auth.api.banUser({ headers, body: { userId, banReason: reason } })
436
+ },
437
+ async unbanUser(headers, userId) {
438
+ await auth.api.unbanUser({ headers, body: { userId } })
439
+ },
440
+ async revokeUserSessions(headers, userId) {
441
+ await auth.api.revokeUserSessions({ headers, body: { userId } })
442
+ },
443
+ async setRole(headers, userId, role) {
444
+ await auth.api.setRole({ headers, body: { userId, role } })
445
+ },
446
+ async mfaStatus(headers) {
447
+ const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })
448
+ if (!session) return null
449
+ const passkeys = await auth.api.listPasskeys({ headers })
450
+ return assurance.status({
451
+ sessionId: session.session.id,
452
+ userId: session.user.id,
453
+ deploymentRole: deploymentRole(session.user),
454
+ twoFactorEnabled:
455
+ 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true,
456
+ passkeyCount: passkeys.length
457
+ })
458
+ },
459
+ async enableTOTP(headers, password) {
460
+ const response = await auth.api.enableTwoFactor({
461
+ headers,
462
+ body: { password, method: 'totp' }
463
+ })
464
+ if (response.method !== 'totp') throw new Error('TOTP setup was unavailable')
465
+ return { totpURI: response.totpURI, backupCodes: response.backupCodes }
466
+ },
467
+ async verifyTOTP(headers, code) {
468
+ const before = await currentSession(headers)
469
+ const response = await verifySecondFactor(
470
+ auth,
471
+ config,
472
+ database,
473
+ assurance,
474
+ headers,
475
+ code,
476
+ 'totp',
477
+ twoStep.endpoints.verifyTOTP
478
+ )
479
+ // The first code from a new authenticator is what turns it on.
480
+ if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {
481
+ await notifyTwoStep(before.user, 'authenticator-on')
482
+ }
483
+ return response
484
+ },
485
+ async verifyRecoveryCode(headers, code) {
486
+ return verifySecondFactor(
487
+ auth,
488
+ config,
489
+ database,
490
+ assurance,
491
+ headers,
492
+ code,
493
+ 'recovery-code',
494
+ twoStep.endpoints.verifyBackupCode
495
+ )
496
+ },
497
+ async generateRecoveryCodes(headers, password) {
498
+ return (await auth.api.generateBackupCodes({ headers, body: { password } })).backupCodes
499
+ },
500
+ async disableTOTP(headers, password) {
501
+ await auth.api.disableTwoFactor({ headers, body: { password } })
502
+ const session = await currentSession(headers)
503
+ if (session) await notifyTwoStep(session.user, 'authenticator-off')
504
+ },
505
+ async listPasskeys(headers) {
506
+ return (await auth.api.listPasskeys({ headers })).map((item) => ({
507
+ id: item.id,
508
+ name: item.name,
509
+ createdAt: item.createdAt
510
+ }))
511
+ },
512
+ async deletePasskey(headers, id) {
513
+ await auth.api.deletePasskey({ headers, body: { id } })
514
+ const session = await currentSession(headers)
515
+ if (session) await notifyTwoStep(session.user, 'passkey-removed')
516
+ },
517
+ emailChangeAvailable,
518
+ async profile(headers) {
519
+ const session = await currentSession(headers)
520
+ if (!session) return null
521
+ return {
522
+ id: session.user.id,
523
+ name: session.user.name,
524
+ email: session.user.email,
525
+ image: session.user.image ?? null,
526
+ createdAt: new Date(session.user.createdAt)
527
+ }
528
+ },
529
+ async updateProfile(headers, input) {
530
+ await auth.api.updateUser({ headers, body: { name: input.name } })
531
+ },
532
+ async changeEmail(headers, input) {
533
+ const session = await freshSession(headers)
534
+ if (session.user.email === input.newEmail) {
535
+ throw APIError.from('BAD_REQUEST', {
536
+ code: 'EMAIL_UNCHANGED',
537
+ message: 'Email is the same'
538
+ })
539
+ }
540
+ await auth.api.changeEmail({ headers, body: input })
541
+ await authenticationEmail?.sendEmailChangeRequested({
542
+ email: session.user.email,
543
+ name: session.user.name,
544
+ userId: session.user.id,
545
+ newEmail: input.newEmail
546
+ })
547
+ },
548
+ async sessions(headers) {
549
+ const session = await currentSession(headers)
550
+ if (!session) return null
551
+ return activity.sessions(session.user.id, session.session.id)
552
+ },
553
+ async revokeSession(headers, sessionId) {
554
+ const session = await currentSession(headers)
555
+ if (!session) throw APIError.fromStatus('UNAUTHORIZED')
556
+ if (session.session.id === sessionId) {
557
+ throw APIError.from('BAD_REQUEST', {
558
+ code: 'CURRENT_SESSION',
559
+ message: 'Sign out to end this session'
560
+ })
561
+ }
562
+ const target = await database
563
+ .selectFrom('session')
564
+ .select('token')
565
+ .where('id', '=', sessionId)
566
+ .where('userId', '=', session.user.id)
567
+ .executeTakeFirst()
568
+ if (target) await auth.api.revokeSession({ headers, body: { token: target.token } })
569
+ },
570
+ async revokeOtherSessions(headers) {
571
+ await auth.api.revokeOtherSessions({ headers })
572
+ },
573
+ async signIns(headers) {
574
+ const session = await currentSession(headers)
575
+ return session ? activity.signIns(session.user.id) : null
576
+ },
577
+ schemaVersion: BETTER_AUTH_SCHEMA_VERSION,
578
+ async migrate() {
579
+ const migrations = await getMigrations(auth.options)
580
+ await migrations.runMigrations()
581
+ }
582
+ }
583
+ }
@@ -0,0 +1,17 @@
1
+ export { createAccountAuthenticationService, type AccountAuthenticationService } from './account'
2
+ export { createSignInActivity, type SignInActivity } from './activity'
3
+ export type { CloudAuthAdapter } from './adapter'
4
+ export { createAuthenticationEmailService, type AuthenticationEmailService } from './email'
5
+ export { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath, isAuthEndpoint } from './endpoints'
6
+ export { createMFAAssuranceService, type MFAAssuranceService } from './mfa-assurance'
7
+ export { createCloudAuthenticationRuntime } from './runtime'
8
+ export { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
9
+ export {
10
+ createCloudIdentityResolver,
11
+ createCloudSessionResolver,
12
+ type CloudActor,
13
+ type CloudIdentityResolver,
14
+ type CloudSessionResolver
15
+ } from './session'
16
+ export type { CloudIdentity } from './adapter'
17
+ export { workspaceAccessControl, workspaceRoles, workspaceStatements } from './workspace-access'
@@ -0,0 +1,55 @@
1
+ import type { CloudMFAStatus } from '#cloud/server/auth/adapter'
2
+ import type { CloudServerConfig } from '#cloud/server/config'
3
+ import type { CloudDatabase } from '#cloud/server/db'
4
+ import type { Kysely } from 'kysely'
5
+
6
+ const ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000
7
+
8
+ export function createMFAAssuranceService(
9
+ database: Kysely<CloudDatabase>,
10
+ config: CloudServerConfig
11
+ ) {
12
+ return {
13
+ async record(input: {
14
+ sessionId: string
15
+ userId: string
16
+ method: 'totp' | 'recovery-code' | 'passkey'
17
+ }): Promise<void> {
18
+ await database
19
+ .insertInto('mfaAssurance')
20
+ .values({ ...input, verifiedAt: new Date() })
21
+ .onConflict((conflict) =>
22
+ conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })
23
+ )
24
+ .execute()
25
+ },
26
+ async status(input: {
27
+ sessionId: string
28
+ userId: string
29
+ deploymentRole?: 'user' | 'admin'
30
+ twoFactorEnabled: boolean
31
+ passkeyCount: number
32
+ }): Promise<CloudMFAStatus> {
33
+ const assurance = await database
34
+ .selectFrom('mfaAssurance')
35
+ .select('verifiedAt')
36
+ .where('sessionId', '=', input.sessionId)
37
+ .where('userId', '=', input.userId)
38
+ .executeTakeFirst()
39
+ const assured = Boolean(
40
+ assurance && new Date(assurance.verifiedAt).getTime() > Date.now() - ASSURANCE_MAX_AGE_MS
41
+ )
42
+ return {
43
+ required: config.deploymentAdminMFARequired && input.deploymentRole === 'admin' && !assured,
44
+ enabled: input.twoFactorEnabled || input.passkeyCount > 0,
45
+ totpEnabled: input.twoFactorEnabled,
46
+ assured,
47
+ totpAvailable: config.totpEnabled,
48
+ passkeysAvailable: config.passkeysEnabled,
49
+ recoveryCodesAvailable: config.totpEnabled && config.recoveryCodesEnabled
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ export type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>
@@ -0,0 +1,26 @@
1
+ import { createEnrollmentService } from '#cloud/admin/enrollment/service'
2
+ import type { CloudServerConfig } from '#cloud/server/config'
3
+ import type { CloudDatabase } from '#cloud/server/db'
4
+ import type { TransactionalEmailService } from '#cloud/server/email'
5
+ import type { Kysely } from 'kysely'
6
+
7
+ import { createAuthenticationEmailService } from './email'
8
+ import { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
9
+
10
+ export function createCloudAuthenticationRuntime(
11
+ config: CloudServerConfig,
12
+ database: Kysely<CloudDatabase>,
13
+ email: TransactionalEmailService,
14
+ options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}
15
+ ) {
16
+ const enrollment = createEnrollmentService(database, {
17
+ publicURL: config.publicURL,
18
+ adminRecipients: config.enrollmentAdminNotificationEmails,
19
+ email
20
+ })
21
+ const auth = createBetterAuthAdapter(config, database, enrollment, {
22
+ email: createAuthenticationEmailService(email, config.publicURL),
23
+ ...options
24
+ })
25
+ return { auth, enrollment }
26
+ }