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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/client.d.ts +560 -93
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +1101 -186
  4. package/dist/client.js.map +1 -1
  5. package/dist/contract.d.ts +2 -2
  6. package/dist/contract.js +2 -2
  7. package/dist/contract2.js +390 -44
  8. package/dist/contract2.js.map +1 -1
  9. package/dist/email.d.ts +366 -3
  10. package/dist/email.d.ts.map +1 -1
  11. package/dist/email.js +1403 -556
  12. package/dist/email.js.map +1 -1
  13. package/dist/errors.js +16 -3
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +878 -37
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index2.d.ts +12 -2
  18. package/dist/index2.d.ts.map +1 -1
  19. package/dist/listen.mjs +589 -128
  20. package/dist/listen.mjs.map +1 -1
  21. package/dist/runtime-cloudflare.d.ts +4 -0
  22. package/dist/runtime-cloudflare.d.ts.map +1 -1
  23. package/dist/runtime-cloudflare.js +8689 -6324
  24. package/dist/runtime-cloudflare.js.map +1 -1
  25. package/dist/runtime-node.d.mts +10098 -5401
  26. package/dist/runtime-node.d.mts.map +1 -1
  27. package/dist/server.d.ts +14078 -7909
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +11723 -9412
  30. package/dist/server.js.map +1 -1
  31. package/dist/server.mjs +10658 -8649
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/server2.mjs +79 -57
  34. package/dist/server2.mjs.map +1 -1
  35. package/package.json +13 -4
  36. package/src/admin/api/routes.ts +263 -190
  37. package/src/admin/audit/service.ts +9 -1
  38. package/src/admin/bootstrap.ts +86 -0
  39. package/src/admin/documents/service.ts +119 -4
  40. package/src/admin/email/service.ts +2 -1
  41. package/src/admin/enrollment/email.ts +17 -3
  42. package/src/admin/enrollment/service.ts +71 -10
  43. package/src/admin/errors.ts +5 -0
  44. package/src/admin/index.ts +1 -0
  45. package/src/admin/reports/service.ts +9 -3
  46. package/src/admin/schema.ts +6 -5
  47. package/src/admin/users/service.ts +173 -16
  48. package/src/client/api.ts +29 -2
  49. package/src/client/comments.ts +205 -0
  50. package/src/client/device-authorization.ts +4 -20
  51. package/src/client/discovery.ts +4 -2
  52. package/src/client/files/archive.ts +60 -0
  53. package/src/client/files/checksum.ts +7 -0
  54. package/src/client/files/download.ts +122 -0
  55. package/src/client/files/images.ts +89 -0
  56. package/src/client/files/index.ts +15 -0
  57. package/src/client/files/objects.ts +173 -0
  58. package/src/client/files/save.ts +79 -0
  59. package/src/client/index.ts +3 -6
  60. package/src/client/portal/account.ts +20 -2
  61. package/src/client/portal/administration.ts +52 -5
  62. package/src/client/portal/request.ts +4 -2
  63. package/src/client/tour.ts +44 -0
  64. package/src/client/versions.ts +7 -1
  65. package/src/contract/account.ts +61 -11
  66. package/src/contract/admin/index.ts +48 -3
  67. package/src/contract/billing.ts +73 -4
  68. package/src/contract/comments.ts +223 -0
  69. package/src/contract/discovery.ts +47 -19
  70. package/src/contract/index.ts +10 -0
  71. package/src/contract/links.ts +5 -0
  72. package/src/contract/relay.ts +3 -1
  73. package/src/contract/services.ts +44 -4
  74. package/src/contract/workspaces.ts +5 -0
  75. package/src/email/locales/ar.json +28 -0
  76. package/src/email/locales/de.json +28 -0
  77. package/src/email/locales/es.json +28 -0
  78. package/src/email/locales/fr.json +28 -0
  79. package/src/email/locales/it.json +28 -0
  80. package/src/email/locales/ja.json +28 -0
  81. package/src/email/locales/pl.json +28 -0
  82. package/src/email/locales/pt-br.json +28 -0
  83. package/src/email/locales/ru.json +28 -0
  84. package/src/email/locales/zh-cn.json +28 -0
  85. package/src/email/messages.ts +35 -0
  86. package/src/email/render.ts +18 -0
  87. package/src/email/samples.ts +28 -1
  88. package/src/email/schema.ts +29 -3
  89. package/src/email/templates/BrandEmail.vue +3 -1
  90. package/src/email/templates/CommentNotification.vue +39 -0
  91. package/src/email/templates/EnrollmentInvitation.vue +53 -0
  92. package/src/email/templates/TwoStepChanged.vue +17 -2
  93. package/src/email/templates/brand.ts +6 -0
  94. package/src/errors/posthog.ts +28 -4
  95. package/src/runtime/cloudflare/email.ts +2 -0
  96. package/src/runtime/cloudflare/relay/index.ts +21 -6
  97. package/src/runtime/cloudflare/worker.ts +6 -0
  98. package/src/runtime/cloudflare/xml.ts +12 -0
  99. package/src/runtime/node/admin.ts +51 -47
  100. package/src/runtime/node/email/runtime.ts +1 -0
  101. package/src/runtime/node/email/transport.ts +1 -0
  102. package/src/runtime/node/server.ts +8 -2
  103. package/src/runtime/posthog/errors.ts +3 -1
  104. package/src/server/account/actions.ts +3 -1
  105. package/src/server/account/deletion.ts +38 -4
  106. package/src/server/account/routes.ts +67 -46
  107. package/src/server/account/tokens.ts +3 -3
  108. package/src/server/api/router.ts +22 -7
  109. package/src/server/app/checks.ts +6 -1
  110. package/src/server/app/cors.ts +44 -0
  111. package/src/server/app/index.ts +76 -76
  112. package/src/server/app/routes.ts +14 -5
  113. package/src/server/app/services.ts +49 -15
  114. package/src/server/auth/access-control.ts +13 -8
  115. package/src/server/auth/account.ts +13 -12
  116. package/src/server/auth/activity.ts +7 -2
  117. package/src/server/auth/adapter.ts +16 -3
  118. package/src/server/auth/email.ts +29 -17
  119. package/src/server/auth/endpoints.ts +4 -0
  120. package/src/server/auth/factory.ts +83 -64
  121. package/src/server/auth/index.ts +1 -1
  122. package/src/server/auth/methods.ts +162 -0
  123. package/src/server/auth/mfa-assurance.ts +147 -10
  124. package/src/server/auth/rate-limit.ts +31 -0
  125. package/src/server/auth/runtime.ts +19 -5
  126. package/src/server/auth/social-providers.ts +70 -24
  127. package/src/server/billing/index.ts +2 -0
  128. package/src/server/billing/notify.ts +55 -0
  129. package/src/server/billing/seats.ts +17 -0
  130. package/src/server/billing/tokens.ts +1 -1
  131. package/src/server/cleanup/documents.ts +5 -2
  132. package/src/server/cleanup/revisions.ts +6 -3
  133. package/src/server/cleanup/uploads.ts +2 -1
  134. package/src/server/collaboration/relay/connection.ts +7 -2
  135. package/src/server/collaboration/relay/hub.ts +55 -24
  136. package/src/server/collaboration/routes.ts +8 -5
  137. package/src/server/comments/index.ts +9 -0
  138. package/src/server/comments/notify.ts +277 -0
  139. package/src/server/comments/routes.ts +352 -0
  140. package/src/server/comments/rows.ts +249 -0
  141. package/src/server/comments/service.ts +570 -0
  142. package/src/server/community/routes.ts +6 -6
  143. package/src/server/config/deployment.ts +19 -6
  144. package/src/server/config/index.ts +1 -1
  145. package/src/server/config/public.ts +19 -6
  146. package/src/server/config/schema.ts +14 -2
  147. package/src/server/config/toml/schema.ts +27 -4
  148. package/src/server/db/index.ts +2 -1
  149. package/src/server/db/migrate.ts +21 -1
  150. package/src/server/db/migrations/015_comments.ts +57 -0
  151. package/src/server/db/migrations/016_comment_notifications.ts +76 -0
  152. package/src/server/db/migrations/017_invitation_emails.ts +19 -0
  153. package/src/server/db/migrations/018_enrollment_source.ts +17 -0
  154. package/src/server/db/tables.ts +92 -2
  155. package/src/server/documents/access.ts +17 -0
  156. package/src/server/documents/images.ts +6 -1
  157. package/src/server/documents/routes.ts +12 -12
  158. package/src/server/documents/service.ts +19 -5
  159. package/src/server/documents/summary.ts +15 -0
  160. package/src/server/documents/versions/routes.ts +7 -8
  161. package/src/server/documents/versions/service.ts +5 -2
  162. package/src/server/email/service.ts +8 -2
  163. package/src/server/email/types.ts +1 -0
  164. package/src/server/errors/index.ts +48 -3
  165. package/src/server/index.ts +15 -1
  166. package/src/server/internal/routes.ts +8 -2
  167. package/src/server/internal/service.ts +10 -0
  168. package/src/server/invitations/budget.ts +3 -1
  169. package/src/server/invitations/index.ts +1 -0
  170. package/src/server/invitations/links.ts +6 -0
  171. package/src/server/pictures/service.ts +3 -1
  172. package/src/server/policy/workspace.ts +5 -2
  173. package/src/server/reports/routes.ts +2 -2
  174. package/src/server/reports/service.ts +3 -1
  175. package/src/server/services/routes.ts +2 -2
  176. package/src/server/sharing/capabilities/service.ts +1 -1
  177. package/src/server/sharing/document-routes.ts +3 -3
  178. package/src/server/sharing/invitations/service.ts +3 -4
  179. package/src/server/sharing/routes.ts +15 -15
  180. package/src/server/validation.ts +33 -25
  181. package/src/server/workspaces/members.ts +50 -12
  182. package/src/server/workspaces/repository.ts +23 -12
  183. package/src/server/workspaces/routes.ts +8 -8
  184. package/src/services/app.ts +30 -19
  185. package/src/services/config.ts +47 -8
  186. package/src/services/metering.ts +15 -27
  187. package/src/client/billing.ts +0 -80
