@terreno/api 57.19.2 → 57.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +443 -0
- package/biome.jsonc +1 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.d.ts +3 -3
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.js +29 -3
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +55 -4
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +4 -0
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +16 -0
- package/dist/terrenoApp.js +18 -0
- package/dist/tests/models.d.ts +22 -22
- package/dist/tests/models.js +15 -1
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +3 -1
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +37 -2
- package/dist/types/mcpServiceToken.d.ts +2 -0
- package/e2e/smoke.ts +193 -0
- package/package.json +10 -5
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +102 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +8 -7
- package/src/api.ts +41 -10
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/auth.test.ts +21 -7
- package/src/authRecovery.test.ts +33 -10
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +490 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +846 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +115 -57
- package/src/betterAuthSetup.ts +457 -38
- package/src/collectionRegistry.test.ts +4 -4
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +38 -0
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +11 -5
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.test.ts +2 -1
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +62 -5
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +23 -0
- package/src/models/mcpServiceToken.ts +10 -0
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +104 -3
- package/src/orgs/orgsApp.ts +69 -28
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/access.ts +4 -1
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +3 -2
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +56 -5
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/realtime/realtime.test.ts +35 -31
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +1 -1
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +5 -4
- package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +34 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +189 -0
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +23 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +1 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +44 -3
- package/src/types/mcpServiceToken.ts +5 -0
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads and changes one user's sign-in security through Better Auth's internal adapter, so the
|
|
3
|
+
* same code works whatever collection names a consumer configures. Never returns secrets: no
|
|
4
|
+
* TOTP secret, no backup codes, no session or OAuth tokens.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {generateRandomString} from "better-auth/crypto";
|
|
8
|
+
import {DateTime} from "luxon";
|
|
9
|
+
import mongoose from "mongoose";
|
|
10
|
+
|
|
11
|
+
import type {User, UserModel} from "../auth";
|
|
12
|
+
import {readBetterAuthMethods} from "../betterAuthMethods";
|
|
13
|
+
import {type BetterAuthInstance, betterAuthResetPasswordUrl} from "../betterAuthSetup";
|
|
14
|
+
import {NotFoundError} from "../errors";
|
|
15
|
+
import {logger} from "../logger";
|
|
16
|
+
import {findOneOrNoneFor} from "../plugins";
|
|
17
|
+
|
|
18
|
+
/** Which features this server has on. The Better Auth ones are all `false` without Better Auth. */
|
|
19
|
+
export interface AccountSecurityFeatures {
|
|
20
|
+
betterAuth: boolean;
|
|
21
|
+
/** Whether the app User model has `disabled` (`isDisabledPlugin`), so accounts can be disabled. */
|
|
22
|
+
disableAccount: boolean;
|
|
23
|
+
multiSession: boolean;
|
|
24
|
+
passkey: boolean;
|
|
25
|
+
twoFactor: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface AccountSecurityProvider {
|
|
29
|
+
/** ISO time the provider was linked, when known. */
|
|
30
|
+
linkedAt: string | null;
|
|
31
|
+
/** Better Auth provider id, such as `github`, `google`, or `mock-oidc`. */
|
|
32
|
+
providerId: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface AccountSecurityPasskey {
|
|
36
|
+
createdAt: string | null;
|
|
37
|
+
id: string;
|
|
38
|
+
name: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface AccountSecurityActionSummary {
|
|
42
|
+
destructive: boolean;
|
|
43
|
+
id: string;
|
|
44
|
+
label: string;
|
|
45
|
+
/** HTTP method of the action's route, such as `POST` or `DELETE`. */
|
|
46
|
+
method: "DELETE" | "POST";
|
|
47
|
+
/**
|
|
48
|
+
* Route path relative to the user's security base (`.../:userId/security`), with `:param`
|
|
49
|
+
* placeholders for values the caller fills from the summary, such as `/passkeys/:passkeyId`.
|
|
50
|
+
*/
|
|
51
|
+
path: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The body of `GET /users/:id/security`. */
|
|
55
|
+
export interface AccountSecuritySummary {
|
|
56
|
+
/** Recovery actions available for this user on this server. */
|
|
57
|
+
actions: AccountSecurityActionSummary[];
|
|
58
|
+
/** Whether the app User is linked to a Better Auth user (`betterAuthId`). */
|
|
59
|
+
betterAuthLinked: boolean;
|
|
60
|
+
/** `User.disabled`. */
|
|
61
|
+
disabled: boolean;
|
|
62
|
+
/** Better Auth `emailVerified` (`false` without a Better Auth link). */
|
|
63
|
+
emailVerified: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Whether the app User has a legacy JWT (passport-local-mongoose) password hash. A user with
|
|
66
|
+
* neither this nor a Better Auth link (a GitHub-JWT user) needs an admin-issued sign-in link.
|
|
67
|
+
*/
|
|
68
|
+
legacyPassword: boolean;
|
|
69
|
+
lastSignIn: {
|
|
70
|
+
/** ISO time of the most recent session start, when known. */
|
|
71
|
+
at: string | null;
|
|
72
|
+
/** Better Auth `lastLoginMethod` (`email`, `github`, `passkey`, ...), when stored. */
|
|
73
|
+
method: string | null;
|
|
74
|
+
};
|
|
75
|
+
passkeys: {count: number; items: AccountSecurityPasskey[]};
|
|
76
|
+
/** Whether the user has a Better Auth email and password credential. */
|
|
77
|
+
password: boolean;
|
|
78
|
+
/** Linked OAuth providers (the password credential is reported as `password`). */
|
|
79
|
+
providers: AccountSecurityProvider[];
|
|
80
|
+
sessions: {active: number};
|
|
81
|
+
twoFactor: {
|
|
82
|
+
/** Unused backup codes, or `null` when 2FA is off or the count cannot be read. */
|
|
83
|
+
backupCodesRemaining: number | null;
|
|
84
|
+
enabled: boolean;
|
|
85
|
+
};
|
|
86
|
+
userId: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The user-facing state the security actions read to decide whether they apply. */
|
|
90
|
+
export type AccountSecurityState = Omit<AccountSecuritySummary, "actions">;
|
|
91
|
+
|
|
92
|
+
interface AdapterWhere {
|
|
93
|
+
field: string;
|
|
94
|
+
operator?: "starts_with";
|
|
95
|
+
value: string;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface BetterAuthAdapterLike {
|
|
99
|
+
create: <T>(args: {data: Record<string, unknown>; model: string}) => Promise<T>;
|
|
100
|
+
delete: (args: {model: string; where: AdapterWhere[]}) => Promise<void>;
|
|
101
|
+
deleteMany: (args: {model: string; where: AdapterWhere[]}) => Promise<number>;
|
|
102
|
+
findMany: <T>(args: {model: string; where: AdapterWhere[]}) => Promise<T[]>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface BetterAuthUserRow {
|
|
106
|
+
email: string;
|
|
107
|
+
emailVerified?: boolean | null;
|
|
108
|
+
id: string;
|
|
109
|
+
lastLoginMethod?: string | null;
|
|
110
|
+
twoFactorEnabled?: boolean | null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface BetterAuthAccountRow {
|
|
114
|
+
createdAt?: Date;
|
|
115
|
+
id: string;
|
|
116
|
+
providerId: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface BetterAuthSessionRow {
|
|
120
|
+
createdAt?: Date;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface BetterAuthPasskeyRow {
|
|
124
|
+
createdAt?: Date;
|
|
125
|
+
id: string;
|
|
126
|
+
name?: string | null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export type VerificationStorageOption =
|
|
130
|
+
| "plain"
|
|
131
|
+
| "hashed"
|
|
132
|
+
| {hash: (identifier: string) => unknown};
|
|
133
|
+
|
|
134
|
+
export type VerificationStoreIdentifier =
|
|
135
|
+
| VerificationStorageOption
|
|
136
|
+
| {default: VerificationStorageOption; overrides?: Record<string, VerificationStorageOption>};
|
|
137
|
+
|
|
138
|
+
/** The parts of Better Auth's context this service uses. */
|
|
139
|
+
interface BetterAuthSecurityContext {
|
|
140
|
+
adapter: BetterAuthAdapterLike;
|
|
141
|
+
baseURL: string;
|
|
142
|
+
internalAdapter: {
|
|
143
|
+
createVerificationValue: (data: {
|
|
144
|
+
expiresAt: Date;
|
|
145
|
+
identifier: string;
|
|
146
|
+
value: string;
|
|
147
|
+
}) => Promise<unknown>;
|
|
148
|
+
deleteUserSessions: (userId: string) => Promise<void>;
|
|
149
|
+
findAccounts: (userId: string) => Promise<BetterAuthAccountRow[]>;
|
|
150
|
+
findUserByEmail: (email: string) => Promise<{user: BetterAuthUserRow} | null>;
|
|
151
|
+
findUserById: (userId: string) => Promise<BetterAuthUserRow | null>;
|
|
152
|
+
listSessions: (
|
|
153
|
+
userId: string,
|
|
154
|
+
options?: {onlyActiveSessions?: boolean}
|
|
155
|
+
) => Promise<BetterAuthSessionRow[]>;
|
|
156
|
+
updateUser: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
|
|
157
|
+
};
|
|
158
|
+
options: Parameters<typeof readBetterAuthMethods>[0]["options"] & {
|
|
159
|
+
emailAndPassword?: {
|
|
160
|
+
resetPasswordTokenExpiresIn?: number;
|
|
161
|
+
sendResetPassword?: (data: {
|
|
162
|
+
token: string;
|
|
163
|
+
url: string;
|
|
164
|
+
user: BetterAuthUserRow;
|
|
165
|
+
}) => Promise<void>;
|
|
166
|
+
};
|
|
167
|
+
verification?: {storeIdentifier?: VerificationStoreIdentifier};
|
|
168
|
+
};
|
|
169
|
+
socialProviders: Parameters<typeof readBetterAuthMethods>[0]["socialProviders"];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
interface ViewBackupCodesApi {
|
|
173
|
+
viewBackupCodes: (args: {body: {userId: string}}) => Promise<{backupCodes?: unknown}>;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Better Auth's provider id for the email and password credential. */
|
|
177
|
+
export const PASSWORD_PROVIDER_ID = "credential";
|
|
178
|
+
|
|
179
|
+
/** Better Auth's default reset-link lifetime, used when `resetPasswordTokenExpiresIn` is unset. */
|
|
180
|
+
const DEFAULT_RESET_TOKEN_SECONDS = 3600;
|
|
181
|
+
|
|
182
|
+
const NO_BETTER_AUTH_FEATURES: Omit<AccountSecurityFeatures, "disableAccount"> = {
|
|
183
|
+
betterAuth: false,
|
|
184
|
+
multiSession: false,
|
|
185
|
+
passkey: false,
|
|
186
|
+
twoFactor: false,
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const toIso = (value: Date | undefined): string | null => {
|
|
190
|
+
if (!value) {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
return DateTime.fromJSDate(value).toUTC().toISO();
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const isCanonicalObjectId = (id: string): boolean => {
|
|
197
|
+
if (!mongoose.isValidObjectId(id)) {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
return new mongoose.Types.ObjectId(id).toString() === id;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/** The app User id as a string. */
|
|
204
|
+
export const userIdOf = (user: User): string => (user._id ? String(user._id) : user.id);
|
|
205
|
+
|
|
206
|
+
const betterAuthIdOf = (user: User): string | undefined => {
|
|
207
|
+
const value = (user as User & {betterAuthId?: unknown}).betterAuthId;
|
|
208
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const latestIso = (sessions: BetterAuthSessionRow[]): string | null => {
|
|
212
|
+
const times = sessions
|
|
213
|
+
.map((session) => session.createdAt)
|
|
214
|
+
.filter((createdAt): createdAt is Date => createdAt instanceof Date)
|
|
215
|
+
.map((createdAt) => DateTime.fromJSDate(createdAt));
|
|
216
|
+
if (times.length === 0) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
return (
|
|
220
|
+
DateTime.max(...times)
|
|
221
|
+
?.toUTC()
|
|
222
|
+
.toISO() ?? null
|
|
223
|
+
);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/** Better Auth's prefix for trusted-device verification identifiers (two-factor plugin). */
|
|
227
|
+
const TRUST_DEVICE_IDENTIFIER_PREFIX = "trust-device-";
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Whether Better Auth stores trusted-device identifiers as written (the default). With a hashed
|
|
231
|
+
* `verification.storeIdentifier` the prefix is gone, so rows can only be matched by user id.
|
|
232
|
+
*/
|
|
233
|
+
export const storesTrustDeviceIdentifiersPlain = (
|
|
234
|
+
storeIdentifier: VerificationStoreIdentifier | undefined
|
|
235
|
+
): boolean => storesIdentifiersPlain(storeIdentifier, TRUST_DEVICE_IDENTIFIER_PREFIX);
|
|
236
|
+
|
|
237
|
+
/** Whether Better Auth stores verification identifiers starting with `identifierPrefix` as written. */
|
|
238
|
+
const storesIdentifiersPlain = (
|
|
239
|
+
storeIdentifier: VerificationStoreIdentifier | undefined,
|
|
240
|
+
identifierPrefix: string
|
|
241
|
+
): boolean => {
|
|
242
|
+
if (!storeIdentifier) {
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
if (typeof storeIdentifier === "object" && "default" in storeIdentifier) {
|
|
246
|
+
for (const [prefix, option] of Object.entries(storeIdentifier.overrides ?? {})) {
|
|
247
|
+
if (identifierPrefix.startsWith(prefix)) {
|
|
248
|
+
return option === "plain";
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return storeIdentifier.default === "plain";
|
|
252
|
+
}
|
|
253
|
+
return storeIdentifier === "plain";
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/** Better Auth's prefix for password-reset verification identifiers. */
|
|
257
|
+
const RESET_PASSWORD_IDENTIFIER_PREFIX = "reset-password:";
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Deletes the user's trusted-device rows (`verification` rows whose value is the Better Auth user
|
|
261
|
+
* id). Returns how many were removed. Rows kept only in Better Auth `secondaryStorage` are not
|
|
262
|
+
* reachable here.
|
|
263
|
+
*/
|
|
264
|
+
const deleteTrustedDevices = async (
|
|
265
|
+
context: BetterAuthSecurityContext,
|
|
266
|
+
betterAuthId: string
|
|
267
|
+
): Promise<number> => {
|
|
268
|
+
const where: AdapterWhere[] = [{field: "value", value: betterAuthId}];
|
|
269
|
+
if (storesTrustDeviceIdentifiersPlain(context.options.verification?.storeIdentifier)) {
|
|
270
|
+
where.push({
|
|
271
|
+
field: "identifier",
|
|
272
|
+
operator: "starts_with",
|
|
273
|
+
value: TRUST_DEVICE_IDENTIFIER_PREFIX,
|
|
274
|
+
});
|
|
275
|
+
} else {
|
|
276
|
+
logger.warn(
|
|
277
|
+
"Better Auth hashes verification identifiers; resetting two-factor removes every verification row for the user"
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
return context.adapter.deleteMany({model: "verification", where});
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
/** One user's sign-in methods as stored by Better Auth. Holds ids only, never key material. */
|
|
284
|
+
export interface AccountSecurityCredentials {
|
|
285
|
+
/** Account rows: one per linked provider account, plus `credential` for the password. */
|
|
286
|
+
accounts: {id: string; providerId: string}[];
|
|
287
|
+
betterAuthId: string;
|
|
288
|
+
/** Better Auth `emailVerified`. */
|
|
289
|
+
emailVerified: boolean;
|
|
290
|
+
/** Passkeys; always empty when the `passkey` feature is off. */
|
|
291
|
+
passkeys: {id: string; name: string | null}[];
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Why a password reset was not sent. */
|
|
295
|
+
export type PasswordResetSkipReason = "not-configured" | "not-linked";
|
|
296
|
+
|
|
297
|
+
export type PasswordResetResult = {sent: true} | {reason: PasswordResetSkipReason; sent: false};
|
|
298
|
+
|
|
299
|
+
/** Why a sign-in link was not issued. */
|
|
300
|
+
export type SignInLinkRefusal =
|
|
301
|
+
/** Better Auth is not running, or `publicAppUrl` is unset so there is no page to link to. */
|
|
302
|
+
| "not-configured"
|
|
303
|
+
/** The User is linked to a Better Auth user that has a sign-in method or a verified email. */
|
|
304
|
+
| "linked"
|
|
305
|
+
/** The User has a legacy password; they can sign up with it instead (T3 migration). */
|
|
306
|
+
| "has-password"
|
|
307
|
+
/** The User has no email to create the Better Auth user with. */
|
|
308
|
+
| "no-email"
|
|
309
|
+
/** Another Better Auth user already uses the email. */
|
|
310
|
+
| "email-taken";
|
|
311
|
+
|
|
312
|
+
export type SignInLinkResult =
|
|
313
|
+
| {betterAuthId: string; expiresAt: string; issued: true; url: string}
|
|
314
|
+
| {issued: false; reason: SignInLinkRefusal};
|
|
315
|
+
|
|
316
|
+
export interface AccountSecurityServiceOptions {
|
|
317
|
+
getAuth: () => BetterAuthInstance | undefined;
|
|
318
|
+
/** The app page base for set-password links (`BetterAuthConfig.publicAppUrl`). */
|
|
319
|
+
getPublicAppUrl?: () => string | undefined;
|
|
320
|
+
getUserModel: () => UserModel;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export interface AccountSecurityService {
|
|
324
|
+
/** Deletes the user's account rows for `providerId`. Returns how many were removed. */
|
|
325
|
+
deleteAccounts: (args: {betterAuthId: string; providerId: string}) => Promise<number>;
|
|
326
|
+
/** Deletes one passkey, only when it belongs to `betterAuthId`. Returns whether it existed. */
|
|
327
|
+
deletePasskey: (args: {betterAuthId: string; passkeyId: string}) => Promise<boolean>;
|
|
328
|
+
/**
|
|
329
|
+
* For a User with no Better Auth link and no legacy password: creates their Better Auth user
|
|
330
|
+
* (email unverified), links it by `betterAuthId`, and returns a single-use set-password link.
|
|
331
|
+
* A User whose link was never used (its Better Auth user still has no sign-in method and an
|
|
332
|
+
* unverified email) gets a fresh link for the same Better Auth user; earlier links stop working.
|
|
333
|
+
*/
|
|
334
|
+
issueSignInLink: (target: User) => Promise<SignInLinkResult>;
|
|
335
|
+
/** The app User with this id, or 404 (an id that is not an ObjectId is also 404). */
|
|
336
|
+
loadTarget: (userId: string) => Promise<User>;
|
|
337
|
+
/** The user's sign-in methods, or `undefined` when the user has no Better Auth link. */
|
|
338
|
+
readCredentials: (
|
|
339
|
+
target: User,
|
|
340
|
+
features: AccountSecurityFeatures
|
|
341
|
+
) => Promise<AccountSecurityCredentials | undefined>;
|
|
342
|
+
readFeatures: () => Promise<AccountSecurityFeatures>;
|
|
343
|
+
readState: (target: User, features: AccountSecurityFeatures) => Promise<AccountSecurityState>;
|
|
344
|
+
/**
|
|
345
|
+
* Removes the user's TOTP secret and backup codes and turns 2FA off. `changed` is false when
|
|
346
|
+
* 2FA was already off (or the user has no Better Auth link).
|
|
347
|
+
*/
|
|
348
|
+
resetTwoFactor: (target: User) => Promise<{changed: boolean}>;
|
|
349
|
+
/**
|
|
350
|
+
* Deletes every Better Auth session the user has (bearer tokens and cookie sessions alike) and,
|
|
351
|
+
* when the User model has `tokenEpoch`, bumps it so legacy JWT refresh tokens stop working.
|
|
352
|
+
* `revokedCount` is how many active sessions were deleted.
|
|
353
|
+
*/
|
|
354
|
+
revokeSessions: (target: User) => Promise<{jwtRefreshRevoked: boolean; revokedCount: number}>;
|
|
355
|
+
/** Sets `User.disabled`. `changed` is false when it already had that value. */
|
|
356
|
+
setDisabled: (target: User, disabled: boolean) => Promise<{changed: boolean}>;
|
|
357
|
+
/**
|
|
358
|
+
* Mails the user a Better Auth password-reset link through the configured
|
|
359
|
+
* `emailAndPassword.sendResetPassword` hook (Terreno's `sendMail` + `publicAppUrl`). The hook
|
|
360
|
+
* is awaited, so a delivery failure (such as the hook's 501 for a missing `publicAppUrl`)
|
|
361
|
+
* throws instead of being logged and dropped as Better Auth's own endpoint does.
|
|
362
|
+
*/
|
|
363
|
+
sendPasswordReset: (target: User) => Promise<PasswordResetResult>;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// The raw collection and schema reads the service makes on the consumer's User model.
|
|
367
|
+
interface UserModelInternals {
|
|
368
|
+
collection: {
|
|
369
|
+
find: (
|
|
370
|
+
filter: Record<string, unknown>,
|
|
371
|
+
options?: {projection: Record<string, number>}
|
|
372
|
+
) => {limit: (count: number) => {next: () => Promise<Record<string, unknown> | null>}};
|
|
373
|
+
};
|
|
374
|
+
schema: {path: (name: string) => unknown};
|
|
375
|
+
updateOne: (
|
|
376
|
+
filter: Record<string, unknown>,
|
|
377
|
+
update: Record<string, unknown>
|
|
378
|
+
) => Promise<{modifiedCount: number}>;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const appUserObjectId = (user: User): unknown => user._id ?? userIdOf(user);
|
|
382
|
+
|
|
383
|
+
export const createAccountSecurityService = ({
|
|
384
|
+
getAuth,
|
|
385
|
+
getPublicAppUrl,
|
|
386
|
+
getUserModel,
|
|
387
|
+
}: AccountSecurityServiceOptions): AccountSecurityService => {
|
|
388
|
+
const userModelInternals = (): UserModelInternals =>
|
|
389
|
+
getUserModel() as unknown as UserModelInternals;
|
|
390
|
+
|
|
391
|
+
const hasSchemaPath = (name: string): boolean => Boolean(userModelInternals().schema?.path(name));
|
|
392
|
+
|
|
393
|
+
/** Whether the User has a passport-local-mongoose hash (stored with `select: false`). */
|
|
394
|
+
const hasLegacyPassword = async (target: User): Promise<boolean> => {
|
|
395
|
+
if (!hasSchemaPath("hash")) {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
const stored = await userModelInternals()
|
|
399
|
+
.collection.find({_id: appUserObjectId(target)}, {projection: {hash: 1}})
|
|
400
|
+
.limit(1)
|
|
401
|
+
.next();
|
|
402
|
+
return typeof stored?.hash === "string" && stored.hash.length > 0;
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
const getContext = async (): Promise<BetterAuthSecurityContext | undefined> => {
|
|
406
|
+
const auth = getAuth();
|
|
407
|
+
if (!auth) {
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
return (await auth.$context) as unknown as BetterAuthSecurityContext;
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
const readFeatures = async (): Promise<AccountSecurityFeatures> => {
|
|
414
|
+
const context = await getContext();
|
|
415
|
+
const disableAccount = hasSchemaPath("disabled");
|
|
416
|
+
if (!context) {
|
|
417
|
+
return {...NO_BETTER_AUTH_FEATURES, disableAccount};
|
|
418
|
+
}
|
|
419
|
+
const methods = readBetterAuthMethods(context);
|
|
420
|
+
return {
|
|
421
|
+
betterAuth: true,
|
|
422
|
+
disableAccount,
|
|
423
|
+
multiSession: methods.multiSession,
|
|
424
|
+
passkey: methods.passkey,
|
|
425
|
+
twoFactor: methods.twoFactor,
|
|
426
|
+
};
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const loadTarget = async (userId: string): Promise<User> => {
|
|
430
|
+
if (!isCanonicalObjectId(userId)) {
|
|
431
|
+
throw new NotFoundError("User not found");
|
|
432
|
+
}
|
|
433
|
+
const user = await findOneOrNoneFor(
|
|
434
|
+
getUserModel() as unknown as mongoose.Model<User>,
|
|
435
|
+
{_id: userId} as never
|
|
436
|
+
);
|
|
437
|
+
if (!user) {
|
|
438
|
+
throw new NotFoundError("User not found");
|
|
439
|
+
}
|
|
440
|
+
return user as unknown as User;
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const countBackupCodes = async (betterAuthUserId: string): Promise<number | null> => {
|
|
444
|
+
const api = getAuth()?.api as unknown as ViewBackupCodesApi;
|
|
445
|
+
try {
|
|
446
|
+
// Better Auth decrypts the codes with its own storage settings; only the count leaves here.
|
|
447
|
+
const result = await api.viewBackupCodes({body: {userId: betterAuthUserId}});
|
|
448
|
+
return Array.isArray(result.backupCodes) ? result.backupCodes.length : null;
|
|
449
|
+
} catch (error: unknown) {
|
|
450
|
+
logger.warn(`Could not count backup codes for Better Auth user ${betterAuthUserId}`, error);
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
const readState = async (
|
|
456
|
+
target: User,
|
|
457
|
+
features: AccountSecurityFeatures
|
|
458
|
+
): Promise<AccountSecurityState> => {
|
|
459
|
+
const empty: AccountSecurityState = {
|
|
460
|
+
betterAuthLinked: false,
|
|
461
|
+
disabled: Boolean((target as User & {disabled?: boolean}).disabled),
|
|
462
|
+
emailVerified: false,
|
|
463
|
+
lastSignIn: {at: null, method: null},
|
|
464
|
+
legacyPassword: await hasLegacyPassword(target),
|
|
465
|
+
passkeys: {count: 0, items: []},
|
|
466
|
+
password: false,
|
|
467
|
+
providers: [],
|
|
468
|
+
sessions: {active: 0},
|
|
469
|
+
twoFactor: {backupCodesRemaining: null, enabled: false},
|
|
470
|
+
userId: userIdOf(target),
|
|
471
|
+
};
|
|
472
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
473
|
+
const context = await getContext();
|
|
474
|
+
if (!betterAuthId || !context) {
|
|
475
|
+
return empty;
|
|
476
|
+
}
|
|
477
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
478
|
+
if (!betterAuthUser) {
|
|
479
|
+
return empty;
|
|
480
|
+
}
|
|
481
|
+
const [accounts, allSessions, activeSessions, passkeyRows] = await Promise.all([
|
|
482
|
+
context.internalAdapter.findAccounts(betterAuthId),
|
|
483
|
+
context.internalAdapter.listSessions(betterAuthId),
|
|
484
|
+
context.internalAdapter.listSessions(betterAuthId, {onlyActiveSessions: true}),
|
|
485
|
+
features.passkey
|
|
486
|
+
? context.adapter.findMany<BetterAuthPasskeyRow>({
|
|
487
|
+
model: "passkey",
|
|
488
|
+
where: [{field: "userId", value: betterAuthId}],
|
|
489
|
+
})
|
|
490
|
+
: Promise.resolve([] as BetterAuthPasskeyRow[]),
|
|
491
|
+
]);
|
|
492
|
+
const twoFactorEnabled = features.twoFactor && betterAuthUser.twoFactorEnabled === true;
|
|
493
|
+
return {
|
|
494
|
+
...empty,
|
|
495
|
+
betterAuthLinked: true,
|
|
496
|
+
emailVerified: betterAuthUser.emailVerified === true,
|
|
497
|
+
lastSignIn: {
|
|
498
|
+
at: latestIso(allSessions),
|
|
499
|
+
method: betterAuthUser.lastLoginMethod ?? null,
|
|
500
|
+
},
|
|
501
|
+
passkeys: {
|
|
502
|
+
count: passkeyRows.length,
|
|
503
|
+
items: passkeyRows.map((row) => ({
|
|
504
|
+
createdAt: toIso(row.createdAt),
|
|
505
|
+
id: String(row.id),
|
|
506
|
+
name: row.name ?? null,
|
|
507
|
+
})),
|
|
508
|
+
},
|
|
509
|
+
password: accounts.some((account) => account.providerId === PASSWORD_PROVIDER_ID),
|
|
510
|
+
providers: accounts
|
|
511
|
+
.filter((account) => account.providerId !== PASSWORD_PROVIDER_ID)
|
|
512
|
+
.map((account) => ({linkedAt: toIso(account.createdAt), providerId: account.providerId}))
|
|
513
|
+
.sort((left, right) => left.providerId.localeCompare(right.providerId)),
|
|
514
|
+
sessions: {active: activeSessions.length},
|
|
515
|
+
twoFactor: {
|
|
516
|
+
backupCodesRemaining: twoFactorEnabled ? await countBackupCodes(betterAuthId) : null,
|
|
517
|
+
enabled: twoFactorEnabled,
|
|
518
|
+
},
|
|
519
|
+
};
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
const resetTwoFactor = async (target: User): Promise<{changed: boolean}> => {
|
|
523
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
524
|
+
const context = await getContext();
|
|
525
|
+
if (!betterAuthId || !context) {
|
|
526
|
+
return {changed: false};
|
|
527
|
+
}
|
|
528
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
529
|
+
if (!betterAuthUser) {
|
|
530
|
+
return {changed: false};
|
|
531
|
+
}
|
|
532
|
+
const where = [{field: "userId", value: betterAuthId}];
|
|
533
|
+
const rows = await context.adapter.findMany<{id: string}>({model: "twoFactor", where});
|
|
534
|
+
const wasEnrolled = betterAuthUser.twoFactorEnabled === true || rows.length > 0;
|
|
535
|
+
if (wasEnrolled) {
|
|
536
|
+
await context.adapter.deleteMany({model: "twoFactor", where});
|
|
537
|
+
await context.internalAdapter.updateUser(betterAuthId, {twoFactorEnabled: false});
|
|
538
|
+
}
|
|
539
|
+
// A trusted browser skips the 2FA challenge for its whole trust period, even after the
|
|
540
|
+
// user enrolls again, so every trusted device goes with the reset.
|
|
541
|
+
const trustedDevicesRemoved = await deleteTrustedDevices(context, betterAuthId);
|
|
542
|
+
return {changed: wasEnrolled || trustedDevicesRemoved > 0};
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
const readCredentials = async (
|
|
546
|
+
target: User,
|
|
547
|
+
features: AccountSecurityFeatures
|
|
548
|
+
): Promise<AccountSecurityCredentials | undefined> => {
|
|
549
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
550
|
+
const context = await getContext();
|
|
551
|
+
if (!betterAuthId || !context) {
|
|
552
|
+
return undefined;
|
|
553
|
+
}
|
|
554
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
555
|
+
if (!betterAuthUser) {
|
|
556
|
+
return undefined;
|
|
557
|
+
}
|
|
558
|
+
const [accounts, passkeyRows] = await Promise.all([
|
|
559
|
+
context.internalAdapter.findAccounts(betterAuthId),
|
|
560
|
+
features.passkey
|
|
561
|
+
? context.adapter.findMany<BetterAuthPasskeyRow>({
|
|
562
|
+
model: "passkey",
|
|
563
|
+
where: [{field: "userId", value: betterAuthId}],
|
|
564
|
+
})
|
|
565
|
+
: Promise.resolve([] as BetterAuthPasskeyRow[]),
|
|
566
|
+
]);
|
|
567
|
+
return {
|
|
568
|
+
accounts: accounts.map((account) => ({
|
|
569
|
+
id: String(account.id),
|
|
570
|
+
providerId: account.providerId,
|
|
571
|
+
})),
|
|
572
|
+
betterAuthId,
|
|
573
|
+
emailVerified: betterAuthUser.emailVerified === true,
|
|
574
|
+
passkeys: passkeyRows.map((row) => ({id: String(row.id), name: row.name ?? null})),
|
|
575
|
+
};
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
const deletePasskey = async ({
|
|
579
|
+
betterAuthId,
|
|
580
|
+
passkeyId,
|
|
581
|
+
}: {
|
|
582
|
+
betterAuthId: string;
|
|
583
|
+
passkeyId: string;
|
|
584
|
+
}): Promise<boolean> => {
|
|
585
|
+
const context = await getContext();
|
|
586
|
+
if (!context) {
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
// Matching on both id and owner means another user's passkey id never deletes anything.
|
|
590
|
+
const where: AdapterWhere[] = [
|
|
591
|
+
{field: "id", value: passkeyId},
|
|
592
|
+
{field: "userId", value: betterAuthId},
|
|
593
|
+
];
|
|
594
|
+
const removed = await context.adapter.deleteMany({model: "passkey", where});
|
|
595
|
+
return removed > 0;
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
const deleteAccounts = async ({
|
|
599
|
+
betterAuthId,
|
|
600
|
+
providerId,
|
|
601
|
+
}: {
|
|
602
|
+
betterAuthId: string;
|
|
603
|
+
providerId: string;
|
|
604
|
+
}): Promise<number> => {
|
|
605
|
+
const context = await getContext();
|
|
606
|
+
if (!context) {
|
|
607
|
+
return 0;
|
|
608
|
+
}
|
|
609
|
+
return context.adapter.deleteMany({
|
|
610
|
+
model: "account",
|
|
611
|
+
where: [
|
|
612
|
+
{field: "userId", value: betterAuthId},
|
|
613
|
+
{field: "providerId", value: providerId},
|
|
614
|
+
],
|
|
615
|
+
});
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Writes the same token, identifier, and lifetime Better Auth's /request-password-reset issues,
|
|
620
|
+
* so its /reset-password endpoint accepts the token, and consumes it there (single use).
|
|
621
|
+
*/
|
|
622
|
+
const createResetToken = async (
|
|
623
|
+
context: BetterAuthSecurityContext,
|
|
624
|
+
betterAuthId: string
|
|
625
|
+
): Promise<{expiresAt: DateTime; token: string}> => {
|
|
626
|
+
// Better Auth's generateId(24): 24 characters from a-z, A-Z, 0-9.
|
|
627
|
+
const token = generateRandomString(24, "a-z", "A-Z", "0-9");
|
|
628
|
+
const expiresInSeconds =
|
|
629
|
+
context.options.emailAndPassword?.resetPasswordTokenExpiresIn || DEFAULT_RESET_TOKEN_SECONDS;
|
|
630
|
+
const expiresAt = DateTime.now().plus({seconds: expiresInSeconds});
|
|
631
|
+
await context.internalAdapter.createVerificationValue({
|
|
632
|
+
expiresAt: expiresAt.toJSDate(),
|
|
633
|
+
identifier: `${RESET_PASSWORD_IDENTIFIER_PREFIX}${token}`,
|
|
634
|
+
value: betterAuthId,
|
|
635
|
+
});
|
|
636
|
+
return {expiresAt, token};
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Whether a Better Auth user looks like one `issueSignInLink` created and nobody has used yet:
|
|
641
|
+
* no account rows (no password, no provider), no passkey, and an unverified email. Only such a
|
|
642
|
+
* user may get a new link, so a reissue never hands over an account someone signs in to.
|
|
643
|
+
*/
|
|
644
|
+
const isUnusedSignInLinkUser = async (
|
|
645
|
+
context: BetterAuthSecurityContext,
|
|
646
|
+
betterAuthUser: BetterAuthUserRow
|
|
647
|
+
): Promise<boolean> => {
|
|
648
|
+
if (betterAuthUser.emailVerified === true) {
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
const accounts = await context.internalAdapter.findAccounts(betterAuthUser.id);
|
|
652
|
+
if (accounts.length > 0) {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
const features = await readFeatures();
|
|
656
|
+
if (!features.passkey) {
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
const passkeys = await context.adapter.findMany<BetterAuthPasskeyRow>({
|
|
660
|
+
model: "passkey",
|
|
661
|
+
where: [{field: "userId", value: betterAuthUser.id}],
|
|
662
|
+
});
|
|
663
|
+
return passkeys.length === 0;
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
/** Deletes the user's outstanding password-reset tokens, so only the newest link works. */
|
|
667
|
+
const deleteResetTokens = async (
|
|
668
|
+
context: BetterAuthSecurityContext,
|
|
669
|
+
betterAuthId: string
|
|
670
|
+
): Promise<void> => {
|
|
671
|
+
if (
|
|
672
|
+
!storesIdentifiersPlain(
|
|
673
|
+
context.options.verification?.storeIdentifier,
|
|
674
|
+
RESET_PASSWORD_IDENTIFIER_PREFIX
|
|
675
|
+
)
|
|
676
|
+
) {
|
|
677
|
+
logger.warn(
|
|
678
|
+
"Better Auth hashes verification identifiers; earlier sign-in links stay valid until they expire"
|
|
679
|
+
);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
await context.adapter.deleteMany({
|
|
683
|
+
model: "verification",
|
|
684
|
+
where: [
|
|
685
|
+
{field: "value", value: betterAuthId},
|
|
686
|
+
{field: "identifier", operator: "starts_with", value: RESET_PASSWORD_IDENTIFIER_PREFIX},
|
|
687
|
+
],
|
|
688
|
+
});
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
const sendPasswordReset = async (target: User): Promise<PasswordResetResult> => {
|
|
692
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
693
|
+
const context = await getContext();
|
|
694
|
+
if (!betterAuthId || !context) {
|
|
695
|
+
return {reason: "not-linked", sent: false};
|
|
696
|
+
}
|
|
697
|
+
const sendResetPassword = context.options.emailAndPassword?.sendResetPassword;
|
|
698
|
+
if (!sendResetPassword) {
|
|
699
|
+
return {reason: "not-configured", sent: false};
|
|
700
|
+
}
|
|
701
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
702
|
+
if (!betterAuthUser) {
|
|
703
|
+
return {reason: "not-linked", sent: false};
|
|
704
|
+
}
|
|
705
|
+
const {token} = await createResetToken(context, betterAuthId);
|
|
706
|
+
await sendResetPassword({
|
|
707
|
+
token,
|
|
708
|
+
url: `${context.baseURL}/reset-password/${token}?callbackURL=`,
|
|
709
|
+
user: betterAuthUser,
|
|
710
|
+
});
|
|
711
|
+
return {sent: true};
|
|
712
|
+
};
|
|
713
|
+
|
|
714
|
+
const revokeSessions = async (
|
|
715
|
+
target: User
|
|
716
|
+
): Promise<{jwtRefreshRevoked: boolean; revokedCount: number}> => {
|
|
717
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
718
|
+
const context = await getContext();
|
|
719
|
+
let revokedCount = 0;
|
|
720
|
+
if (betterAuthId && context) {
|
|
721
|
+
const active = await context.internalAdapter.listSessions(betterAuthId, {
|
|
722
|
+
onlyActiveSessions: true,
|
|
723
|
+
});
|
|
724
|
+
revokedCount = active.length;
|
|
725
|
+
await context.internalAdapter.deleteUserSessions(betterAuthId);
|
|
726
|
+
}
|
|
727
|
+
const jwtRefreshRevoked = hasSchemaPath("tokenEpoch");
|
|
728
|
+
if (jwtRefreshRevoked) {
|
|
729
|
+
await userModelInternals().updateOne({_id: appUserObjectId(target)}, {$inc: {tokenEpoch: 1}});
|
|
730
|
+
}
|
|
731
|
+
return {jwtRefreshRevoked, revokedCount};
|
|
732
|
+
};
|
|
733
|
+
|
|
734
|
+
const setDisabled = async (target: User, disabled: boolean): Promise<{changed: boolean}> => {
|
|
735
|
+
const result = await userModelInternals().updateOne(
|
|
736
|
+
{_id: appUserObjectId(target), disabled: {$ne: disabled}},
|
|
737
|
+
{$set: {disabled}}
|
|
738
|
+
);
|
|
739
|
+
return {changed: result.modifiedCount > 0};
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
const issueSignInLink = async (target: User): Promise<SignInLinkResult> => {
|
|
743
|
+
const context = await getContext();
|
|
744
|
+
const publicAppUrl = getPublicAppUrl?.();
|
|
745
|
+
if (!context || !publicAppUrl) {
|
|
746
|
+
return {issued: false, reason: "not-configured"};
|
|
747
|
+
}
|
|
748
|
+
const previousBetterAuthId = betterAuthIdOf(target);
|
|
749
|
+
const linkedUser = previousBetterAuthId
|
|
750
|
+
? await context.internalAdapter.findUserById(previousBetterAuthId)
|
|
751
|
+
: null;
|
|
752
|
+
if (linkedUser && !(await isUnusedSignInLinkUser(context, linkedUser))) {
|
|
753
|
+
return {issued: false, reason: "linked"};
|
|
754
|
+
}
|
|
755
|
+
if (await hasLegacyPassword(target)) {
|
|
756
|
+
return {issued: false, reason: "has-password"};
|
|
757
|
+
}
|
|
758
|
+
if (linkedUser) {
|
|
759
|
+
await deleteResetTokens(context, linkedUser.id);
|
|
760
|
+
const {expiresAt, token} = await createResetToken(context, linkedUser.id);
|
|
761
|
+
return {
|
|
762
|
+
betterAuthId: linkedUser.id,
|
|
763
|
+
expiresAt: expiresAt.toUTC().toISO() ?? "",
|
|
764
|
+
issued: true,
|
|
765
|
+
url: betterAuthResetPasswordUrl(publicAppUrl, token),
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
const email = typeof target.email === "string" ? target.email.trim().toLowerCase() : "";
|
|
769
|
+
if (!email) {
|
|
770
|
+
return {issued: false, reason: "no-email"};
|
|
771
|
+
}
|
|
772
|
+
if (await context.internalAdapter.findUserByEmail(email)) {
|
|
773
|
+
return {issued: false, reason: "email-taken"};
|
|
774
|
+
}
|
|
775
|
+
const name = (target as User & {name?: unknown}).name;
|
|
776
|
+
const now = DateTime.now().toJSDate();
|
|
777
|
+
// The adapter call skips Better Auth's user.create hooks on purpose: Terreno's guard there
|
|
778
|
+
// refuses an unverified user whose email matches an unclaimed app User, which is exactly the
|
|
779
|
+
// User an administrator is vouching for here. The email stays unverified: the administrator
|
|
780
|
+
// hands the link over themselves, so nothing proves the user controls the inbox.
|
|
781
|
+
const created = await context.adapter.create<{id: string}>({
|
|
782
|
+
data: {
|
|
783
|
+
createdAt: now,
|
|
784
|
+
email,
|
|
785
|
+
emailVerified: false,
|
|
786
|
+
name: typeof name === "string" && name.length > 0 ? name : email.split("@")[0],
|
|
787
|
+
updatedAt: now,
|
|
788
|
+
},
|
|
789
|
+
model: "user",
|
|
790
|
+
});
|
|
791
|
+
const betterAuthId = String(created.id);
|
|
792
|
+
// Link only if nobody linked the User in the meantime (a concurrent link or sign-up).
|
|
793
|
+
const linked = await userModelInternals().updateOne(
|
|
794
|
+
{
|
|
795
|
+
_id: appUserObjectId(target),
|
|
796
|
+
betterAuthId: previousBetterAuthId ?? {$in: [null, ""]},
|
|
797
|
+
},
|
|
798
|
+
{$set: {betterAuthId}}
|
|
799
|
+
);
|
|
800
|
+
if (linked.modifiedCount === 0) {
|
|
801
|
+
await context.adapter.delete({model: "user", where: [{field: "id", value: betterAuthId}]});
|
|
802
|
+
return {issued: false, reason: "linked"};
|
|
803
|
+
}
|
|
804
|
+
const {expiresAt, token} = await createResetToken(context, betterAuthId);
|
|
805
|
+
return {
|
|
806
|
+
betterAuthId,
|
|
807
|
+
expiresAt: expiresAt.toUTC().toISO() ?? "",
|
|
808
|
+
issued: true,
|
|
809
|
+
url: betterAuthResetPasswordUrl(publicAppUrl, token),
|
|
810
|
+
};
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
return {
|
|
814
|
+
deleteAccounts,
|
|
815
|
+
deletePasskey,
|
|
816
|
+
issueSignInLink,
|
|
817
|
+
loadTarget,
|
|
818
|
+
readCredentials,
|
|
819
|
+
readFeatures,
|
|
820
|
+
readState,
|
|
821
|
+
resetTwoFactor,
|
|
822
|
+
revokeSessions,
|
|
823
|
+
sendPasswordReset,
|
|
824
|
+
setDisabled,
|
|
825
|
+
};
|
|
826
|
+
};
|