@open-pencil/cloud 0.17.0-beta.4 → 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.
- 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 +783 -47
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +1651 -382
- package/dist/client.js.map +1 -1
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +2 -2
- package/dist/contract2.js +701 -45
- package/dist/contract2.js.map +1 -1
- package/dist/email.d.ts +2138 -34
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +4343 -306
- package/dist/email.js.map +1 -1
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +61 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +1338 -44
- package/dist/index.d.ts.map +1 -1
- package/dist/index2.d.ts +45 -0
- package/dist/index2.d.ts.map +1 -0
- package/dist/listen.mjs +958 -340
- package/dist/listen.mjs.map +1 -1
- package/dist/runtime-cloudflare.d.ts +93 -0
- package/dist/runtime-cloudflare.d.ts.map +1 -0
- package/dist/runtime-cloudflare.js +18032 -0
- package/dist/runtime-cloudflare.js.map +1 -0
- package/dist/runtime-node.d.mts +12615 -5249
- package/dist/runtime-node.d.mts.map +1 -1
- package/dist/server.d.ts +17367 -8567
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +13587 -7333
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +11601 -5401
- package/dist/server.mjs.map +1 -1
- package/dist/server2.mjs +84 -62
- package/dist/server2.mjs.map +1 -1
- package/package.json +31 -5
- package/src/admin/api/routes.ts +263 -190
- package/src/admin/audit/service.ts +11 -3
- package/src/admin/bootstrap.ts +86 -0
- package/src/admin/documents/service.ts +195 -10
- package/src/admin/email/service.ts +2 -1
- package/src/admin/enrollment/email.ts +17 -3
- package/src/admin/enrollment/service.ts +71 -10
- package/src/admin/errors.ts +5 -0
- package/src/admin/index.ts +1 -0
- package/src/admin/reports/service.ts +15 -3
- package/src/admin/schema.ts +6 -5
- package/src/admin/users/service.ts +173 -16
- package/src/client/api.ts +52 -473
- package/src/client/auth/client.ts +22 -3
- package/src/client/comments.ts +205 -0
- package/src/client/community.ts +40 -0
- package/src/client/device-authorization.ts +4 -20
- package/src/client/discovery.ts +39 -11
- package/src/client/documents.ts +160 -0
- package/src/client/files/archive.ts +60 -0
- package/src/client/files/checksum.ts +7 -0
- package/src/client/files/download.ts +122 -0
- package/src/client/files/images.ts +89 -0
- package/src/client/files/index.ts +15 -0
- package/src/client/files/objects.ts +173 -0
- package/src/client/files/save.ts +79 -0
- package/src/client/index.ts +4 -0
- package/src/client/portal/account.ts +73 -3
- package/src/client/portal/administration.ts +52 -5
- package/src/client/portal/request.ts +6 -2
- 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/tour.ts +44 -0
- package/src/client/versions.ts +110 -0
- package/src/contract/account.ts +111 -11
- package/src/contract/admin/index.ts +48 -3
- package/src/contract/billing.ts +235 -0
- package/src/contract/collaboration.ts +5 -0
- package/src/contract/comments.ts +223 -0
- package/src/contract/community.ts +60 -0
- package/src/contract/discovery.ts +94 -5
- package/src/contract/entitlements.ts +10 -0
- package/src/contract/index.ts +64 -5
- package/src/contract/links.ts +62 -4
- package/src/contract/locale.ts +27 -0
- package/src/contract/portal.ts +12 -1
- package/src/contract/relay.ts +3 -1
- package/src/contract/routes.ts +10 -0
- package/src/contract/services.ts +62 -20
- package/src/contract/workspaces.ts +5 -0
- package/src/email/i18n.ts +174 -0
- package/src/email/index.ts +13 -2
- package/src/email/locales/ar.json +169 -0
- package/src/email/locales/de.json +169 -0
- package/src/email/locales/es.json +169 -0
- package/src/email/locales/fr.json +169 -0
- package/src/email/locales/it.json +169 -0
- package/src/email/locales/ja.json +169 -0
- package/src/email/locales/pl.json +169 -0
- package/src/email/locales/pt-br.json +169 -0
- package/src/email/locales/ru.json +169 -0
- package/src/email/locales/zh-cn.json +169 -0
- package/src/email/messages.ts +235 -0
- package/src/email/render.ts +160 -276
- package/src/email/samples.ts +142 -0
- package/src/email/schema.ts +98 -8
- package/src/email/templates/BrandEmail.vue +56 -0
- package/src/email/templates/CommentNotification.vue +39 -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/EnrollmentInvitation.vue +53 -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 +47 -0
- package/src/email/templates/WaitlistConfirmation.vue +29 -0
- package/src/email/templates/WorkspaceInvitation.vue +28 -0
- package/src/email/templates/brand.ts +15 -61
- package/src/email/templates/localization.ts +17 -0
- package/src/errors/index.ts +6 -0
- package/src/{server/errors → errors}/posthog.ts +28 -4
- package/src/global.d.ts +7 -0
- package/src/runtime/cloudflare/email.ts +2 -0
- package/src/runtime/cloudflare/relay/index.ts +28 -7
- package/src/runtime/cloudflare/tsconfig.json +2 -1
- package/src/runtime/cloudflare/worker.ts +14 -1
- package/src/runtime/cloudflare/xml.ts +12 -0
- package/src/runtime/node/admin.ts +51 -47
- package/src/runtime/node/cleanup.ts +5 -1
- package/src/runtime/node/email/runtime.ts +1 -0
- package/src/runtime/node/email/transport.ts +14 -10
- package/src/runtime/node/main.ts +1 -1
- package/src/runtime/node/server.ts +20 -4
- package/src/runtime/node/services/main.ts +1 -1
- package/src/runtime/posthog/errors.ts +5 -2
- 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/actions.ts +3 -1
- package/src/server/account/deletion.ts +40 -4
- package/src/server/account/routes.ts +305 -253
- package/src/server/account/tokens.ts +57 -0
- package/src/server/api/router.ts +44 -6
- package/src/server/app/checks.ts +89 -0
- package/src/server/app/cors.ts +44 -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 +123 -0
- package/src/server/app/services.ts +219 -0
- package/src/server/auth/access-control.ts +13 -8
- package/src/server/auth/access-tokens.ts +62 -0
- package/src/server/auth/account.ts +13 -12
- package/src/server/auth/activity.ts +7 -2
- package/src/server/auth/adapter.ts +36 -3
- package/src/server/auth/email.ts +33 -18
- package/src/server/auth/endpoints.ts +4 -0
- package/src/server/auth/enrollment.ts +116 -0
- package/src/server/auth/factory.ts +165 -189
- package/src/server/auth/index.ts +1 -1
- package/src/server/auth/logger.ts +23 -0
- package/src/server/auth/methods.ts +162 -0
- package/src/server/auth/mfa-assurance.ts +190 -2
- package/src/server/auth/passwords.ts +43 -0
- package/src/server/auth/rate-limit.ts +31 -0
- package/src/server/auth/runtime.ts +19 -5
- package/src/server/auth/session.ts +2 -0
- package/src/server/auth/social-providers.ts +70 -24
- package/src/server/billing/index.ts +8 -0
- package/src/server/billing/notify.ts +55 -0
- package/src/server/billing/routes.ts +27 -0
- package/src/server/billing/seats.ts +17 -0
- package/src/server/billing/tokens.ts +37 -0
- package/src/server/cleanup/configured.ts +16 -3
- package/src/server/cleanup/documents.ts +5 -2
- package/src/server/cleanup/revisions.ts +6 -3
- package/src/server/cleanup/uploads.ts +2 -1
- package/src/server/cleanup/worker.ts +10 -1
- package/src/server/collaboration/relay/connection.ts +7 -2
- package/src/server/collaboration/relay/hub.ts +80 -166
- package/src/server/collaboration/relay/room.ts +154 -0
- package/src/server/collaboration/routes.ts +8 -5
- package/src/server/collaboration/service.ts +21 -2
- package/src/server/comments/index.ts +9 -0
- package/src/server/comments/notify.ts +277 -0
- package/src/server/comments/routes.ts +352 -0
- package/src/server/comments/rows.ts +249 -0
- package/src/server/comments/service.ts +570 -0
- 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 +35 -10
- package/src/server/config/index.ts +2 -2
- package/src/server/config/public.ts +25 -6
- package/src/server/config/schema.ts +53 -293
- package/src/server/config/toml/schema.ts +330 -0
- package/src/server/db/index.ts +3 -1
- package/src/server/db/migrate.ts +33 -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/015_comments.ts +57 -0
- package/src/server/db/migrations/016_comment_notifications.ts +76 -0
- package/src/server/db/migrations/017_invitation_emails.ts +19 -0
- package/src/server/db/migrations/018_enrollment_source.ts +17 -0
- package/src/server/db/migrations/schema.ts +26 -1
- package/src/server/db/tables.ts +122 -3
- package/src/server/db/users.ts +22 -0
- package/src/server/documents/access.ts +17 -0
- package/src/server/documents/images.ts +6 -1
- package/src/server/documents/index.ts +1 -1
- package/src/server/documents/limits.ts +7 -1
- package/src/server/documents/routes.ts +12 -12
- package/src/server/documents/service.ts +31 -407
- package/src/server/documents/summary.ts +15 -0
- package/src/server/documents/uploads.ts +450 -0
- package/src/server/documents/versions/routes.ts +7 -8
- package/src/server/documents/versions/service.ts +86 -26
- package/src/server/email/invitations.ts +1 -0
- package/src/server/email/service.ts +39 -6
- package/src/server/email/types.ts +13 -0
- package/src/server/errors/index.ts +49 -12
- package/src/server/index.ts +27 -6
- package/src/server/internal/routes.ts +8 -2
- package/src/server/internal/service.ts +10 -0
- package/src/server/invitations/budget.ts +3 -1
- package/src/server/invitations/index.ts +1 -0
- package/src/server/invitations/links.ts +6 -0
- package/src/server/invitations/types.ts +5 -1
- package/src/server/objects/types.ts +5 -0
- package/src/server/pictures/service.ts +3 -1
- 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/policy/workspace.ts +5 -2
- 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 +5 -3
- package/src/server/reports/service.ts +27 -3
- package/src/server/services/routes.ts +2 -2
- package/src/server/sharing/capabilities/service.ts +3 -4
- package/src/server/sharing/document-routes.ts +3 -3
- package/src/server/sharing/invitations/service.ts +17 -8
- package/src/server/sharing/routes.ts +15 -15
- package/src/server/validation.ts +35 -24
- package/src/server/workspaces/members.ts +57 -31
- package/src/server/workspaces/repository.ts +23 -12
- package/src/server/workspaces/routes.ts +8 -8
- package/src/services/app.ts +31 -22
- package/src/services/config.ts +48 -8
- package/src/services/metering.ts +15 -27
- 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
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { EnrollmentService } from '#cloud/admin/enrollment/service'
|
|
2
|
+
import { cloudLanguageTagSchema } from '#cloud/contract'
|
|
3
|
+
import { acceptedLocale, emailLocale, isEmailLocale, type EmailLocale } from '#cloud/email'
|
|
4
|
+
import { accountDeletionOptions } from '#cloud/server/account/deletion'
|
|
5
|
+
import type { CloudServerConfig } from '#cloud/server/config'
|
|
6
|
+
import type { CloudDatabase } from '#cloud/server/db'
|
|
7
|
+
import type { BetterAuthOptions } from 'better-auth'
|
|
8
|
+
import type { Kysely } from 'kysely'
|
|
9
|
+
import * as v from 'valibot'
|
|
10
|
+
|
|
11
|
+
import type { AuthenticationEmailService } from './email'
|
|
12
|
+
|
|
13
|
+
/** The language an account writes in, which Better Auth's types don't know it has. */
|
|
14
|
+
function accountLocale(user: object): EmailLocale | null {
|
|
15
|
+
return 'locale' in user && isEmailLocale(user.locale) ? user.locale : null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The language tag the app sent, if any, before it's matched to one Cloud writes in. */
|
|
19
|
+
function languageTag(user: object): string | null {
|
|
20
|
+
return 'locale' in user && typeof user.locale === 'string' ? user.locale : null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Who may join and when an account counts as enrolled: addresses are verified before an account
|
|
25
|
+
* asks for approval or binds an approved invitation, and a closed deployment creates no accounts.
|
|
26
|
+
*/
|
|
27
|
+
export function enrollmentOptions(
|
|
28
|
+
config: CloudServerConfig,
|
|
29
|
+
database: Kysely<CloudDatabase>,
|
|
30
|
+
enrollment: EnrollmentService,
|
|
31
|
+
authenticationEmail: AuthenticationEmailService | undefined,
|
|
32
|
+
emailChangeAvailable: boolean
|
|
33
|
+
) {
|
|
34
|
+
async function enroll(user: { id: string; email: string; name: string }) {
|
|
35
|
+
if (config.enrollmentMode === 'approval') {
|
|
36
|
+
await enrollment.request({ email: user.email, name: user.name })
|
|
37
|
+
}
|
|
38
|
+
await enrollment.bindApprovedUser(user.email, user.id)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
emailVerification:
|
|
43
|
+
config.emailPasswordEnabled && authenticationEmail
|
|
44
|
+
? {
|
|
45
|
+
expiresIn: config.emailVerificationExpiresIn,
|
|
46
|
+
sendOnSignUp: true,
|
|
47
|
+
// Signing in unverified only says so; people ask for another link with Send again.
|
|
48
|
+
sendOnSignIn: false,
|
|
49
|
+
autoSignInAfterVerification: true,
|
|
50
|
+
// A change of address sends the link to the new address as `user.email`, on the
|
|
51
|
+
// account it already confirmed; a new account has not confirmed one yet. This runs
|
|
52
|
+
// inside sign-up's transaction, so it must not query the database itself.
|
|
53
|
+
sendVerificationEmail: ({ user, url, token }) =>
|
|
54
|
+
authenticationEmail.sendVerification({
|
|
55
|
+
email: user.email,
|
|
56
|
+
name: user.name,
|
|
57
|
+
url,
|
|
58
|
+
token,
|
|
59
|
+
purpose: user.emailVerified ? 'change' : 'account',
|
|
60
|
+
// The account carries its language, so nothing is looked up in the transaction.
|
|
61
|
+
locale: accountLocale(user)
|
|
62
|
+
}),
|
|
63
|
+
afterEmailVerification: async (user) => {
|
|
64
|
+
await enrollment.followEmailChange(user.id, user.email)
|
|
65
|
+
await enroll(user)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
: undefined,
|
|
69
|
+
user: {
|
|
70
|
+
additionalFields: {
|
|
71
|
+
// The language Cloud writes to the account in: the app's, sent when signing up and
|
|
72
|
+
// whenever the person changes it, as the nearest language Cloud has (the hooks below).
|
|
73
|
+
locale: {
|
|
74
|
+
type: 'string' as const,
|
|
75
|
+
required: false,
|
|
76
|
+
input: true,
|
|
77
|
+
validator: { input: v.nullish(cloudLanguageTagSchema) }
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
changeEmail: { enabled: emailChangeAvailable },
|
|
81
|
+
deleteUser: accountDeletionOptions(database),
|
|
82
|
+
validateUserInfo: ({ source }) => {
|
|
83
|
+
if (source.action === 'create-user' && config.enrollmentMode === 'closed') {
|
|
84
|
+
return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }
|
|
85
|
+
}
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
databaseHooks: {
|
|
90
|
+
user: {
|
|
91
|
+
create: {
|
|
92
|
+
// The app's language, or for an account it didn't name one for, as one made through
|
|
93
|
+
// Google or Apple, the browser's. A language Cloud doesn't write in reads English.
|
|
94
|
+
before: async (user, context) => {
|
|
95
|
+
const tag = languageTag(user)
|
|
96
|
+
const locale = tag
|
|
97
|
+
? emailLocale([tag])
|
|
98
|
+
: acceptedLocale(context?.headers?.get('accept-language'))
|
|
99
|
+
return { data: { ...user, locale } }
|
|
100
|
+
},
|
|
101
|
+
after: async (user) => {
|
|
102
|
+
if (user.emailVerified) await enroll(user)
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
update: {
|
|
106
|
+
// Whoever changes it, Cloud keeps the nearest language it writes in, or English.
|
|
107
|
+
before: async (user) => {
|
|
108
|
+
if (!('locale' in user)) return undefined
|
|
109
|
+
const tag = languageTag(user)
|
|
110
|
+
return { data: { ...user, locale: emailLocale(tag ? [tag] : []) } }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
} satisfies Pick<BetterAuthOptions, 'emailVerification' | 'user' | 'databaseHooks'>
|
|
116
|
+
}
|
|
@@ -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,32 @@ 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 {
|
|
25
|
-
import {
|
|
30
|
+
import { enrollmentOptions } from './enrollment'
|
|
31
|
+
import { betterAuthLogger } from './logger'
|
|
32
|
+
import { removeSignInMethod, signInMethodHooks, signInProviders } from './methods'
|
|
33
|
+
import { createMFAAssuranceService, createProofRecorder, verifySecondFactor } from './mfa-assurance'
|
|
34
|
+
import { passwordOptions } from './passwords'
|
|
35
|
+
import { authRateLimit } from './rate-limit'
|
|
36
|
+
import { APPLE_AUDIENCE, socialProviders, TRUSTED_SOCIAL_PROVIDERS } from './social-providers'
|
|
26
37
|
|
|
27
38
|
const BETTER_AUTH_SCHEMA_VERSION = '1.7.7+mfa.1'
|
|
39
|
+
const DAY_SECONDS = 24 * 60 * 60
|
|
28
40
|
const ACCOUNT_SECURITY_FRESH_AGE_SECONDS = 10 * 60
|
|
29
41
|
|
|
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
42
|
export type CloudAuthRuntimeOptions = {
|
|
74
43
|
email?: AuthenticationEmailService
|
|
75
44
|
runInBackground?: (promise: Promise<unknown>) => void
|
|
76
45
|
/**
|
|
77
|
-
* Whether Better Auth checks the database schema when it starts
|
|
78
|
-
*
|
|
46
|
+
* Whether Better Auth checks the database schema when it starts, off unless asked for. The check
|
|
47
|
+
* runs in the background and nothing waits for it, so an adapter made briefly, as for one
|
|
48
|
+
* request, for migrating, or in a test, would leave it querying a database being closed;
|
|
49
|
+
* `migrateCloudDatabase` has already checked the recorded version. A server's long-lived
|
|
50
|
+
* adapter turns it on.
|
|
79
51
|
*/
|
|
80
52
|
validateSchema?: boolean
|
|
81
53
|
}
|
|
@@ -92,6 +64,7 @@ export function createBetterAuthAdapter(
|
|
|
92
64
|
const activity = createSignInActivity(database, authenticationEmail)
|
|
93
65
|
// A new address is confirmed through a link sent to it, so changing one needs email delivery.
|
|
94
66
|
const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)
|
|
67
|
+
const providers = signInProviders(config)
|
|
95
68
|
// The plugins are built first, so the options below name their endpoints by the paths they declare.
|
|
96
69
|
const twoStep = twoFactor({
|
|
97
70
|
issuer: 'OpenPencil Cloud',
|
|
@@ -113,21 +86,43 @@ export function createBetterAuthAdapter(
|
|
|
113
86
|
validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')
|
|
114
87
|
})
|
|
115
88
|
const administration = admin()
|
|
89
|
+
// Personal access tokens. Cloud reads them itself (`resolveAccessToken`), for the document API
|
|
90
|
+
// alone, so they never become sessions; Cloud's own limiters count their requests.
|
|
91
|
+
const accessTokens = apiKey({
|
|
92
|
+
defaultPrefix: CLOUD_ACCESS_TOKEN_PREFIX,
|
|
93
|
+
requireName: true,
|
|
94
|
+
maximumNameLength: CLOUD_ACCESS_TOKEN_NAME_MAX_LENGTH,
|
|
95
|
+
startingCharactersConfig: { charactersLength: CLOUD_ACCESS_TOKEN_PREFIX.length + 4 },
|
|
96
|
+
keyExpiration: { minExpiresIn: 1, maxExpiresIn: CLOUD_ACCESS_TOKEN_MAX_DAYS },
|
|
97
|
+
rateLimit: { enabled: false },
|
|
98
|
+
enableSessionForAPIKeys: false
|
|
99
|
+
})
|
|
100
|
+
const joining = enrollmentOptions(
|
|
101
|
+
config,
|
|
102
|
+
database,
|
|
103
|
+
enrollment,
|
|
104
|
+
authenticationEmail,
|
|
105
|
+
emailChangeAvailable
|
|
106
|
+
)
|
|
116
107
|
const auth = betterAuth({
|
|
117
108
|
appName: 'OpenPencil Cloud',
|
|
109
|
+
logger: betterAuthLogger,
|
|
118
110
|
baseURL: config.publicURL,
|
|
119
111
|
basePath: AUTH_BASE_PATH,
|
|
120
|
-
// Clients never reach Better Auth's
|
|
121
|
-
//
|
|
122
|
-
// through its account routes; the server still calls them itself.
|
|
112
|
+
// Clients never reach Better Auth's administration, which `/api/admin` replaces with its own
|
|
113
|
+
// checks, nor the endpoints Cloud's account routes manage; the server still calls them itself.
|
|
123
114
|
disabledPaths: [
|
|
124
115
|
...Object.values(administration.endpoints).map((endpoint) => endpoint.path),
|
|
116
|
+
// Tokens are made, listed, and revoked through `/api/account/tokens`, with a fresh session.
|
|
117
|
+
...Object.values(accessTokens.endpoints).map((endpoint) => endpoint.path),
|
|
125
118
|
passkeys.endpoints.deletePasskey.path,
|
|
126
119
|
twoStep.endpoints.disableTwoFactor.path,
|
|
127
|
-
// Accounts are deleted through `/api/account/delete`,
|
|
128
|
-
// cannot reach either.
|
|
120
|
+
// Accounts are deleted through `/api/account/delete`, closed to accounts awaiting approval.
|
|
129
121
|
CORE_AUTH_PATHS.deleteUser,
|
|
130
|
-
CORE_AUTH_PATHS.deleteUserCallback
|
|
122
|
+
CORE_AUTH_PATHS.deleteUserCallback,
|
|
123
|
+
// Linking and unlinking go through `/api/account/authentication`, with a fresh session.
|
|
124
|
+
CORE_AUTH_PATHS.linkSocialAccount,
|
|
125
|
+
CORE_AUTH_PATHS.unlinkAccount
|
|
131
126
|
],
|
|
132
127
|
secret: config.authSecret,
|
|
133
128
|
database: {
|
|
@@ -140,7 +135,7 @@ export function createBetterAuthAdapter(
|
|
|
140
135
|
accountLinking: {
|
|
141
136
|
enabled: true,
|
|
142
137
|
disableImplicitLinking: false,
|
|
143
|
-
trustedProviders:
|
|
138
|
+
trustedProviders: TRUSTED_SOCIAL_PROVIDERS,
|
|
144
139
|
allowDifferentEmails: false,
|
|
145
140
|
allowUnlinkingAll: false,
|
|
146
141
|
requireLocalEmailVerified: true
|
|
@@ -148,110 +143,16 @@ export function createBetterAuthAdapter(
|
|
|
148
143
|
},
|
|
149
144
|
session: { freshAge: ACCOUNT_SECURITY_FRESH_AGE_SECONDS },
|
|
150
145
|
advanced: {
|
|
151
|
-
database: { generateId: 'uuid', validateSchema: runtime.validateSchema },
|
|
146
|
+
database: { generateId: 'uuid', validateSchema: runtime.validateSchema ?? false },
|
|
152
147
|
ipAddress: {
|
|
153
148
|
ipAddressHeaders: config.authTrustedIPHeaders,
|
|
154
149
|
trustedProxies: config.authTrustedProxies
|
|
155
150
|
},
|
|
156
151
|
...(runtime.runInBackground ? { backgroundTasks: { handler: runtime.runInBackground } } : {})
|
|
157
152
|
},
|
|
158
|
-
rateLimit:
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
window: 60,
|
|
162
|
-
max: 100,
|
|
163
|
-
customRules: {
|
|
164
|
-
[devices.endpoints.deviceCode.path]: { window: 60, max: 10 },
|
|
165
|
-
[devices.endpoints.deviceToken.path]: { window: 60, max: 60 },
|
|
166
|
-
[devices.endpoints.deviceApprove.path]: { window: 60, max: 10 },
|
|
167
|
-
[devices.endpoints.deviceDeny.path]: { window: 60, max: 10 },
|
|
168
|
-
[CORE_AUTH_PATHS.signInEmail]: { window: 10, max: 3 },
|
|
169
|
-
[CORE_AUTH_PATHS.signUpEmail]: { window: 10, max: 3 },
|
|
170
|
-
[CORE_AUTH_PATHS.requestPasswordReset]: { window: 60, max: 3 },
|
|
171
|
-
[CORE_AUTH_PATHS.sendVerificationEmail]: { window: 60, max: 3 }
|
|
172
|
-
}
|
|
173
|
-
},
|
|
174
|
-
emailAndPassword: config.emailPasswordEnabled
|
|
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
|
-
},
|
|
153
|
+
rateLimit: authRateLimit(devices.endpoints),
|
|
154
|
+
emailAndPassword: passwordOptions(config, authenticationEmail),
|
|
155
|
+
...joining,
|
|
255
156
|
plugins: [
|
|
256
157
|
...(config.captchaProvider && config.captchaSecretKey
|
|
257
158
|
? [
|
|
@@ -280,9 +181,11 @@ export function createBetterAuthAdapter(
|
|
|
280
181
|
{ twoStep: twoStep.endpoints, passkeys: passkeys.endpoints, devices: devices.endpoints },
|
|
281
182
|
(user) => notifyTwoStep(user, 'passkey-added')
|
|
282
183
|
),
|
|
283
|
-
providerPictures(createUserPictures(database, { publicURL: config.publicURL }))
|
|
184
|
+
providerPictures(createUserPictures(database, { publicURL: config.publicURL })),
|
|
185
|
+
accessTokens
|
|
284
186
|
],
|
|
285
187
|
socialProviders: socialProviders(config),
|
|
188
|
+
databaseHooks: { ...joining.databaseHooks, ...signInMethodHooks },
|
|
286
189
|
trustedOrigins: [
|
|
287
190
|
config.publicURL,
|
|
288
191
|
...config.trustedOrigins,
|
|
@@ -294,18 +197,35 @@ export function createBetterAuthAdapter(
|
|
|
294
197
|
const deploymentRole = (user: { id: string; role?: string | null }) =>
|
|
295
198
|
user.role === 'admin' ? ('admin' as const) : ('user' as const)
|
|
296
199
|
|
|
297
|
-
|
|
200
|
+
/** The signed-in person, and the session they are signed in with. */
|
|
201
|
+
async function signedIn(headers: Headers) {
|
|
298
202
|
const session = await auth.api.getSession({ headers })
|
|
299
203
|
if (!session) return null
|
|
300
204
|
return {
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
205
|
+
identity: {
|
|
206
|
+
userId: session.user.id,
|
|
207
|
+
email: session.user.email,
|
|
208
|
+
name: session.user.name,
|
|
209
|
+
image: session.user.image ?? null,
|
|
210
|
+
deploymentRole: deploymentRole(session.user)
|
|
211
|
+
},
|
|
212
|
+
sessionId: session.session.id,
|
|
213
|
+
twoFactorEnabled: 'twoFactorEnabled' in session.user && session.user.twoFactorEnabled === true
|
|
306
214
|
}
|
|
307
215
|
}
|
|
308
216
|
|
|
217
|
+
const resolveIdentity = async (headers: Headers) => (await signedIn(headers))?.identity ?? null
|
|
218
|
+
|
|
219
|
+
async function twoStepConfirmed(headers: Headers): Promise<boolean> {
|
|
220
|
+
const signed = await signedIn(headers)
|
|
221
|
+
if (!signed) return false
|
|
222
|
+
return assurance.confirmed({
|
|
223
|
+
sessionId: signed.sessionId,
|
|
224
|
+
userId: signed.identity.userId,
|
|
225
|
+
twoFactorEnabled: signed.twoFactorEnabled
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
309
229
|
/** The signed-in person, read past the cookie cache, for changes about their own account. */
|
|
310
230
|
const currentSession = (headers: Headers) =>
|
|
311
231
|
auth.api.getSession({ headers, query: { disableCookieCache: true } })
|
|
@@ -349,14 +269,41 @@ export function createBetterAuthAdapter(
|
|
|
349
269
|
return identity
|
|
350
270
|
}
|
|
351
271
|
|
|
352
|
-
/**
|
|
272
|
+
/**
|
|
273
|
+
* The signed-in person while their account is approved and their session proved its second step,
|
|
274
|
+
* before or after accepting the terms.
|
|
275
|
+
*/
|
|
353
276
|
async function resolveAccountSession(headers: Headers) {
|
|
354
|
-
const
|
|
355
|
-
if (!
|
|
277
|
+
const signed = await signedIn(headers)
|
|
278
|
+
if (!signed) return null
|
|
279
|
+
const { identity } = signed
|
|
356
280
|
if (config.enrollmentMode === 'approval' && !(await enrollment.isApproved(identity.email))) {
|
|
357
281
|
return null
|
|
358
282
|
}
|
|
359
|
-
|
|
283
|
+
const confirmed = await assurance.confirmed({
|
|
284
|
+
sessionId: signed.sessionId,
|
|
285
|
+
userId: identity.userId,
|
|
286
|
+
twoFactorEnabled: signed.twoFactorEnabled
|
|
287
|
+
})
|
|
288
|
+
return confirmed ? identity : null
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The account a personal access token in `Authorization: Bearer` stands for. */
|
|
292
|
+
async function resolveAccessToken(headers: Headers) {
|
|
293
|
+
const key = bearerAccessToken(headers)
|
|
294
|
+
if (!key) return null
|
|
295
|
+
const verified = await auth.api.verifyApiKey({ body: { key } })
|
|
296
|
+
if (!verified.valid || !verified.key) return null
|
|
297
|
+
const context = { database, config, enrollment, terms }
|
|
298
|
+
const user = await accessTokenAccount(context, verified.key.referenceId)
|
|
299
|
+
if (!user) return null
|
|
300
|
+
return {
|
|
301
|
+
userId: user.id,
|
|
302
|
+
email: user.email,
|
|
303
|
+
name: user.name,
|
|
304
|
+
deploymentRole: deploymentRole(user),
|
|
305
|
+
credential: 'token' as const
|
|
306
|
+
}
|
|
360
307
|
}
|
|
361
308
|
|
|
362
309
|
/**
|
|
@@ -366,6 +313,9 @@ export function createBetterAuthAdapter(
|
|
|
366
313
|
*/
|
|
367
314
|
const activeAccountPaths = new Set(
|
|
368
315
|
[
|
|
316
|
+
// The desktop session it grants counts as two-step proved; only a proved session may grant one.
|
|
317
|
+
auth.api.deviceApprove,
|
|
318
|
+
auth.api.deviceDeny,
|
|
369
319
|
auth.api.generatePasskeyRegistrationOptions,
|
|
370
320
|
auth.api.listPasskeys,
|
|
371
321
|
auth.api.updatePasskey,
|
|
@@ -388,12 +338,13 @@ export function createBetterAuthAdapter(
|
|
|
388
338
|
auth.api.unlinkAccount
|
|
389
339
|
].map((endpoint) => authRequestPath(endpoint.path))
|
|
390
340
|
)
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
341
|
+
const recordProof = createProofRecorder(database, assurance, {
|
|
342
|
+
totp: authRequestPath(twoStep.endpoints.verifyTOTP.path),
|
|
343
|
+
recoveryCode: authRequestPath(twoStep.endpoints.verifyBackupCode.path),
|
|
344
|
+
passkeySignIn: authRequestPath(passkeys.endpoints.verifyPasskeyAuthentication.path),
|
|
345
|
+
passkeyRegistration: authRequestPath(passkeys.endpoints.verifyPasskeyRegistration.path),
|
|
346
|
+
deviceToken: authRequestPath(devices.endpoints.deviceToken.path)
|
|
347
|
+
})
|
|
397
348
|
|
|
398
349
|
return {
|
|
399
350
|
handler: async (request) => {
|
|
@@ -402,14 +353,35 @@ export function createBetterAuthAdapter(
|
|
|
402
353
|
return Response.json({ error: { code: 'unauthorized' } }, { status: 401 })
|
|
403
354
|
}
|
|
404
355
|
const response = await auth.handler(request)
|
|
405
|
-
|
|
406
|
-
if (response.ok && method)
|
|
407
|
-
await recordResponseAssurance(response, method, database, assurance)
|
|
356
|
+
if (response.ok) await recordProof(path, response, () => currentSession(request.headers))
|
|
408
357
|
return response
|
|
409
358
|
},
|
|
410
359
|
resolveIdentity,
|
|
411
360
|
resolveSession,
|
|
412
361
|
resolveAccountSession,
|
|
362
|
+
twoStepConfirmed,
|
|
363
|
+
resolveAccessToken,
|
|
364
|
+
async listAccessTokens(headers) {
|
|
365
|
+
const session = await currentSession(headers)
|
|
366
|
+
if (!session) return null
|
|
367
|
+
const { apiKeys } = await auth.api.listApiKeys({ headers })
|
|
368
|
+
return apiKeys.map(toAccessToken)
|
|
369
|
+
},
|
|
370
|
+
async createAccessToken(headers, input) {
|
|
371
|
+
// A token outlives the session that makes it, so making one needs a recent sign-in.
|
|
372
|
+
const session = await freshSession(headers)
|
|
373
|
+
const created = await auth.api.createApiKey({
|
|
374
|
+
body: {
|
|
375
|
+
name: input.name,
|
|
376
|
+
expiresIn: input.expiresInDays * DAY_SECONDS,
|
|
377
|
+
userId: session.user.id
|
|
378
|
+
}
|
|
379
|
+
})
|
|
380
|
+
return { token: created.key, accessToken: toAccessToken(created) }
|
|
381
|
+
},
|
|
382
|
+
async revokeAccessToken(headers, id) {
|
|
383
|
+
await auth.api.deleteApiKey({ headers, body: { keyId: id } })
|
|
384
|
+
},
|
|
413
385
|
async listAuthenticationMethods(headers) {
|
|
414
386
|
const accounts = await auth.api.listUserAccounts({ headers })
|
|
415
387
|
return accounts.map((account) => ({
|
|
@@ -436,16 +408,13 @@ export function createBetterAuthAdapter(
|
|
|
436
408
|
},
|
|
437
409
|
async startSocialLink(headers, input) {
|
|
438
410
|
await freshSession(headers)
|
|
439
|
-
const
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
})
|
|
448
|
-
return response.url
|
|
411
|
+
const body = { ...input, errorCallbackURL: input.callbackURL, disableRedirect: true }
|
|
412
|
+
const link = await auth.api.linkSocialAccount({ headers, body, returnHeaders: true })
|
|
413
|
+
return { url: link.response.url, headers: link.headers }
|
|
414
|
+
},
|
|
415
|
+
async unlinkAuthenticationMethod(headers, methodId) {
|
|
416
|
+
const session = await freshSession(headers)
|
|
417
|
+
await removeSignInMethod(database, { userId: session.user.id, methodId, providers })
|
|
449
418
|
},
|
|
450
419
|
async deleteAccount(headers, password) {
|
|
451
420
|
const { headers: answer } = await auth.api.deleteUser({
|
|
@@ -455,9 +424,6 @@ export function createBetterAuthAdapter(
|
|
|
455
424
|
})
|
|
456
425
|
return answer
|
|
457
426
|
},
|
|
458
|
-
async unlinkAuthenticationMethod(headers, methodId) {
|
|
459
|
-
await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })
|
|
460
|
-
},
|
|
461
427
|
async banUser(headers, userId, reason) {
|
|
462
428
|
await auth.api.banUser({ headers, body: { userId, banReason: reason } })
|
|
463
429
|
},
|
|
@@ -501,7 +467,8 @@ export function createBetterAuthAdapter(
|
|
|
501
467
|
headers,
|
|
502
468
|
code,
|
|
503
469
|
'totp',
|
|
504
|
-
twoStep.endpoints.verifyTOTP
|
|
470
|
+
twoStep.endpoints.verifyTOTP,
|
|
471
|
+
before ? { id: before.session.id, userId: before.user.id } : null
|
|
505
472
|
)
|
|
506
473
|
// The first code from a new authenticator is what turns it on.
|
|
507
474
|
if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {
|
|
@@ -510,6 +477,7 @@ export function createBetterAuthAdapter(
|
|
|
510
477
|
return response
|
|
511
478
|
},
|
|
512
479
|
async verifyRecoveryCode(headers, code) {
|
|
480
|
+
const current = await currentSession(headers)
|
|
513
481
|
return verifySecondFactor(
|
|
514
482
|
auth,
|
|
515
483
|
config,
|
|
@@ -518,7 +486,8 @@ export function createBetterAuthAdapter(
|
|
|
518
486
|
headers,
|
|
519
487
|
code,
|
|
520
488
|
'recovery-code',
|
|
521
|
-
twoStep.endpoints.verifyBackupCode
|
|
489
|
+
twoStep.endpoints.verifyBackupCode,
|
|
490
|
+
current ? { id: current.session.id, userId: current.user.id } : null
|
|
522
491
|
)
|
|
523
492
|
},
|
|
524
493
|
async generateRecoveryCodes(headers, password) {
|
|
@@ -556,6 +525,9 @@ export function createBetterAuthAdapter(
|
|
|
556
525
|
async updateProfile(headers, input) {
|
|
557
526
|
await auth.api.updateUser({ headers, body: { name: input.name } })
|
|
558
527
|
},
|
|
528
|
+
async setLocale(headers, locale) {
|
|
529
|
+
await auth.api.updateUser({ headers, body: { locale } })
|
|
530
|
+
},
|
|
559
531
|
async changeEmail(headers, input) {
|
|
560
532
|
const session = await freshSession(headers)
|
|
561
533
|
if (session.user.email === input.newEmail) {
|
|
@@ -603,7 +575,11 @@ export function createBetterAuthAdapter(
|
|
|
603
575
|
},
|
|
604
576
|
schemaVersion: BETTER_AUTH_SCHEMA_VERSION,
|
|
605
577
|
async migrate() {
|
|
606
|
-
|
|
578
|
+
// The access token table is Cloud's migration `009_access_tokens`, built before this runs.
|
|
579
|
+
const migrations = await getMigrations({
|
|
580
|
+
...auth.options,
|
|
581
|
+
plugins: auth.options.plugins.filter((plugin) => plugin.id !== accessTokens.id)
|
|
582
|
+
})
|
|
607
583
|
await migrations.runMigrations()
|
|
608
584
|
}
|
|
609
585
|
}
|
package/src/server/auth/index.ts
CHANGED
|
@@ -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,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
|
+
}
|