@@ -4,7 +4,7 @@ export type { CloudAuthAdapter } from './adapter'
4
4
  export { createAuthenticationEmailService, type AuthenticationEmailService } from './email'
5
5
  export { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath, isAuthEndpoint } from './endpoints'
6
6
  export { createMFAAssuranceService, type MFAAssuranceService } from './mfa-assurance'
7
- export { createCloudAuthenticationRuntime } from './runtime'
7
+ export { createCloudAuthenticationRuntime, enrollmentEmailOptions } from './runtime'
8
8
  export { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
9
9
  export {
10
10
  createCloudIdentityResolver,
@@ -0,0 +1,162 @@
1
+ import type { CloudServerConfig } from '#cloud/server/config'
2
+ import type { CloudDatabase } from '#cloud/server/db'
3
+ import { APIError, type BetterAuthOptions } from 'better-auth'
4
+ import { getOAuthState } from 'better-auth/api'
5
+ import type { Kysely, Transaction } from 'kysely'
6
+
7
+ import { configuredSocialProviders } from './social-providers'
8
+
9
+ /**
10
+ * An administrator's removal of a Google or Apple identity is kept as one of Better Auth's
11
+ * verification values: its database hooks read them inside the transaction that would create the
12
+ * account, and the removal writes it in its own, so the two cannot come apart.
13
+ */
14
+ const BLOCK_EXPIRES_AT = new Date(Date.UTC(9999, 11, 31))
15
+ const blockIdentifier = (userId: string, provider: string) =>
16
+ `sign-in-method-block:${userId}:${provider}`
17
+
18
+ /** Better Auth's store of keyed values, as its database hooks are handed it. */
19
+ export type SignInMethodBlockStore = {
20
+ findVerificationValue(identifier: string): Promise<{ value: string } | null>
21
+ deleteVerificationByIdentifier(identifier: string): Promise<void>
22
+ }
23
+
24
+ /**
25
+ * The providers this server signs in with now, `credential` for a password. A method linked before
26
+ * its provider was turned off stays on the account but no longer lets anyone in.
27
+ */
28
+ export function signInProviders(config: CloudServerConfig): ReadonlySet<string> {
29
+ const providers = new Set<string>(configuredSocialProviders(config))
30
+ if (config.emailPasswordEnabled) providers.add('credential')
31
+ return providers
32
+ }
33
+
34
+ /**
35
+ * Whether `method` can come off an account holding `methods`: the account keeps at least one, and,
36
+ * with `providers`, one whose provider is turned on. Taking away a provider that is off changes
37
+ * nothing, so it can always go while another method remains.
38
+ */
39
+ export function canRemoveSignInMethod(
40
+ method: { id: string; providerId: string },
41
+ methods: readonly { id: string; providerId: string }[],
42
+ providers?: ReadonlySet<string>
43
+ ): boolean {
44
+ const counts = (provider: string) => !providers || providers.has(provider)
45
+ const others = methods.filter((candidate) => candidate.id !== method.id)
46
+ if (others.length === 0) return false
47
+ return !counts(method.providerId) || others.some((other) => counts(other.providerId))
48
+ }
49
+
50
+ /** The sign-in method a removal took away: its provider (`credential` for a password). */
51
+ export type RemovedSignInMethod = { provider: string }
52
+
53
+ /**
54
+ * Removes one of an account's sign-in methods, by its row. The account's row is locked first, so
55
+ * its owner unlinking one while an administrator removes another cannot leave it with none. An
56
+ * administrator's removal (`block`) also keeps that Google or Apple identity from linking itself
57
+ * back by the account's email; `also` runs in the same transaction, as their audit entry does.
58
+ * With `providers`, only methods whose provider is turned on count as a way still in.
59
+ */
60
+ export async function removeSignInMethod(
61
+ database: Kysely<CloudDatabase>,
62
+ input: {
63
+ userId: string
64
+ methodId: string
65
+ providers?: ReadonlySet<string>
66
+ block?: boolean
67
+ also?: (transaction: Transaction<CloudDatabase>, provider: string) => Promise<void>
68
+ }
69
+ ): Promise<RemovedSignInMethod> {
70
+ return database.transaction().execute(async (transaction) => {
71
+ await transaction
72
+ .selectFrom('user')
73
+ .select('id')
74
+ .where('id', '=', input.userId)
75
+ .forUpdate()
76
+ .executeTakeFirstOrThrow()
77
+ const methods = await transaction
78
+ .selectFrom('account')
79
+ .select(['id', 'providerId', 'accountId'])
80
+ .where('userId', '=', input.userId)
81
+ .execute()
82
+ const method = methods.find((candidate) => candidate.id === input.methodId)
83
+ if (!method) {
84
+ throw APIError.from('NOT_FOUND', { code: 'ACCOUNT_NOT_FOUND', message: 'No such method' })
85
+ }
86
+ if (!canRemoveSignInMethod(method, methods, input.providers)) {
87
+ // Better Auth's own word, which the account routes already answer for.
88
+ throw APIError.from('BAD_REQUEST', {
89
+ code: 'FAILED_TO_UNLINK_LAST_ACCOUNT',
90
+ message: 'An account keeps at least one way to sign in'
91
+ })
92
+ }
93
+ await transaction.deleteFrom('account').where('id', '=', method.id).execute()
94
+ if (input.block && method.providerId !== 'credential') {
95
+ const identifier = blockIdentifier(input.userId, method.providerId)
96
+ await transaction.deleteFrom('verification').where('identifier', '=', identifier).execute()
97
+ await transaction
98
+ .insertInto('verification')
99
+ .values({
100
+ id: crypto.randomUUID(),
101
+ identifier,
102
+ value: method.accountId,
103
+ expiresAt: BLOCK_EXPIRES_AT,
104
+ createdAt: new Date(),
105
+ updatedAt: new Date()
106
+ })
107
+ .execute()
108
+ }
109
+ await input.also?.(transaction, method.providerId)
110
+ return { provider: method.providerId }
111
+ })
112
+ }
113
+
114
+ /**
115
+ * Whether a sign-in may create `account`: not an identity an administrator removed from that
116
+ * person, unless that person is linking it again from their own security page (`linkingUserId`,
117
+ * which Better Auth carries from the request that started the link).
118
+ */
119
+ export async function signInMethodAllowed(
120
+ store: SignInMethodBlockStore,
121
+ account: { userId: string; providerId: string; accountId: string },
122
+ linkingUserId: () => Promise<string | null>
123
+ ): Promise<boolean> {
124
+ const block = await store.findVerificationValue(
125
+ blockIdentifier(account.userId, account.providerId)
126
+ )
127
+ if (block?.value !== account.accountId) return true
128
+ return (await linkingUserId()) === account.userId
129
+ }
130
+
131
+ /** The person a provider callback links an identity to, when it is a link they started. */
132
+ async function linkingUserId(): Promise<string | null> {
133
+ // Outside a provider callback there is no sign-in state, and nothing is being linked.
134
+ const state = await getOAuthState().catch(() => null)
135
+ return state?.link?.userId ?? null
136
+ }
137
+
138
+ /**
139
+ * Refuses to create an identity an administrator removed, however a sign-in tries to, and lifts
140
+ * the block once its owner has linked it again.
141
+ */
142
+ export const signInMethodHooks: NonNullable<BetterAuthOptions['databaseHooks']> = {
143
+ account: {
144
+ create: {
145
+ async before(account, context) {
146
+ const store = context?.context.internalAdapter
147
+ // `undefined` lets Better Auth create the account as it is; `false` refuses it.
148
+ return store && !(await signInMethodAllowed(store, account, linkingUserId))
149
+ ? false
150
+ : undefined
151
+ },
152
+ async after(account, context) {
153
+ const store = context?.context.internalAdapter
154
+ if (store && (await linkingUserId()) === account.userId) {
155
+ await store.deleteVerificationByIdentifier(
156
+ blockIdentifier(account.userId, account.providerId)
157
+ )
158
+ }
159
+ }
160
+ }
161
+ }
162
+ }
@@ -1,8 +1,9 @@
1
1
  import type { CloudMFAStatus } from '#cloud/server/auth/adapter'
2
2
  import type { CloudServerConfig } from '#cloud/server/config'
3
- import type { CloudDatabase } from '#cloud/server/db'
3
+ import type { CloudDatabase, MFAAssuranceMethod } from '#cloud/server/db'
4
4
  import { APIError } from 'better-auth'
5
5
  import type { Kysely } from 'kysely'
6
+ import * as v from 'valibot'
6
7
 
7
8
  import { authRequestPath } from './endpoints'
8
9
 
@@ -16,7 +17,7 @@ export function createMFAAssuranceService(
16
17
  async record(input: {
17
18
  sessionId: string
18
19
  userId: string
19
- method: 'totp' | 'recovery-code' | 'passkey'
20
+ method: MFAAssuranceMethod
20
21
  }): Promise<void> {
21
22
  await database
22
23
  .insertInto('mfaAssurance')
@@ -26,6 +27,40 @@ export function createMFAAssuranceService(
26
27
  )
27
28
  .execute()
28
29
  },
30
+ /**
31
+ * Whether a session may act as its account. One whose account has an authenticator or a
32
+ * passkey must have proved it, at sign-in or since; a sign-in through a linked account such
33
+ * as Google never asks for it. Unlike `status().assured`, the proof does not age.
34
+ */
35
+ async confirmed(input: {
36
+ sessionId: string
37
+ userId: string
38
+ twoFactorEnabled: boolean
39
+ }): Promise<boolean> {
40
+ const row = await database
41
+ .selectNoFrom((expression) => [
42
+ expression
43
+ .exists(
44
+ expression
45
+ .selectFrom('mfaAssurance')
46
+ .select('mfaAssurance.sessionId')
47
+ .where('mfaAssurance.sessionId', '=', input.sessionId)
48
+ .where('mfaAssurance.userId', '=', input.userId)
49
+ )
50
+ .as('assured'),
51
+ expression
52
+ .exists(
53
+ expression
54
+ .selectFrom('passkey')
55
+ .select('passkey.id')
56
+ .where('passkey.userId', '=', input.userId)
57
+ )
58
+ .as('passkey')
59
+ ])
60
+ .executeTakeFirstOrThrow()
61
+ if (row.assured) return true
62
+ return !input.twoFactorEnabled && !row.passkey
63
+ },
29
64
  async status(input: {
30
65
  sessionId: string
31
66
  userId: string
@@ -57,24 +92,112 @@ export function createMFAAssuranceService(
57
92
 
58
93
  export type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>
59
94
 
60
- /** Records the second step a response just signed in with, against the session it started. */
95
+ /**
96
+ * Records the second step a response just signed in with, against the session it started; false
97
+ * when it started none.
98
+ */
61
99
  export async function recordResponseAssurance(
62
100
  response: Response,
63
- method: 'totp' | 'recovery-code' | 'passkey',
101
+ method: MFAAssuranceMethod,
64
102
  database: Kysely<CloudDatabase>,
65
103
  assurance: MFAAssuranceService
66
- ): Promise<void> {
104
+ ): Promise<boolean> {
67
105
  const signedToken = response.headers.get('set-auth-token')
68
106
  const token = signedToken?.split('.', 1)[0]
69
- if (!token) return
107
+ if (!token) return false
70
108
  const session = await database
71
109
  .selectFrom('session')
72
110
  .select(['id', 'userId'])
73
111
  .where('token', '=', token)
74
112
  .executeTakeFirst()
75
- if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })
113
+ if (!session) return false
114
+ await assurance.record({ sessionId: session.id, userId: session.userId, method })
115
+ return true
116
+ }
117
+
118
+ const deviceTokenSchema = v.pipe(v.string(), v.parseJson(), v.object({ access_token: v.string() }))
119
+
120
+ /** Records a desktop app's new session from a device sign-in, whose approval proved the step. */
121
+ export async function recordDeviceAssurance(
122
+ response: Response,
123
+ database: Kysely<CloudDatabase>,
124
+ assurance: MFAAssuranceService
125
+ ): Promise<void> {
126
+ const body = v.safeParse(deviceTokenSchema, await response.clone().text())
127
+ if (!body.success) return
128
+ const session = await database
129
+ .selectFrom('session')
130
+ .select(['id', 'userId'])
131
+ .where('token', '=', body.output.access_token)
132
+ .executeTakeFirst()
133
+ if (session) {
134
+ await assurance.record({ sessionId: session.id, userId: session.userId, method: 'device' })
135
+ }
136
+ }
137
+
138
+ /** The auth endpoints whose success proves a second step, by their request paths. */
139
+ export type ProofPaths = {
140
+ totp: string
141
+ recoveryCode: string
142
+ passkeySignIn: string
143
+ passkeyRegistration: string
144
+ deviceToken: string
145
+ }
146
+
147
+ /**
148
+ * Records what a successful auth response proved. Signing in with a code, a recovery code, or a
149
+ * passkey proves it for the session it starts; a device sign-in proves it for the app's session,
150
+ * since only a proved session may approve one; registering a passkey proves it for the session
151
+ * that added it, maybe the account's first second step, so that session is not then held.
152
+ */
153
+ export function createProofRecorder(
154
+ database: Kysely<CloudDatabase>,
155
+ assurance: MFAAssuranceService,
156
+ paths: ProofPaths
157
+ ) {
158
+ const signIns = new Map<string, MFAAssuranceMethod>([
159
+ [paths.totp, 'totp'],
160
+ [paths.recoveryCode, 'recovery-code'],
161
+ [paths.passkeySignIn, 'passkey']
162
+ ])
163
+ return async (
164
+ path: string,
165
+ response: Response,
166
+ /** The session the request came from, read only when the step is proved for it. */
167
+ current: () => Promise<{ session: { id: string }; user: { id: string } } | null>
168
+ ): Promise<void> => {
169
+ const method = signIns.get(path)
170
+ if (method) {
171
+ const recorded = await recordResponseAssurance(response, method, database, assurance)
172
+ // A code checked for a session whose account already has the step does not replace the
173
+ // session, so it proves it for that one; a passkey sign-in always starts a session.
174
+ const session = !recorded && method !== 'passkey' ? await current() : null
175
+ if (session) {
176
+ await assurance.record({ sessionId: session.session.id, userId: session.user.id, method })
177
+ }
178
+ } else if (path === paths.deviceToken)
179
+ await recordDeviceAssurance(response, database, assurance)
180
+ else if (path === paths.passkeyRegistration) {
181
+ const session = await current()
182
+ if (session) {
183
+ await assurance.record({
184
+ sessionId: session.session.id,
185
+ userId: session.user.id,
186
+ method: 'passkey'
187
+ })
188
+ }
189
+ }
190
+ }
76
191
  }
77
192
 
193
+ /** Better Auth's words for a code that does not match. */
194
+ const WRONG_CODES = new Set(['INVALID_CODE', 'INVALID_TWO_FACTOR_CODE', 'INVALID_BACKUP_CODE'])
195
+ const authErrorSchema = v.pipe(
196
+ v.string(),
197
+ v.parseJson(),
198
+ v.object({ code: v.optional(v.string()) })
199
+ )
200
+
78
201
  /**
79
202
  * Checks a second-step code through the two-step plugin's own endpoint, and records the session's
80
203
  * assurance when it passes.
@@ -88,7 +211,9 @@ export async function verifySecondFactor(
88
211
  code: string,
89
212
  method: 'totp' | 'recovery-code',
90
213
  /** The two-step plugin's endpoint that checks this kind of code. */
91
- endpoint: { path: string }
214
+ endpoint: { path: string },
215
+ /** The session the code is checked for, which proves the step when it is not replaced. */
216
+ current: { id: string; userId: string } | null
92
217
  ): Promise<Response> {
93
218
  const response = await auth.handler(
94
219
  new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
@@ -100,7 +225,19 @@ export async function verifySecondFactor(
100
225
  body: JSON.stringify({ code, trustDevice: false })
101
226
  })
102
227
  )
103
- if (!response.ok) throw APIError.fromStatus(response.status as 401)
104
- await recordResponseAssurance(response, method, database, assurance)
228
+ if (!response.ok) {
229
+ // A wrong code is the person's mistake, not a session to renew: say so, as a 400.
230
+ const answer = v.safeParse(authErrorSchema, await response.clone().text())
231
+ if (answer.success && WRONG_CODES.has(answer.output.code ?? '')) {
232
+ throw new APIError('BAD_REQUEST', { code: 'INVALID_CODE' })
233
+ }
234
+ throw APIError.fromStatus(response.status as 401)
235
+ }
236
+ // A session whose account already has the step proves it without being replaced: it is the one
237
+ // that proved it. Turning an authenticator on replaces the session, and the new one is recorded.
238
+ const recorded = await recordResponseAssurance(response, method, database, assurance)
239
+ if (!recorded && current) {
240
+ await assurance.record({ sessionId: current.id, userId: current.userId, method })
241
+ }
105
242
  return response
106
243
  }
@@ -0,0 +1,31 @@
1
+ import type { deviceAuthorization } from 'better-auth/plugins'
2
+
3
+ import { CORE_AUTH_PATHS } from './endpoints'
4
+
5
+ type DeviceEndpoints = ReturnType<typeof deviceAuthorization>['endpoints']
6
+
7
+ /**
8
+ * Better Auth's request budgets, counted per client IP in the database: a general one, and tighter
9
+ * ones for steps that send email, check passwords, or hand out desktop sign-in codes.
10
+ */
11
+ export function authRateLimit(devices: DeviceEndpoints) {
12
+ return {
13
+ enabled: true,
14
+ storage: 'database' as const,
15
+ window: 60,
16
+ max: 100,
17
+ customRules: {
18
+ [devices.deviceCode.path]: { window: 60, max: 10 },
19
+ [devices.deviceToken.path]: { window: 60, max: 60 },
20
+ // The plugin's own budget is 5 lookups per code lifetime (30 minutes), so reopening the
21
+ // sign-in page a few times turned away every new code for half an hour.
22
+ [devices.deviceVerify.path]: { window: 60, max: 20 },
23
+ [devices.deviceApprove.path]: { window: 60, max: 10 },
24
+ [devices.deviceDeny.path]: { window: 60, max: 10 },
25
+ [CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
26
+ [CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },
27
+ [CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },
28
+ [CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
29
+ }
30
+ }
31
+ }
@@ -1,3 +1,4 @@
1
+ import type { EnrollmentEmailOptions } from '#cloud/admin/enrollment/email'
1
2
  import { createEnrollmentService } from '#cloud/admin/enrollment/service'
2
3
  import type { CloudServerConfig } from '#cloud/server/config'
3
4
  import type { CloudDatabase } from '#cloud/server/db'
@@ -7,17 +8,30 @@ import type { Kysely } from 'kysely'
7
8
  import { createAuthenticationEmailService } from './email'
8
9
  import { createBetterAuthAdapter, type CloudAuthRuntimeOptions } from './factory'
9
10
 
11
+ /**
12
+ * What the enrollment service tells people, from the server's settings: where its links go, who
13
+ * hears about new requests, and whether approvals may carry the official deployment's letter.
14
+ * Every place that builds the service takes it from here, so none of them disagrees.
15
+ */
16
+ export function enrollmentEmailOptions(
17
+ config: CloudServerConfig,
18
+ email: TransactionalEmailService | undefined
19
+ ): EnrollmentEmailOptions {
20
+ return {
21
+ publicURL: config.publicURL,
22
+ adminRecipients: config.enrollmentAdminNotificationEmails,
23
+ email,
24
+ invitations: config.deployment === 'official'
25
+ }
26
+ }
27
+
10
28
  export function createCloudAuthenticationRuntime(
11
29
  config: CloudServerConfig,
12
30
  database: Kysely<CloudDatabase>,
13
31
  email: TransactionalEmailService,
14
32
  options: Pick<CloudAuthRuntimeOptions, 'runInBackground' | 'validateSchema'> = {}
15
33
  ) {
16
- const enrollment = createEnrollmentService(database, {
17
- publicURL: config.publicURL,
18
- adminRecipients: config.enrollmentAdminNotificationEmails,
19
- email
20
- })
34
+ const enrollment = createEnrollmentService(database, enrollmentEmailOptions(config, email))
21
35
  const auth = createBetterAuthAdapter(config, database, enrollment, {
22
36
  email: createAuthenticationEmailService(email, config.publicURL),
23
37
  ...options
@@ -1,3 +1,4 @@
1
+ import { CLOUD_SOCIAL_PROVIDERS, type CloudSocialProvider } from '#cloud/contract/account'
1
2
  import type { CloudServerConfig } from '#cloud/server/config'
2
3
  import type { BetterAuthOptions } from 'better-auth'
3
4
  import { importPKCS8, SignJWT } from 'jose'
@@ -26,30 +27,75 @@ async function generateAppleClientSecret(config: CloudServerConfig): Promise<str
26
27
  .sign(privateKey)
27
28
  }
28
29
 
29
- /** The sign-in providers the deployment configures; Apple's secret is signed when it is needed. */
30
- export function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
31
- const providers: BetterAuthOptions['socialProviders'] = {}
32
- if (config.googleClientId && config.googleClientSecret) {
33
- providers.google = {
34
- clientId: config.googleClientId,
35
- clientSecret: config.googleClientSecret
36
- }
30
+ type ProviderOptions = NonNullable<BetterAuthOptions['socialProviders']>
31
+
32
+ /**
33
+ * Each provider as the server sets it up: its Better Auth options from the deployment's config, or
34
+ * `undefined` where it is not configured, and whether its email may link to an existing account
35
+ * whatever it says of that address (`trusted`). The one place a new provider's server side goes,
36
+ * beside its config fields.
37
+ */
38
+ const PROVIDERS: {
39
+ [Provider in CloudSocialProvider]: {
40
+ options: (config: CloudServerConfig) => ProviderOptions[Provider]
41
+ trusted: boolean
37
42
  }
38
- if (config.appleClientId) {
39
- providers.apple = async () => {
40
- const provider: {
41
- clientId: string
42
- clientSecret: string
43
- appBundleIdentifier?: string
44
- } = {
45
- clientId: config.appleClientId ?? '',
46
- clientSecret: await generateAppleClientSecret(config)
47
- }
48
- if (config.appleAppBundleIdentifier) {
49
- provider.appBundleIdentifier = config.appleAppBundleIdentifier
50
- }
51
- return provider
52
- }
43
+ } = {
44
+ // Google only gives an address it has verified.
45
+ google: {
46
+ options: (config) =>
47
+ config.googleClientId && config.googleClientSecret
48
+ ? { clientId: config.googleClientId, clientSecret: config.googleClientSecret }
49
+ : undefined,
50
+ trusted: true
51
+ },
52
+ // Apple's addresses are verified, or relays it delivers itself. Its client secret is a token the
53
+ // server signs, so it is made when Better Auth asks.
54
+ apple: {
55
+ options: (config) =>
56
+ config.appleClientId
57
+ ? async () => ({
58
+ clientId: config.appleClientId ?? '',
59
+ clientSecret: await generateAppleClientSecret(config),
60
+ ...(config.appleAppBundleIdentifier && {
61
+ appBundleIdentifier: config.appleAppBundleIdentifier
62
+ })
63
+ })
64
+ : undefined,
65
+ trusted: true
66
+ },
67
+ // GitHub can hand over an address it has not verified, such as an account's first listed email
68
+ // when none is primary; untrusted, it links only when GitHub says the address is verified.
69
+ github: {
70
+ options: (config) =>
71
+ config.githubClientId && config.githubClientSecret
72
+ ? { clientId: config.githubClientId, clientSecret: config.githubClientSecret }
73
+ : undefined,
74
+ trusted: false
53
75
  }
54
- return providers
76
+ }
77
+
78
+ /**
79
+ * Providers whose sign-in links to the account with the same email even when it does not say the
80
+ * address is verified. Better Auth links any other provider only when it does.
81
+ */
82
+ export const TRUSTED_SOCIAL_PROVIDERS: CloudSocialProvider[] = CLOUD_SOCIAL_PROVIDERS.filter(
83
+ (provider) => PROVIDERS[provider].trusted
84
+ )
85
+
86
+ /** The providers the deployment configures, in the order the editor shows them. */
87
+ export function configuredSocialProviders(config: CloudServerConfig): CloudSocialProvider[] {
88
+ return CLOUD_SOCIAL_PROVIDERS.filter(
89
+ (provider) => PROVIDERS[provider].options(config) !== undefined
90
+ )
91
+ }
92
+
93
+ /** Better Auth's options for the providers the deployment configures. */
94
+ export function socialProviders(config: CloudServerConfig): BetterAuthOptions['socialProviders'] {
95
+ return Object.fromEntries(
96
+ configuredSocialProviders(config).map((provider) => [
97
+ provider,
98
+ PROVIDERS[provider].options(config)
99
+ ])
100
+ )
55
101
  }
@@ -1,4 +1,6 @@
1
1
  export { createBillingRoutes, type BillingRouteEnvironment } from './routes'
2
+ export { createSeatNotifier, type SeatNotifier, type SeatNotifierOptions } from './notify'
3
+ export { accountSeats } from './seats'
2
4
  export {
3
5
  createBillingTokenService,
4
6
  type BillingTokenService,
@@ -0,0 +1,55 @@
1
+ import { CLOUD_BILLING_API_PATHS } from '#cloud/contract'
2
+ import { userIdText, type CloudDatabase } from '#cloud/server/db'
3
+ import type { Kysely } from 'kysely'
4
+ import { joinURL } from 'ufo'
5
+
6
+ import type { BillingTokenService } from './tokens'
7
+
8
+ export type SeatNotifierOptions = {
9
+ database: Kysely<CloudDatabase>
10
+ /** The billing service's discovered endpoint. */
11
+ endpoint: string
12
+ tokens: BillingTokenService
13
+ /** Sends a notice; the global `fetch` by default. */
14
+ fetch?: (url: string, init: RequestInit) => Promise<Response>
15
+ }
16
+
17
+ /**
18
+ * Tells the billing service when the people who can edit in an account's workspaces change, so it
19
+ * can charge for the seats. Each notice carries a billing token for that account and nothing
20
+ * else: the service reads the count from Cloud's internal API, so a notice that never arrives only
21
+ * leaves the change to the service's own reconciliation.
22
+ */
23
+ export function createSeatNotifier(options: SeatNotifierOptions) {
24
+ const send = options.fetch ?? ((url: string, init: RequestInit) => fetch(url, init))
25
+ return {
26
+ async notify(accountIds: readonly string[]): Promise<void> {
27
+ if (accountIds.length === 0) return
28
+ const accounts = await options.database
29
+ .selectFrom('user')
30
+ .select((eb) => [userIdText(eb).as('userId'), 'email'])
31
+ .where((eb) => eb(userIdText(eb), 'in', accountIds))
32
+ .execute()
33
+ // Every notice is sent before any failure is reported, so one refusal never leaves
34
+ // another account's notice cut off.
35
+ const sent = await Promise.allSettled(
36
+ accounts.map(async (account) => {
37
+ const { token } = await options.tokens.issue(account)
38
+ const response = await send(joinURL(options.endpoint, CLOUD_BILLING_API_PATHS.seats), {
39
+ method: 'POST',
40
+ headers: { Authorization: `Bearer ${token}` }
41
+ })
42
+ if (!response.ok) {
43
+ throw new Error(`Billing refused a seat notice with status ${response.status}`)
44
+ }
45
+ })
46
+ )
47
+ const failed: unknown[] = sent.flatMap((result): unknown[] =>
48
+ result.status === 'rejected' ? [result.reason] : []
49
+ )
50
+ if (failed.length > 0) throw new AggregateError(failed, 'Billing missed seat notices')
51
+ }
52
+ }
53
+ }
54
+
55
+ export type SeatNotifier = ReturnType<typeof createSeatNotifier>
@@ -0,0 +1,17 @@
1
+ import type { CloudDatabase } from '#cloud/server/db'
2
+ import type { Kysely } from 'kysely'
3
+
4
+ /**
5
+ * An account's seats: the people who can edit in the workspaces it owns, each counted once
6
+ * however many of them they edit, the owner too. Viewers take no seat.
7
+ */
8
+ export async function accountSeats(database: Kysely<CloudDatabase>, accountId: string) {
9
+ const row = await database
10
+ .selectFrom('workspaceMember')
11
+ .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')
12
+ .select((eb) => eb.fn.count<string>('workspaceMember.userId').distinct().as('seats'))
13
+ .where('workspace.ownerId', '=', accountId)
14
+ .where('workspaceMember.role', 'in', ['editor', 'admin'])
15
+ .executeTakeFirst()
16
+ return Number(row?.seats ?? 0)
17
+ }
@@ -18,7 +18,7 @@ export function createBillingTokenService(options: BillingTokenServiceOptions) {
18
18
  * Signs a token that lets the signed-in person buy or manage their own account's plan and
19
19
  * credits with billing; nobody else's, since an account is the person.
20
20
  */
21
- async issue(actor: CloudActor): Promise<BillingToken> {
21
+ async issue(actor: Pick<CloudActor, 'userId' | 'email'>): Promise<BillingToken> {
22
22
  const issuedAt = Math.floor(Date.now() / 1000)
23
23
  const expiresAt = issuedAt + options.lifetimeSeconds
24
24
  const token = await new SignJWT({ email: actor.email })
@@ -111,12 +111,15 @@ export function createDocumentCleanupService(
111
111
  } catch (error) {
112
112
  result.failed++
113
113
  result.failures.push(error)
114
- // Only the document's ID: its name and the people on it stay out of error tracking.
114
+ // Only the document's and its workspace's IDs: its name and the people on it stay out.
115
115
  await reportCloudError(
116
116
  options.reportError,
117
117
  `Cleaning up document ${document.id} failed`,
118
118
  error,
119
- { source: 'cleanup' }
119
+ {
120
+ source: 'cleanup',
121
+ resources: { documentId: document.id, workspaceId: document.workspaceId }
122
+ }
120
123
  )
121
124
  // Out of Trash already, a document whose files are partly gone is never restorable; the
122
125
  // next pass tries again.