@open-pencil/cloud 0.17.0-beta.4 → 0.17.0-beta.5
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.
- package/README.md +2 -1
- package/dist/bin/server.mjs +1 -1
- package/dist/bin/server.mjs.map +1 -1
- package/dist/bin/services.mjs +1 -1
- package/dist/bin/services.mjs.map +1 -1
- package/dist/client.d.ts +296 -27
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +649 -295
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +331 -21
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +1773 -32
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +3478 -288
- package/dist/email.js.map +1 -1
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +48 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +466 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index2.d.ts +35 -0
- package/dist/index2.d.ts.map +1 -0
- package/dist/listen.mjs +447 -290
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-cloudflare.d.ts +89 -0
- package/dist/runtime-cloudflare.d.ts.map +1 -0
- package/dist/runtime-cloudflare.js +15667 -0
- package/dist/runtime-cloudflare.js.map +1 -0
- package/dist/runtime-node.d.mts +2963 -294
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +3473 -842
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +12187 -8244
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +7739 -3548
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +5 -5
- package/dist/server2.mjs.map +1 -1
- package/package.json +22 -5
- package/src/admin/audit/service.ts +2 -2
- package/src/admin/documents/service.ts +76 -6
- package/src/admin/reports/service.ts +7 -1
- package/src/client/api.ts +23 -471
- package/src/client/auth/client.ts +22 -3
- package/src/client/billing.ts +80 -0
- package/src/client/community.ts +40 -0
- package/src/client/discovery.ts +35 -9
- package/src/client/documents.ts +160 -0
- package/src/client/index.ts +7 -0
- package/src/client/portal/account.ts +54 -2
- package/src/client/portal/request.ts +2 -0
- package/src/client/response.ts +21 -0
- package/src/client/schema.ts +8 -0
- package/src/client/services.ts +23 -18
- package/src/client/sharing.ts +262 -0
- package/src/client/versions.ts +104 -0
- package/src/contract/account.ts +50 -0
- package/src/contract/billing.ts +166 -0
- package/src/contract/collaboration.ts +5 -0
- package/src/contract/community.ts +60 -0
- package/src/contract/discovery.ts +63 -2
- package/src/contract/entitlements.ts +10 -0
- package/src/contract/index.ts +54 -5
- package/src/contract/links.ts +57 -4
- package/src/contract/locale.ts +27 -0
- package/src/contract/portal.ts +12 -1
- package/src/contract/routes.ts +10 -0
- package/src/contract/services.ts +18 -16
- package/src/email/i18n.ts +174 -0
- package/src/email/index.ts +13 -2
- package/src/email/locales/ar.json +141 -0
- package/src/email/locales/de.json +141 -0
- package/src/email/locales/es.json +141 -0
- package/src/email/locales/fr.json +141 -0
- package/src/email/locales/it.json +141 -0
- package/src/email/locales/ja.json +141 -0
- package/src/email/locales/pl.json +141 -0
- package/src/email/locales/pt-br.json +141 -0
- package/src/email/locales/ru.json +141 -0
- package/src/email/locales/zh-cn.json +141 -0
- package/src/email/messages.ts +200 -0
- package/src/email/render.ts +142 -276
- package/src/email/samples.ts +115 -0
- package/src/email/schema.ts +70 -6
- package/src/email/templates/BrandEmail.vue +54 -0
- package/src/email/templates/DocumentBlocked.vue +45 -0
- package/src/email/templates/DocumentInvitation.vue +24 -0
- package/src/email/templates/DocumentReport.vue +32 -0
- package/src/email/templates/DocumentReportDecided.vue +36 -0
- package/src/email/templates/DocumentReportReceived.vue +18 -0
- package/src/email/templates/DocumentRestored.vue +24 -0
- package/src/email/templates/EmailChangeRequested.vue +24 -0
- package/src/email/templates/EmailRoot.vue +19 -0
- package/src/email/templates/EmailText.vue +9 -0
- package/src/email/templates/EmailVerification.vue +38 -0
- package/src/email/templates/EnrollmentNotification.vue +24 -0
- package/src/email/templates/EnrollmentUpdate.vue +52 -0
- package/src/email/templates/NewSignIn.vue +37 -0
- package/src/email/templates/PasswordChanged.vue +22 -0
- package/src/email/templates/PasswordReset.vue +23 -0
- package/src/email/templates/StorageLimitReached.vue +28 -0
- package/src/email/templates/TwoStepChanged.vue +32 -0
- package/src/email/templates/WaitlistConfirmation.vue +29 -0
- package/src/email/templates/WorkspaceInvitation.vue +28 -0
- package/src/email/templates/brand.ts +9 -61
- package/src/email/templates/localization.ts +17 -0
- package/src/errors/index.ts +6 -0
- package/src/global.d.ts +7 -0
- package/src/runtime/cloudflare/relay/index.ts +7 -1
- package/src/runtime/cloudflare/tsconfig.json +2 -1
- package/src/runtime/cloudflare/worker.ts +8 -1
- package/src/runtime/node/cleanup.ts +5 -1
- package/src/runtime/node/email/transport.ts +13 -10
- package/src/runtime/node/main.ts +1 -1
- package/src/runtime/node/server.ts +12 -2
- package/src/runtime/node/services/main.ts +1 -1
- package/src/runtime/posthog/errors.ts +2 -1
- package/src/runtime/s3/objects.ts +17 -0
- package/src/runtime/site/community.ts +101 -0
- package/src/runtime/site/server.ts +17 -1
- package/src/server/account/deletion.ts +2 -0
- package/src/server/account/routes.ts +271 -240
- package/src/server/account/tokens.ts +57 -0
- package/src/server/api/router.ts +23 -0
- package/src/server/app/checks.ts +84 -0
- package/src/server/app/editors.ts +20 -0
- package/src/server/app/index.ts +128 -0
- package/src/server/app/indexing.ts +40 -0
- package/src/server/app/limiters.ts +53 -0
- package/src/server/app/routes.ts +114 -0
- package/src/server/app/services.ts +185 -0
- package/src/server/auth/access-tokens.ts +62 -0
- package/src/server/auth/adapter.ts +21 -1
- package/src/server/auth/email.ts +4 -1
- package/src/server/auth/enrollment.ts +116 -0
- package/src/server/auth/factory.ts +88 -131
- package/src/server/auth/logger.ts +23 -0
- package/src/server/auth/mfa-assurance.ts +51 -0
- package/src/server/auth/passwords.ts +43 -0
- package/src/server/auth/session.ts +2 -0
- package/src/server/billing/index.ts +6 -0
- package/src/server/billing/routes.ts +27 -0
- package/src/server/billing/tokens.ts +37 -0
- package/src/server/cleanup/configured.ts +16 -3
- package/src/server/cleanup/worker.ts +10 -1
- package/src/server/collaboration/relay/hub.ts +25 -142
- package/src/server/collaboration/relay/room.ts +154 -0
- package/src/server/collaboration/service.ts +21 -2
- package/src/server/community/index.ts +2 -0
- package/src/server/community/routes.ts +93 -0
- package/src/server/community/service.ts +134 -0
- package/src/server/config/deployment.ts +17 -5
- package/src/server/config/index.ts +1 -1
- package/src/server/config/public.ts +7 -1
- package/src/server/config/schema.ts +40 -292
- package/src/server/config/toml/schema.ts +307 -0
- package/src/server/db/index.ts +1 -0
- package/src/server/db/migrate.ts +13 -1
- package/src/server/db/migrations/009_access_tokens.ts +47 -0
- package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
- package/src/server/db/migrations/011_account_ids.ts +30 -0
- package/src/server/db/migrations/012_email_locales.ts +34 -0
- package/src/server/db/migrations/013_document_block_emails.ts +40 -0
- package/src/server/db/migrations/014_report_replies.ts +28 -0
- package/src/server/db/migrations/schema.ts +26 -1
- package/src/server/db/tables.ts +30 -1
- package/src/server/db/users.ts +22 -0
- package/src/server/documents/index.ts +1 -1
- package/src/server/documents/limits.ts +7 -1
- package/src/server/documents/service.ts +12 -402
- package/src/server/documents/uploads.ts +450 -0
- package/src/server/documents/versions/service.ts +81 -24
- package/src/server/email/invitations.ts +1 -0
- package/src/server/email/service.ts +31 -4
- package/src/server/email/types.ts +12 -0
- package/src/server/errors/index.ts +1 -9
- package/src/server/index.ts +12 -5
- package/src/server/invitations/types.ts +5 -1
- package/src/server/objects/types.ts +5 -0
- package/src/server/policy/configured.ts +9 -3
- package/src/server/policy/database.ts +13 -2
- package/src/server/policy/policy.ts +39 -12
- package/src/server/policy/service.ts +71 -52
- package/src/server/policy/storage.ts +33 -0
- package/src/server/quota/index.ts +6 -0
- package/src/server/quota/notices.ts +121 -0
- package/src/server/quota/storage.ts +5 -0
- package/src/server/rate-limit/middleware.ts +4 -0
- package/src/server/reports/index.ts +1 -0
- package/src/server/reports/replies.ts +55 -0
- package/src/server/reports/routes.ts +3 -1
- package/src/server/reports/service.ts +24 -2
- package/src/server/sharing/capabilities/service.ts +2 -3
- package/src/server/sharing/invitations/service.ts +14 -4
- package/src/server/validation.ts +3 -0
- package/src/server/workspaces/members.ts +7 -19
- package/src/services/app.ts +1 -3
- package/src/services/config.ts +1 -0
- package/src/services/usage.ts +6 -14
- package/src/email/templates/document-invitation.ts +0 -35
- package/src/email/templates/enrollment.ts +0 -27
- package/src/email/templates/layout.ts +0 -18
- package/src/server/app.ts +0 -453
- /package/src/{server/errors → errors}/posthog.ts +0 -0
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
CLOUD_ACCESS_TOKEN_MAX_DAYS,
|
|
4
|
+
CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH,
|
|
5
|
+
CLOUD_ACCESS_TOKEN_PREFIX
|
|
6
|
+
} from '#cloud/contract'
|
|
3
7
|
import { createTermsService } from '#cloud/server/account/terms'
|
|
4
8
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
5
9
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
6
10
|
import { createUserPictures, providerPictures } from '#cloud/server/pictures'
|
|
11
|
+
import { apiKey } from '@better-auth/api-key'
|
|
7
12
|
import { passkey } from '@better-auth/passkey'
|
|
8
13
|
import { APIError, betterAuth } from 'better-auth'
|
|
9
14
|
import { getMigrations } from 'better-auth/db/migration'
|
|
@@ -17,65 +22,34 @@ import {
|
|
|
17
22
|
} from 'better-auth/plugins'
|
|
18
23
|
import type { Kysely } from 'kysely'
|
|
19
24
|
|
|
25
|
+
import { accessTokenAccount, bearerAccessToken, toAccessToken } from './access-tokens'
|
|
20
26
|
import { accountActivity, createSignInActivity } from './activity'
|
|
21
27
|
import type { CloudAuthAdapter } from './adapter'
|
|
22
28
|
import type { AuthenticationEmailService } from './email'
|
|
23
29
|
import { AUTH_BASE_PATH, CORE_AUTH_PATHS, authRequestPath } from './endpoints'
|
|
24
|
-
import {
|
|
30
|
+
import { enrollmentOptions } from './enrollment'
|
|
31
|
+
import { betterAuthLogger } from './logger'
|
|
32
|
+
import {
|
|
33
|
+
createMFAAssuranceService,
|
|
34
|
+
recordResponseAssurance,
|
|
35
|
+
verifySecondFactor
|
|
36
|
+
} from './mfa-assurance'
|
|
37
|
+
import { passwordOptions } from './passwords'
|
|
25
38
|
import { APPLE_AUDIENCE, socialProviders } from './social-providers'
|
|
26
39
|
|
|
27
40
|
const BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'
|
|
41
|
+
const DAY_SECONDS = 24 * 60 * 60
|
|
28
42
|
const ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60
|
|
29
43
|
|
|
30
|
-
async function recordResponseAssurance(
|
|
31
|
-
response: Response,
|
|
32
|
-
method: 'totp' | 'recovery-code' | 'passkey',
|
|
33
|
-
database: Kysely<CloudDatabase>,
|
|
34
|
-
assurance: ReturnType<typeof createMFAAssuranceService>
|
|
35
|
-
): Promise<void> {
|
|
36
|
-
const signedToken = response.headers.get('set-auth-token')
|
|
37
|
-
const token = signedToken?.split('.', 1)[0]
|
|
38
|
-
if (!token) return
|
|
39
|
-
const session = await database
|
|
40
|
-
.selectFrom('session')
|
|
41
|
-
.select(['id', 'userId'])
|
|
42
|
-
.where('token', '=', token)
|
|
43
|
-
.executeTakeFirst()
|
|
44
|
-
if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function verifySecondFactor(
|
|
48
|
-
auth: { handler(request: Request): Promise<Response> },
|
|
49
|
-
config: CloudServerConfig,
|
|
50
|
-
database: Kysely<CloudDatabase>,
|
|
51
|
-
assurance: ReturnType<typeof createMFAAssuranceService>,
|
|
52
|
-
headers: Headers,
|
|
53
|
-
code: string,
|
|
54
|
-
method: 'totp' | 'recovery-code',
|
|
55
|
-
/** The two-step plugin's endpoint that checks this kind of code. */
|
|
56
|
-
endpoint: { path: string }
|
|
57
|
-
): Promise<Response> {
|
|
58
|
-
const response = await auth.handler(
|
|
59
|
-
new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
|
|
60
|
-
method: 'POST',
|
|
61
|
-
headers: new Headers({
|
|
62
|
-
...Object.fromEntries(headers),
|
|
63
|
-
'Content-Type': 'application/json'
|
|
64
|
-
}),
|
|
65
|
-
body: JSON.stringify({ code, trustDevice: false })
|
|
66
|
-
})
|
|
67
|
-
)
|
|
68
|
-
if (!response.ok) throw APIError.fromStatus(response.status as 401)
|
|
69
|
-
await recordResponseAssurance(response, method, database, assurance)
|
|
70
|
-
return response
|
|
71
|
-
}
|
|
72
|
-
|
|
73
44
|
export type CloudAuthRuntimeOptions = {
|
|
74
45
|
email?: AuthenticationEmailService
|
|
75
46
|
runInBackground?: (promise: Promise<unknown>) => void
|
|
76
47
|
/**
|
|
77
|
-
* Whether Better Auth checks the database schema when it starts
|
|
78
|
-
*
|
|
48
|
+
* Whether Better Auth checks the database schema when it starts, off unless asked for. The check
|
|
49
|
+
* runs in the background and nothing waits for it, so an adapter made briefly, as for one
|
|
50
|
+
* request, for migrating, or in a test, would leave it querying a database being closed;
|
|
51
|
+
* `migrateCloudDatabase` has already checked the recorded version. A server's long-lived
|
|
52
|
+
* adapter turns it on.
|
|
79
53
|
*/
|
|
80
54
|
validateSchema?: boolean
|
|
81
55
|
}
|
|
@@ -113,8 +87,20 @@ export function createBetterAuthAdapter(
|
|
|
113
87
|
validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
|
|
114
88
|
})
|
|
115
89
|
const administration = admin()
|
|
90
|
+
// Personal access tokens. Cloud reads them itself (`resolveAccessToken`), for the document API
|
|
91
|
+
// alone, so they never become sessions; Cloud's own limiters count their requests.
|
|
92
|
+
const accessTokens = apiKey({
|
|
93
|
+
defaultPrefix: CLOUD_ACCESS_TOKEN_PREFIX,
|
|
94
|
+
requireName: true,
|
|
95
|
+
maximumNameLength: CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH,
|
|
96
|
+
startingCharactersConfig: { charactersLength: CLOUD_ACCESS_TOKEN_PREFIX.length + 4 },
|
|
97
|
+
keyExpiration: { minExpiresIn: 1, maxExpiresIn: CLOUD_ACCESS_TOKEN_MAX_DAYS },
|
|
98
|
+
rateLimit: { enabled: false },
|
|
99
|
+
enableSessionForAPIKeys: false
|
|
100
|
+
})
|
|
116
101
|
const auth = betterAuth({
|
|
117
102
|
appName: 'OpenPencil Cloud',
|
|
103
|
+
logger: betterAuthLogger,
|
|
118
104
|
baseURL: config.publicURL,
|
|
119
105
|
basePath: AUTH_BASE_PATH,
|
|
120
106
|
// Clients never reach Better Auth's own administration, which `/api/admin` replaces with MFA,
|
|
@@ -122,6 +108,8 @@ export function createBetterAuthAdapter(
|
|
|
122
108
|
// through its account routes; the server still calls them itself.
|
|
123
109
|
disabledPaths: [
|
|
124
110
|
...Object.values(administration.endpoints).map((endpoint) => endpoint.path),
|
|
111
|
+
// Tokens are made, listed, and revoked through `/api/account/tokens`, with a fresh session.
|
|
112
|
+
...Object.values(accessTokens.endpoints).map((endpoint) => endpoint.path),
|
|
125
113
|
passkeys.endpoints.deletePasskey.path,
|
|
126
114
|
twoStep.endpoints.disableTwoFactor.path,
|
|
127
115
|
// Accounts are deleted through `/api/account/delete`, which an account awaiting approval
|
|
@@ -148,7 +136,7 @@ export function createBetterAuthAdapter(
|
|
|
148
136
|
},
|
|
149
137
|
session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },
|
|
150
138
|
advanced: {
|
|
151
|
-
database: { generateId: 'uuid', validateSchema: runtime.validateSchema },
|
|
139
|
+
database: { generateId: 'uuid', validateSchema: runtime.validateSchema ?? false },
|
|
152
140
|
ipAddress: {
|
|
153
141
|
ipAddressHeaders: config.authTrustedIPHeaders,
|
|
154
142
|
trustedProxies: config.authTrustedProxies
|
|
@@ -171,87 +159,8 @@ export function createBetterAuthAdapter(
|
|
|
171
159
|
[CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
|
|
172
160
|
}
|
|
173
161
|
},
|
|
174
|
-
emailAndPassword: config
|
|
175
|
-
|
|
176
|
-
enabled: true,
|
|
177
|
-
disableSignUp: !config.emailPasswordSignUpEnabled,
|
|
178
|
-
requireEmailVerification: true,
|
|
179
|
-
minPasswordLength: config.emailPasswordMinimumLength,
|
|
180
|
-
maxPasswordLength: config.emailPasswordMaximumLength,
|
|
181
|
-
autoSignIn: false,
|
|
182
|
-
resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,
|
|
183
|
-
revokeSessionsOnPasswordReset: true,
|
|
184
|
-
sendResetPassword: authenticationEmail
|
|
185
|
-
? ({ user, url, token }) =>
|
|
186
|
-
authenticationEmail.sendPasswordReset({
|
|
187
|
-
email: user.email,
|
|
188
|
-
name: user.name,
|
|
189
|
-
url,
|
|
190
|
-
token
|
|
191
|
-
})
|
|
192
|
-
: undefined,
|
|
193
|
-
onPasswordReset: authenticationEmail
|
|
194
|
-
? ({ user }) =>
|
|
195
|
-
authenticationEmail.sendPasswordChanged({
|
|
196
|
-
email: user.email,
|
|
197
|
-
name: user.name,
|
|
198
|
-
userId: user.id,
|
|
199
|
-
url: config.publicURL
|
|
200
|
-
})
|
|
201
|
-
: undefined
|
|
202
|
-
}
|
|
203
|
-
: undefined,
|
|
204
|
-
emailVerification:
|
|
205
|
-
config.emailPasswordEnabled && authenticationEmail
|
|
206
|
-
? {
|
|
207
|
-
expiresIn: config.emailVerificationExpiresIn,
|
|
208
|
-
sendOnSignUp: true,
|
|
209
|
-
// Signing in unverified only says so; people ask for another link with Send again.
|
|
210
|
-
sendOnSignIn: false,
|
|
211
|
-
autoSignInAfterVerification: true,
|
|
212
|
-
// A change of address sends the link to the new address as `user.email`, on the
|
|
213
|
-
// account it already confirmed; a new account has not confirmed one yet. This runs
|
|
214
|
-
// inside sign-up's transaction, so it must not query the database itself.
|
|
215
|
-
sendVerificationEmail: ({ user, url, token }) =>
|
|
216
|
-
authenticationEmail.sendVerification({
|
|
217
|
-
email: user.email,
|
|
218
|
-
name: user.name,
|
|
219
|
-
url,
|
|
220
|
-
token,
|
|
221
|
-
purpose: user.emailVerified ? 'change' : 'account'
|
|
222
|
-
}),
|
|
223
|
-
afterEmailVerification: async (user) => {
|
|
224
|
-
await enrollment.followEmailChange(user.id, user.email)
|
|
225
|
-
if (config.enrollmentMode === 'approval') {
|
|
226
|
-
await enrollment.request({ email: user.email, name: user.name })
|
|
227
|
-
}
|
|
228
|
-
await enrollment.bindApprovedUser(user.email, user.id)
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
: undefined,
|
|
232
|
-
user: {
|
|
233
|
-
changeEmail: { enabled: emailChangeAvailable },
|
|
234
|
-
deleteUser: accountDeletionOptions(database),
|
|
235
|
-
validateUserInfo: ({ source }) => {
|
|
236
|
-
if (source.action === 'create-user' && config.enrollmentMode === 'closed') {
|
|
237
|
-
return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }
|
|
238
|
-
}
|
|
239
|
-
return undefined
|
|
240
|
-
}
|
|
241
|
-
},
|
|
242
|
-
databaseHooks: {
|
|
243
|
-
user: {
|
|
244
|
-
create: {
|
|
245
|
-
after: async (user) => {
|
|
246
|
-
if (!user.emailVerified) return
|
|
247
|
-
if (config.enrollmentMode === 'approval') {
|
|
248
|
-
await enrollment.request({ email: user.email, name: user.name })
|
|
249
|
-
}
|
|
250
|
-
await enrollment.bindApprovedUser(user.email, user.id)
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
},
|
|
162
|
+
emailAndPassword: passwordOptions(config, authenticationEmail),
|
|
163
|
+
...enrollmentOptions(config, database, enrollment, authenticationEmail, emailChangeAvailable),
|
|
255
164
|
plugins: [
|
|
256
165
|
...(config.captchaProvider && config.captchaSecretKey
|
|
257
166
|
? [
|
|
@@ -280,7 +189,8 @@ export function createBetterAuthAdapter(
|
|
|
280
189
|
{ twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },
|
|
281
190
|
(user) => notifyTwoStep(user, 'passkey-added')
|
|
282
191
|
),
|
|
283
|
-
providerPictures(createUserPictures(database, { publicURL: config.publicURL }))
|
|
192
|
+
providerPictures(createUserPictures(database, { publicURL: config.publicURL })),
|
|
193
|
+
accessTokens
|
|
284
194
|
],
|
|
285
195
|
socialProviders: socialProviders(config),
|
|
286
196
|
trustedOrigins: [
|
|
@@ -359,6 +269,24 @@ export function createBetterAuthAdapter(
|
|
|
359
269
|
return identity
|
|
360
270
|
}
|
|
361
271
|
|
|
272
|
+
/** The account a personal access token in `Authorization: Bearer` stands for. */
|
|
273
|
+
async function resolveAccessToken(headers: Headers) {
|
|
274
|
+
const key = bearerAccessToken(headers)
|
|
275
|
+
if (!key) return null
|
|
276
|
+
const verified = await auth.api.verifyApiKey({ body: { key } })
|
|
277
|
+
if (!verified.valid || !verified.key) return null
|
|
278
|
+
const context = { database, config, enrollment, terms }
|
|
279
|
+
const user = await accessTokenAccount(context, verified.key.referenceId)
|
|
280
|
+
if (!user) return null
|
|
281
|
+
return {
|
|
282
|
+
userId: user.id,
|
|
283
|
+
email: user.email,
|
|
284
|
+
name: user.name,
|
|
285
|
+
deploymentRole: deploymentRole(user),
|
|
286
|
+
credential: 'token' as const
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
362
290
|
/**
|
|
363
291
|
* The endpoints that read or change an account, which only an account that may use the server
|
|
364
292
|
* reaches; one awaiting approval still signs in and out. Better Auth checks the session inside
|
|
@@ -410,6 +338,28 @@ export function createBetterAuthAdapter(
|
|
|
410
338
|
resolveIdentity,
|
|
411
339
|
resolveSession,
|
|
412
340
|
resolveAccountSession,
|
|
341
|
+
resolveAccessToken,
|
|
342
|
+
async listAccessTokens(headers) {
|
|
343
|
+
const session = await currentSession(headers)
|
|
344
|
+
if (!session) return null
|
|
345
|
+
const { apiKeys } = await auth.api.listApiKeys({ headers })
|
|
346
|
+
return apiKeys.map(toAccessToken)
|
|
347
|
+
},
|
|
348
|
+
async createAccessToken(headers, input) {
|
|
349
|
+
// A token outlives the session that makes it, so making one needs a recent sign-in.
|
|
350
|
+
const session = await freshSession(headers)
|
|
351
|
+
const created = await auth.api.createApiKey({
|
|
352
|
+
body: {
|
|
353
|
+
name: input.name,
|
|
354
|
+
expiresIn: input.expiresInDays * DAY_SECONDS,
|
|
355
|
+
userId: session.user.id
|
|
356
|
+
}
|
|
357
|
+
})
|
|
358
|
+
return { token: created.key, accessToken: toAccessToken(created) }
|
|
359
|
+
},
|
|
360
|
+
async revokeAccessToken(headers, id) {
|
|
361
|
+
await auth.api.deleteApiKey({ headers, body: { keyId: id } })
|
|
362
|
+
},
|
|
413
363
|
async listAuthenticationMethods(headers) {
|
|
414
364
|
const accounts = await auth.api.listUserAccounts({ headers })
|
|
415
365
|
return accounts.map((account) => ({
|
|
@@ -556,6 +506,9 @@ export function createBetterAuthAdapter(
|
|
|
556
506
|
async updateProfile(headers, input) {
|
|
557
507
|
await auth.api.updateUser({ headers, body: { name: input.name } })
|
|
558
508
|
},
|
|
509
|
+
async setLocale(headers, locale) {
|
|
510
|
+
await auth.api.updateUser({ headers, body: { locale } })
|
|
511
|
+
},
|
|
559
512
|
async changeEmail(headers, input) {
|
|
560
513
|
const session = await freshSession(headers)
|
|
561
514
|
if (session.user.email === input.newEmail) {
|
|
@@ -603,7 +556,11 @@ export function createBetterAuthAdapter(
|
|
|
603
556
|
},
|
|
604
557
|
schemaVersion: BETTER_AUTH_SCHEMA_VERSION,
|
|
605
558
|
async migrate() {
|
|
606
|
-
|
|
559
|
+
// The access token table is Cloud's migration `009_access_tokens`, built before this runs.
|
|
560
|
+
const migrations = await getMigrations({
|
|
561
|
+
...auth.options,
|
|
562
|
+
plugins: auth.options.plugins.filter((plugin) => plugin.id !== accessTokens.id)
|
|
563
|
+
})
|
|
607
564
|
await migrations.runMigrations()
|
|
608
565
|
}
|
|
609
566
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { writeJSONLine } from '#cloud/server/logging'
|
|
2
|
+
import type { BetterAuthOptions } from 'better-auth'
|
|
3
|
+
|
|
4
|
+
/** What the API-key plugin logs, as an error, for a token that is wrong, expired, or revoked. */
|
|
5
|
+
const REFUSED_TOKEN = 'Failed to validate API key'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Better Auth's log lines as Cloud's JSON lines. A refused personal access token is the caller's
|
|
9
|
+
* mistake, which the request answers with 401, so it is not logged as the server's error; nor is
|
|
10
|
+
* anything a log line's arguments carry beyond an error's name and message.
|
|
11
|
+
*/
|
|
12
|
+
export const betterAuthLogger: NonNullable<BetterAuthOptions['logger']> = {
|
|
13
|
+
log(level, message, ...args) {
|
|
14
|
+
if (level === 'debug' || message.startsWith(REFUSED_TOKEN)) return
|
|
15
|
+
const error = args.find((arg): arg is Error => arg instanceof Error)
|
|
16
|
+
writeJSONLine({
|
|
17
|
+
level,
|
|
18
|
+
message,
|
|
19
|
+
source: 'better-auth',
|
|
20
|
+
...(error && { error: { name: error.name, message: error.message } })
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import type { CloudMFAStatus } from '#cloud/server/auth/adapter'
|
|
2
2
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
3
3
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
4
|
+
import { APIError } from 'better-auth'
|
|
4
5
|
import type { Kysely } from 'kysely'
|
|
5
6
|
|
|
7
|
+
import { authRequestPath } from './endpoints'
|
|
8
|
+
|
|
6
9
|
const ASSURANCE_MAX_AGE_MS = 12 * 60 * 60_000
|
|
7
10
|
|
|
8
11
|
export function createMFAAssuranceService(
|
|
@@ -53,3 +56,51 @@ export function createMFAAssuranceService(
|
|
|
53
56
|
}
|
|
54
57
|
|
|
55
58
|
export type MFAAssuranceService = ReturnType<typeof createMFAAssuranceService>
|
|
59
|
+
|
|
60
|
+
/** Records the second step a response just signed in with, against the session it started. */
|
|
61
|
+
export async function recordResponseAssurance(
|
|
62
|
+
response: Response,
|
|
63
|
+
method: 'totp' | 'recovery-code' | 'passkey',
|
|
64
|
+
database: Kysely<CloudDatabase>,
|
|
65
|
+
assurance: MFAAssuranceService
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
const signedToken = response.headers.get('set-auth-token')
|
|
68
|
+
const token = signedToken?.split('.', 1)[0]
|
|
69
|
+
if (!token) return
|
|
70
|
+
const session = await database
|
|
71
|
+
.selectFrom('session')
|
|
72
|
+
.select(['id', 'userId'])
|
|
73
|
+
.where('token', '=', token)
|
|
74
|
+
.executeTakeFirst()
|
|
75
|
+
if (session) await assurance.record({ sessionId: session.id, userId: session.userId, method })
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Checks a second-step code through the two-step plugin's own endpoint, and records the session's
|
|
80
|
+
* assurance when it passes.
|
|
81
|
+
*/
|
|
82
|
+
export async function verifySecondFactor(
|
|
83
|
+
auth: { handler(request: Request): Promise<Response> },
|
|
84
|
+
config: CloudServerConfig,
|
|
85
|
+
database: Kysely<CloudDatabase>,
|
|
86
|
+
assurance: MFAAssuranceService,
|
|
87
|
+
headers: Headers,
|
|
88
|
+
code: string,
|
|
89
|
+
method: 'totp' | 'recovery-code',
|
|
90
|
+
/** The two-step plugin's endpoint that checks this kind of code. */
|
|
91
|
+
endpoint: { path: string }
|
|
92
|
+
): Promise<Response> {
|
|
93
|
+
const response = await auth.handler(
|
|
94
|
+
new Request(new URL(authRequestPath(endpoint.path), config.publicURL), {
|
|
95
|
+
method: 'POST',
|
|
96
|
+
headers: new Headers({
|
|
97
|
+
...Object.fromEntries(headers),
|
|
98
|
+
'Content-Type': 'application/json'
|
|
99
|
+
}),
|
|
100
|
+
body: JSON.stringify({ code, trustDevice: false })
|
|
101
|
+
})
|
|
102
|
+
)
|
|
103
|
+
if (!response.ok) throw APIError.fromStatus(response.status as 401)
|
|
104
|
+
await recordResponseAssurance(response, method, database, assurance)
|
|
105
|
+
return response
|
|
106
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
|
+
import type { BetterAuthOptions } from 'better-auth'
|
|
3
|
+
|
|
4
|
+
import type { AuthenticationEmailService } from './email'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Signing in with an email and password, when the deployment allows it: a verified address, the
|
|
8
|
+
* configured password lengths, and mail about resets when the deployment sends email.
|
|
9
|
+
*/
|
|
10
|
+
export function passwordOptions(
|
|
11
|
+
config: CloudServerConfig,
|
|
12
|
+
authenticationEmail: AuthenticationEmailService | undefined
|
|
13
|
+
): BetterAuthOptions['emailAndPassword'] {
|
|
14
|
+
if (!config.emailPasswordEnabled) return undefined
|
|
15
|
+
return {
|
|
16
|
+
enabled: true,
|
|
17
|
+
disableSignUp: !config.emailPasswordSignUpEnabled,
|
|
18
|
+
requireEmailVerification: true,
|
|
19
|
+
minPasswordLength: config.emailPasswordMinimumLength,
|
|
20
|
+
maxPasswordLength: config.emailPasswordMaximumLength,
|
|
21
|
+
autoSignIn: false,
|
|
22
|
+
resetPasswordTokenExpiresIn: config.passwordResetExpiresIn,
|
|
23
|
+
revokeSessionsOnPasswordReset: true,
|
|
24
|
+
sendResetPassword: authenticationEmail
|
|
25
|
+
? ({ user, url, token }) =>
|
|
26
|
+
authenticationEmail.sendPasswordReset({
|
|
27
|
+
email: user.email,
|
|
28
|
+
name: user.name,
|
|
29
|
+
url,
|
|
30
|
+
token
|
|
31
|
+
})
|
|
32
|
+
: undefined,
|
|
33
|
+
onPasswordReset: authenticationEmail
|
|
34
|
+
? ({ user }) =>
|
|
35
|
+
authenticationEmail.sendPasswordChanged({
|
|
36
|
+
email: user.email,
|
|
37
|
+
name: user.name,
|
|
38
|
+
userId: user.id,
|
|
39
|
+
url: config.publicURL
|
|
40
|
+
})
|
|
41
|
+
: undefined
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -5,6 +5,8 @@ export type CloudActor = {
|
|
|
5
5
|
email: string
|
|
6
6
|
name: string
|
|
7
7
|
deploymentRole?: 'user' | 'admin'
|
|
8
|
+
/** How the request proved who it is: a signed-in session, or a personal access token. */
|
|
9
|
+
credential?: 'session' | 'token'
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export type CloudIdentityResolver = (request: Request) => Promise<CloudIdentity | null>
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CloudActor } from '#cloud/server/auth'
|
|
2
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import { CLOUD_RATE_LIMITS, createRouteRateLimiter } from '#cloud/server/rate-limit'
|
|
4
|
+
import { Hono } from 'hono'
|
|
5
|
+
import type { Kysely } from 'kysely'
|
|
6
|
+
|
|
7
|
+
import type { BillingTokenService } from './tokens'
|
|
8
|
+
|
|
9
|
+
export type BillingRouteEnvironment = { Variables: { actor: CloudActor } }
|
|
10
|
+
|
|
11
|
+
/** Without a billing service, the deployment sells nothing and the token route is not found. */
|
|
12
|
+
export function createBillingRoutes(
|
|
13
|
+
service: BillingTokenService | undefined,
|
|
14
|
+
rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
|
|
15
|
+
) {
|
|
16
|
+
const router = new Hono<BillingRouteEnvironment>()
|
|
17
|
+
if (service && rateLimit) {
|
|
18
|
+
router.use(
|
|
19
|
+
'/billing/token',
|
|
20
|
+
createRouteRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.billingToken)
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
return router.post('/billing/token', async (context) => {
|
|
24
|
+
if (!service) return context.json({ error: { code: 'not_found' as const } }, 404)
|
|
25
|
+
return context.json(await service.issue(context.get('actor')))
|
|
26
|
+
})
|
|
27
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { CLOUD_BILLING_TOKEN_AUDIENCE, type BillingToken } from '#cloud/contract'
|
|
2
|
+
import type { CloudActor } from '#cloud/server/auth'
|
|
3
|
+
import { SERVICES_SIGNING_ALGORITHM, type ServicesSigningKey } from '#cloud/server/services/keys'
|
|
4
|
+
import { SignJWT } from 'jose'
|
|
5
|
+
|
|
6
|
+
export type BillingTokenServiceOptions = {
|
|
7
|
+
/** The Cloud public URL, which billing checks as the token's `iss`. */
|
|
8
|
+
issuer: string
|
|
9
|
+
/** The services' key, whose public half Cloud publishes for billing to verify with. */
|
|
10
|
+
signingKey: ServicesSigningKey
|
|
11
|
+
lifetimeSeconds: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createBillingTokenService(options: BillingTokenServiceOptions) {
|
|
15
|
+
const { privateKey, publicJWK } = options.signingKey
|
|
16
|
+
return {
|
|
17
|
+
/**
|
|
18
|
+
* Signs a token that lets the signed-in person buy or manage their own account's plan and
|
|
19
|
+
* credits with billing; nobody else's, since an account is the person.
|
|
20
|
+
*/
|
|
21
|
+
async issue(actor: CloudActor): Promise<BillingToken> {
|
|
22
|
+
const issuedAt = Math.floor(Date.now() / 1000)
|
|
23
|
+
const expiresAt = issuedAt + options.lifetimeSeconds
|
|
24
|
+
const token = await new SignJWT({ email: actor.email })
|
|
25
|
+
.setProtectedHeader({ alg: SERVICES_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })
|
|
26
|
+
.setIssuer(options.issuer)
|
|
27
|
+
.setAudience(CLOUD_BILLING_TOKEN_AUDIENCE)
|
|
28
|
+
.setSubject(actor.userId)
|
|
29
|
+
.setIssuedAt(issuedAt)
|
|
30
|
+
.setExpirationTime(expiresAt)
|
|
31
|
+
.sign(privateKey)
|
|
32
|
+
return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type BillingTokenService = ReturnType<typeof createBillingTokenService>
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { CloudServerConfig } from '#cloud/server/config'
|
|
2
2
|
import type { CloudDatabase } from '#cloud/server/db'
|
|
3
|
+
import type { TransactionalEmailService } from '#cloud/server/email'
|
|
3
4
|
import type { CloudErrorReporter } from '#cloud/server/errors'
|
|
4
5
|
import type { ObjectStore } from '#cloud/server/objects'
|
|
5
6
|
import type { CloudPolicy } from '#cloud/server/policy/policy'
|
|
7
|
+
import { createStorageLimitNoticeService } from '#cloud/server/quota'
|
|
6
8
|
import { createRateLimitCleanupService } from '#cloud/server/rate-limit/cleanup'
|
|
7
9
|
import type { Kysely } from 'kysely'
|
|
8
10
|
|
|
@@ -14,13 +16,15 @@ import type { CleanupPassOptions, CleanupServices } from './worker'
|
|
|
14
16
|
/**
|
|
15
17
|
* Every cleanup service, over a deployment's database and bucket. Each reports what it couldn't
|
|
16
18
|
* clean through `reportError`, where a deployment tracks errors, and carries on with the rest.
|
|
19
|
+
* With `email`, a deployment that sends mail, it also tells accounts their storage is full.
|
|
17
20
|
*/
|
|
18
21
|
export function createCleanupServices(
|
|
19
|
-
config: Pick<CloudServerConfig, 'deployment'>,
|
|
22
|
+
config: Pick<CloudServerConfig, 'deployment' | 'publicURL' | 'billingEndpoint'>,
|
|
20
23
|
database: Kysely<CloudDatabase>,
|
|
21
24
|
objects: ObjectStore,
|
|
22
25
|
policy: CloudPolicy,
|
|
23
|
-
reportError?: CloudErrorReporter
|
|
26
|
+
reportError?: CloudErrorReporter,
|
|
27
|
+
email?: TransactionalEmailService
|
|
24
28
|
): CleanupServices {
|
|
25
29
|
return {
|
|
26
30
|
uploads: createUploadCleanupService(database, objects, reportError),
|
|
@@ -30,7 +34,16 @@ export function createCleanupServices(
|
|
|
30
34
|
deploymentMode: config.deployment,
|
|
31
35
|
reportError
|
|
32
36
|
}),
|
|
33
|
-
rateLimits: createRateLimitCleanupService(database)
|
|
37
|
+
rateLimits: createRateLimitCleanupService(database),
|
|
38
|
+
storageLimits: email
|
|
39
|
+
? createStorageLimitNoticeService(database, {
|
|
40
|
+
policy,
|
|
41
|
+
email,
|
|
42
|
+
publicURL: config.publicURL,
|
|
43
|
+
upgradable: config.billingEndpoint !== undefined,
|
|
44
|
+
deploymentMode: config.deployment
|
|
45
|
+
})
|
|
46
|
+
: undefined
|
|
34
47
|
}
|
|
35
48
|
}
|
|
36
49
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { StorageLimitNoticeResult, StorageLimitNoticeService } from '#cloud/server/quota'
|
|
2
|
+
|
|
1
3
|
import { startPeriodicWorker } from '../worker/periodic'
|
|
2
4
|
import type { DocumentCleanupResult, DocumentCleanupService } from './documents'
|
|
3
5
|
import {
|
|
@@ -23,6 +25,7 @@ export type CleanupResult = {
|
|
|
23
25
|
documents: DocumentCleanupResult
|
|
24
26
|
revisions: RevisionCompactionResult | null
|
|
25
27
|
rateLimits: number
|
|
28
|
+
storageLimits: StorageLimitNoticeResult | null
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
export type CleanupServices = {
|
|
@@ -30,6 +33,8 @@ export type CleanupServices = {
|
|
|
30
33
|
uploads: UploadCleanupService
|
|
31
34
|
revisions?: RevisionCompactionService
|
|
32
35
|
rateLimits?: { cleanupExpired(before: Date): Promise<number> }
|
|
36
|
+
/** Emails accounts whose storage became full; only where the server sends email. */
|
|
37
|
+
storageLimits?: Pick<StorageLimitNoticeService, 'notifyStorageLimits'>
|
|
33
38
|
}
|
|
34
39
|
|
|
35
40
|
export type CleanupWorker = {
|
|
@@ -66,7 +71,11 @@ export async function runCleanup(
|
|
|
66
71
|
const rateLimits = cleanup.rateLimits
|
|
67
72
|
? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))
|
|
68
73
|
: 0
|
|
69
|
-
|
|
74
|
+
// After documents, so storage they freed counts before anyone is told theirs is full.
|
|
75
|
+
const storageLimits = cleanup.storageLimits
|
|
76
|
+
? await cleanup.storageLimits.notifyStorageLimits()
|
|
77
|
+
: null
|
|
78
|
+
return { uploads, documents, revisions, rateLimits, storageLimits }
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
export function startCleanupWorker(
|