@terreno/api 57.19.2 → 57.20.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 +393 -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.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/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- 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/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 +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- 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/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- 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 +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -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 +39 -7
- package/src/betterAuthSetup.ts +457 -38
- 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/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- 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 +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Reads and changes one user's sign-in security through Better Auth's internal adapter, so the
|
|
4
|
+
* same code works whatever collection names a consumer configures. Never returns secrets: no
|
|
5
|
+
* TOTP secret, no backup codes, no session or OAuth tokens.
|
|
6
|
+
*/
|
|
7
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
8
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9
|
+
};
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.createAccountSecurityService = exports.storesTrustDeviceIdentifiersPlain = exports.userIdOf = exports.PASSWORD_PROVIDER_ID = void 0;
|
|
12
|
+
const crypto_1 = require("better-auth/crypto");
|
|
13
|
+
const luxon_1 = require("luxon");
|
|
14
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
15
|
+
const betterAuthMethods_1 = require("../betterAuthMethods");
|
|
16
|
+
const betterAuthSetup_1 = require("../betterAuthSetup");
|
|
17
|
+
const errors_1 = require("../errors");
|
|
18
|
+
const logger_1 = require("../logger");
|
|
19
|
+
const plugins_1 = require("../plugins");
|
|
20
|
+
/** Better Auth's provider id for the email and password credential. */
|
|
21
|
+
exports.PASSWORD_PROVIDER_ID = "credential";
|
|
22
|
+
/** Better Auth's default reset-link lifetime, used when `resetPasswordTokenExpiresIn` is unset. */
|
|
23
|
+
const DEFAULT_RESET_TOKEN_SECONDS = 3600;
|
|
24
|
+
const NO_BETTER_AUTH_FEATURES = {
|
|
25
|
+
betterAuth: false,
|
|
26
|
+
multiSession: false,
|
|
27
|
+
passkey: false,
|
|
28
|
+
twoFactor: false,
|
|
29
|
+
};
|
|
30
|
+
const toIso = (value) => {
|
|
31
|
+
if (!value) {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return luxon_1.DateTime.fromJSDate(value).toUTC().toISO();
|
|
35
|
+
};
|
|
36
|
+
const isCanonicalObjectId = (id) => {
|
|
37
|
+
if (!mongoose_1.default.isValidObjectId(id)) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return new mongoose_1.default.Types.ObjectId(id).toString() === id;
|
|
41
|
+
};
|
|
42
|
+
/** The app User id as a string. */
|
|
43
|
+
const userIdOf = (user) => (user._id ? String(user._id) : user.id);
|
|
44
|
+
exports.userIdOf = userIdOf;
|
|
45
|
+
const betterAuthIdOf = (user) => {
|
|
46
|
+
const value = user.betterAuthId;
|
|
47
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
48
|
+
};
|
|
49
|
+
const latestIso = (sessions) => {
|
|
50
|
+
const times = sessions
|
|
51
|
+
.map((session) => session.createdAt)
|
|
52
|
+
.filter((createdAt) => createdAt instanceof Date)
|
|
53
|
+
.map((createdAt) => luxon_1.DateTime.fromJSDate(createdAt));
|
|
54
|
+
if (times.length === 0) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
return (luxon_1.DateTime.max(...times)
|
|
58
|
+
?.toUTC()
|
|
59
|
+
.toISO() ?? null);
|
|
60
|
+
};
|
|
61
|
+
/** Better Auth's prefix for trusted-device verification identifiers (two-factor plugin). */
|
|
62
|
+
const TRUST_DEVICE_IDENTIFIER_PREFIX = "trust-device-";
|
|
63
|
+
/**
|
|
64
|
+
* Whether Better Auth stores trusted-device identifiers as written (the default). With a hashed
|
|
65
|
+
* `verification.storeIdentifier` the prefix is gone, so rows can only be matched by user id.
|
|
66
|
+
*/
|
|
67
|
+
const storesTrustDeviceIdentifiersPlain = (storeIdentifier) => storesIdentifiersPlain(storeIdentifier, TRUST_DEVICE_IDENTIFIER_PREFIX);
|
|
68
|
+
exports.storesTrustDeviceIdentifiersPlain = storesTrustDeviceIdentifiersPlain;
|
|
69
|
+
/** Whether Better Auth stores verification identifiers starting with `identifierPrefix` as written. */
|
|
70
|
+
const storesIdentifiersPlain = (storeIdentifier, identifierPrefix) => {
|
|
71
|
+
if (!storeIdentifier) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
if (typeof storeIdentifier === "object" && "default" in storeIdentifier) {
|
|
75
|
+
for (const [prefix, option] of Object.entries(storeIdentifier.overrides ?? {})) {
|
|
76
|
+
if (identifierPrefix.startsWith(prefix)) {
|
|
77
|
+
return option === "plain";
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return storeIdentifier.default === "plain";
|
|
81
|
+
}
|
|
82
|
+
return storeIdentifier === "plain";
|
|
83
|
+
};
|
|
84
|
+
/** Better Auth's prefix for password-reset verification identifiers. */
|
|
85
|
+
const RESET_PASSWORD_IDENTIFIER_PREFIX = "reset-password:";
|
|
86
|
+
/**
|
|
87
|
+
* Deletes the user's trusted-device rows (`verification` rows whose value is the Better Auth user
|
|
88
|
+
* id). Returns how many were removed. Rows kept only in Better Auth `secondaryStorage` are not
|
|
89
|
+
* reachable here.
|
|
90
|
+
*/
|
|
91
|
+
const deleteTrustedDevices = async (context, betterAuthId) => {
|
|
92
|
+
const where = [{ field: "value", value: betterAuthId }];
|
|
93
|
+
if ((0, exports.storesTrustDeviceIdentifiersPlain)(context.options.verification?.storeIdentifier)) {
|
|
94
|
+
where.push({
|
|
95
|
+
field: "identifier",
|
|
96
|
+
operator: "starts_with",
|
|
97
|
+
value: TRUST_DEVICE_IDENTIFIER_PREFIX,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
logger_1.logger.warn("Better Auth hashes verification identifiers; resetting two-factor removes every verification row for the user");
|
|
102
|
+
}
|
|
103
|
+
return context.adapter.deleteMany({ model: "verification", where });
|
|
104
|
+
};
|
|
105
|
+
const appUserObjectId = (user) => user._id ?? (0, exports.userIdOf)(user);
|
|
106
|
+
const createAccountSecurityService = ({ getAuth, getPublicAppUrl, getUserModel, }) => {
|
|
107
|
+
const userModelInternals = () => getUserModel();
|
|
108
|
+
const hasSchemaPath = (name) => Boolean(userModelInternals().schema?.path(name));
|
|
109
|
+
/** Whether the User has a passport-local-mongoose hash (stored with `select: false`). */
|
|
110
|
+
const hasLegacyPassword = async (target) => {
|
|
111
|
+
if (!hasSchemaPath("hash")) {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
const stored = await userModelInternals()
|
|
115
|
+
.collection.find({ _id: appUserObjectId(target) }, { projection: { hash: 1 } })
|
|
116
|
+
.limit(1)
|
|
117
|
+
.next();
|
|
118
|
+
return typeof stored?.hash === "string" && stored.hash.length > 0;
|
|
119
|
+
};
|
|
120
|
+
const getContext = async () => {
|
|
121
|
+
const auth = getAuth();
|
|
122
|
+
if (!auth) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
return (await auth.$context);
|
|
126
|
+
};
|
|
127
|
+
const readFeatures = async () => {
|
|
128
|
+
const context = await getContext();
|
|
129
|
+
const disableAccount = hasSchemaPath("disabled");
|
|
130
|
+
if (!context) {
|
|
131
|
+
return { ...NO_BETTER_AUTH_FEATURES, disableAccount };
|
|
132
|
+
}
|
|
133
|
+
const methods = (0, betterAuthMethods_1.readBetterAuthMethods)(context);
|
|
134
|
+
return {
|
|
135
|
+
betterAuth: true,
|
|
136
|
+
disableAccount,
|
|
137
|
+
multiSession: methods.multiSession,
|
|
138
|
+
passkey: methods.passkey,
|
|
139
|
+
twoFactor: methods.twoFactor,
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
const loadTarget = async (userId) => {
|
|
143
|
+
if (!isCanonicalObjectId(userId)) {
|
|
144
|
+
throw new errors_1.NotFoundError("User not found");
|
|
145
|
+
}
|
|
146
|
+
const user = await (0, plugins_1.findOneOrNoneFor)(getUserModel(), { _id: userId });
|
|
147
|
+
if (!user) {
|
|
148
|
+
throw new errors_1.NotFoundError("User not found");
|
|
149
|
+
}
|
|
150
|
+
return user;
|
|
151
|
+
};
|
|
152
|
+
const countBackupCodes = async (betterAuthUserId) => {
|
|
153
|
+
const api = getAuth()?.api;
|
|
154
|
+
try {
|
|
155
|
+
// Better Auth decrypts the codes with its own storage settings; only the count leaves here.
|
|
156
|
+
const result = await api.viewBackupCodes({ body: { userId: betterAuthUserId } });
|
|
157
|
+
return Array.isArray(result.backupCodes) ? result.backupCodes.length : null;
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
logger_1.logger.warn(`Could not count backup codes for Better Auth user ${betterAuthUserId}`, error);
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
const readState = async (target, features) => {
|
|
165
|
+
const empty = {
|
|
166
|
+
betterAuthLinked: false,
|
|
167
|
+
disabled: Boolean(target.disabled),
|
|
168
|
+
emailVerified: false,
|
|
169
|
+
lastSignIn: { at: null, method: null },
|
|
170
|
+
legacyPassword: await hasLegacyPassword(target),
|
|
171
|
+
passkeys: { count: 0, items: [] },
|
|
172
|
+
password: false,
|
|
173
|
+
providers: [],
|
|
174
|
+
sessions: { active: 0 },
|
|
175
|
+
twoFactor: { backupCodesRemaining: null, enabled: false },
|
|
176
|
+
userId: (0, exports.userIdOf)(target),
|
|
177
|
+
};
|
|
178
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
179
|
+
const context = await getContext();
|
|
180
|
+
if (!betterAuthId || !context) {
|
|
181
|
+
return empty;
|
|
182
|
+
}
|
|
183
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
184
|
+
if (!betterAuthUser) {
|
|
185
|
+
return empty;
|
|
186
|
+
}
|
|
187
|
+
const [accounts, allSessions, activeSessions, passkeyRows] = await Promise.all([
|
|
188
|
+
context.internalAdapter.findAccounts(betterAuthId),
|
|
189
|
+
context.internalAdapter.listSessions(betterAuthId),
|
|
190
|
+
context.internalAdapter.listSessions(betterAuthId, { onlyActiveSessions: true }),
|
|
191
|
+
features.passkey
|
|
192
|
+
? context.adapter.findMany({
|
|
193
|
+
model: "passkey",
|
|
194
|
+
where: [{ field: "userId", value: betterAuthId }],
|
|
195
|
+
})
|
|
196
|
+
: Promise.resolve([]),
|
|
197
|
+
]);
|
|
198
|
+
const twoFactorEnabled = features.twoFactor && betterAuthUser.twoFactorEnabled === true;
|
|
199
|
+
return {
|
|
200
|
+
...empty,
|
|
201
|
+
betterAuthLinked: true,
|
|
202
|
+
emailVerified: betterAuthUser.emailVerified === true,
|
|
203
|
+
lastSignIn: {
|
|
204
|
+
at: latestIso(allSessions),
|
|
205
|
+
method: betterAuthUser.lastLoginMethod ?? null,
|
|
206
|
+
},
|
|
207
|
+
passkeys: {
|
|
208
|
+
count: passkeyRows.length,
|
|
209
|
+
items: passkeyRows.map((row) => ({
|
|
210
|
+
createdAt: toIso(row.createdAt),
|
|
211
|
+
id: String(row.id),
|
|
212
|
+
name: row.name ?? null,
|
|
213
|
+
})),
|
|
214
|
+
},
|
|
215
|
+
password: accounts.some((account) => account.providerId === exports.PASSWORD_PROVIDER_ID),
|
|
216
|
+
providers: accounts
|
|
217
|
+
.filter((account) => account.providerId !== exports.PASSWORD_PROVIDER_ID)
|
|
218
|
+
.map((account) => ({ linkedAt: toIso(account.createdAt), providerId: account.providerId }))
|
|
219
|
+
.sort((left, right) => left.providerId.localeCompare(right.providerId)),
|
|
220
|
+
sessions: { active: activeSessions.length },
|
|
221
|
+
twoFactor: {
|
|
222
|
+
backupCodesRemaining: twoFactorEnabled ? await countBackupCodes(betterAuthId) : null,
|
|
223
|
+
enabled: twoFactorEnabled,
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
const resetTwoFactor = async (target) => {
|
|
228
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
229
|
+
const context = await getContext();
|
|
230
|
+
if (!betterAuthId || !context) {
|
|
231
|
+
return { changed: false };
|
|
232
|
+
}
|
|
233
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
234
|
+
if (!betterAuthUser) {
|
|
235
|
+
return { changed: false };
|
|
236
|
+
}
|
|
237
|
+
const where = [{ field: "userId", value: betterAuthId }];
|
|
238
|
+
const rows = await context.adapter.findMany({ model: "twoFactor", where });
|
|
239
|
+
const wasEnrolled = betterAuthUser.twoFactorEnabled === true || rows.length > 0;
|
|
240
|
+
if (wasEnrolled) {
|
|
241
|
+
await context.adapter.deleteMany({ model: "twoFactor", where });
|
|
242
|
+
await context.internalAdapter.updateUser(betterAuthId, { twoFactorEnabled: false });
|
|
243
|
+
}
|
|
244
|
+
// A trusted browser skips the 2FA challenge for its whole trust period, even after the
|
|
245
|
+
// user enrolls again, so every trusted device goes with the reset.
|
|
246
|
+
const trustedDevicesRemoved = await deleteTrustedDevices(context, betterAuthId);
|
|
247
|
+
return { changed: wasEnrolled || trustedDevicesRemoved > 0 };
|
|
248
|
+
};
|
|
249
|
+
const readCredentials = async (target, features) => {
|
|
250
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
251
|
+
const context = await getContext();
|
|
252
|
+
if (!betterAuthId || !context) {
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
256
|
+
if (!betterAuthUser) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
const [accounts, passkeyRows] = await Promise.all([
|
|
260
|
+
context.internalAdapter.findAccounts(betterAuthId),
|
|
261
|
+
features.passkey
|
|
262
|
+
? context.adapter.findMany({
|
|
263
|
+
model: "passkey",
|
|
264
|
+
where: [{ field: "userId", value: betterAuthId }],
|
|
265
|
+
})
|
|
266
|
+
: Promise.resolve([]),
|
|
267
|
+
]);
|
|
268
|
+
return {
|
|
269
|
+
accounts: accounts.map((account) => ({
|
|
270
|
+
id: String(account.id),
|
|
271
|
+
providerId: account.providerId,
|
|
272
|
+
})),
|
|
273
|
+
betterAuthId,
|
|
274
|
+
emailVerified: betterAuthUser.emailVerified === true,
|
|
275
|
+
passkeys: passkeyRows.map((row) => ({ id: String(row.id), name: row.name ?? null })),
|
|
276
|
+
};
|
|
277
|
+
};
|
|
278
|
+
const deletePasskey = async ({ betterAuthId, passkeyId, }) => {
|
|
279
|
+
const context = await getContext();
|
|
280
|
+
if (!context) {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
// Matching on both id and owner means another user's passkey id never deletes anything.
|
|
284
|
+
const where = [
|
|
285
|
+
{ field: "id", value: passkeyId },
|
|
286
|
+
{ field: "userId", value: betterAuthId },
|
|
287
|
+
];
|
|
288
|
+
const removed = await context.adapter.deleteMany({ model: "passkey", where });
|
|
289
|
+
return removed > 0;
|
|
290
|
+
};
|
|
291
|
+
const deleteAccounts = async ({ betterAuthId, providerId, }) => {
|
|
292
|
+
const context = await getContext();
|
|
293
|
+
if (!context) {
|
|
294
|
+
return 0;
|
|
295
|
+
}
|
|
296
|
+
return context.adapter.deleteMany({
|
|
297
|
+
model: "account",
|
|
298
|
+
where: [
|
|
299
|
+
{ field: "userId", value: betterAuthId },
|
|
300
|
+
{ field: "providerId", value: providerId },
|
|
301
|
+
],
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
/**
|
|
305
|
+
* Writes the same token, identifier, and lifetime Better Auth's /request-password-reset issues,
|
|
306
|
+
* so its /reset-password endpoint accepts the token, and consumes it there (single use).
|
|
307
|
+
*/
|
|
308
|
+
const createResetToken = async (context, betterAuthId) => {
|
|
309
|
+
// Better Auth's generateId(24): 24 characters from a-z, A-Z, 0-9.
|
|
310
|
+
const token = (0, crypto_1.generateRandomString)(24, "a-z", "A-Z", "0-9");
|
|
311
|
+
const expiresInSeconds = context.options.emailAndPassword?.resetPasswordTokenExpiresIn || DEFAULT_RESET_TOKEN_SECONDS;
|
|
312
|
+
const expiresAt = luxon_1.DateTime.now().plus({ seconds: expiresInSeconds });
|
|
313
|
+
await context.internalAdapter.createVerificationValue({
|
|
314
|
+
expiresAt: expiresAt.toJSDate(),
|
|
315
|
+
identifier: `${RESET_PASSWORD_IDENTIFIER_PREFIX}${token}`,
|
|
316
|
+
value: betterAuthId,
|
|
317
|
+
});
|
|
318
|
+
return { expiresAt, token };
|
|
319
|
+
};
|
|
320
|
+
/**
|
|
321
|
+
* Whether a Better Auth user looks like one `issueSignInLink` created and nobody has used yet:
|
|
322
|
+
* no account rows (no password, no provider), no passkey, and an unverified email. Only such a
|
|
323
|
+
* user may get a new link, so a reissue never hands over an account someone signs in to.
|
|
324
|
+
*/
|
|
325
|
+
const isUnusedSignInLinkUser = async (context, betterAuthUser) => {
|
|
326
|
+
if (betterAuthUser.emailVerified === true) {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
const accounts = await context.internalAdapter.findAccounts(betterAuthUser.id);
|
|
330
|
+
if (accounts.length > 0) {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
const features = await readFeatures();
|
|
334
|
+
if (!features.passkey) {
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
const passkeys = await context.adapter.findMany({
|
|
338
|
+
model: "passkey",
|
|
339
|
+
where: [{ field: "userId", value: betterAuthUser.id }],
|
|
340
|
+
});
|
|
341
|
+
return passkeys.length === 0;
|
|
342
|
+
};
|
|
343
|
+
/** Deletes the user's outstanding password-reset tokens, so only the newest link works. */
|
|
344
|
+
const deleteResetTokens = async (context, betterAuthId) => {
|
|
345
|
+
if (!storesIdentifiersPlain(context.options.verification?.storeIdentifier, RESET_PASSWORD_IDENTIFIER_PREFIX)) {
|
|
346
|
+
logger_1.logger.warn("Better Auth hashes verification identifiers; earlier sign-in links stay valid until they expire");
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
await context.adapter.deleteMany({
|
|
350
|
+
model: "verification",
|
|
351
|
+
where: [
|
|
352
|
+
{ field: "value", value: betterAuthId },
|
|
353
|
+
{ field: "identifier", operator: "starts_with", value: RESET_PASSWORD_IDENTIFIER_PREFIX },
|
|
354
|
+
],
|
|
355
|
+
});
|
|
356
|
+
};
|
|
357
|
+
const sendPasswordReset = async (target) => {
|
|
358
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
359
|
+
const context = await getContext();
|
|
360
|
+
if (!betterAuthId || !context) {
|
|
361
|
+
return { reason: "not-linked", sent: false };
|
|
362
|
+
}
|
|
363
|
+
const sendResetPassword = context.options.emailAndPassword?.sendResetPassword;
|
|
364
|
+
if (!sendResetPassword) {
|
|
365
|
+
return { reason: "not-configured", sent: false };
|
|
366
|
+
}
|
|
367
|
+
const betterAuthUser = await context.internalAdapter.findUserById(betterAuthId);
|
|
368
|
+
if (!betterAuthUser) {
|
|
369
|
+
return { reason: "not-linked", sent: false };
|
|
370
|
+
}
|
|
371
|
+
const { token } = await createResetToken(context, betterAuthId);
|
|
372
|
+
await sendResetPassword({
|
|
373
|
+
token,
|
|
374
|
+
url: `${context.baseURL}/reset-password/${token}?callbackURL=`,
|
|
375
|
+
user: betterAuthUser,
|
|
376
|
+
});
|
|
377
|
+
return { sent: true };
|
|
378
|
+
};
|
|
379
|
+
const revokeSessions = async (target) => {
|
|
380
|
+
const betterAuthId = betterAuthIdOf(target);
|
|
381
|
+
const context = await getContext();
|
|
382
|
+
let revokedCount = 0;
|
|
383
|
+
if (betterAuthId && context) {
|
|
384
|
+
const active = await context.internalAdapter.listSessions(betterAuthId, {
|
|
385
|
+
onlyActiveSessions: true,
|
|
386
|
+
});
|
|
387
|
+
revokedCount = active.length;
|
|
388
|
+
await context.internalAdapter.deleteUserSessions(betterAuthId);
|
|
389
|
+
}
|
|
390
|
+
const jwtRefreshRevoked = hasSchemaPath("tokenEpoch");
|
|
391
|
+
if (jwtRefreshRevoked) {
|
|
392
|
+
await userModelInternals().updateOne({ _id: appUserObjectId(target) }, { $inc: { tokenEpoch: 1 } });
|
|
393
|
+
}
|
|
394
|
+
return { jwtRefreshRevoked, revokedCount };
|
|
395
|
+
};
|
|
396
|
+
const setDisabled = async (target, disabled) => {
|
|
397
|
+
const result = await userModelInternals().updateOne({ _id: appUserObjectId(target), disabled: { $ne: disabled } }, { $set: { disabled } });
|
|
398
|
+
return { changed: result.modifiedCount > 0 };
|
|
399
|
+
};
|
|
400
|
+
const issueSignInLink = async (target) => {
|
|
401
|
+
const context = await getContext();
|
|
402
|
+
const publicAppUrl = getPublicAppUrl?.();
|
|
403
|
+
if (!context || !publicAppUrl) {
|
|
404
|
+
return { issued: false, reason: "not-configured" };
|
|
405
|
+
}
|
|
406
|
+
const previousBetterAuthId = betterAuthIdOf(target);
|
|
407
|
+
const linkedUser = previousBetterAuthId
|
|
408
|
+
? await context.internalAdapter.findUserById(previousBetterAuthId)
|
|
409
|
+
: null;
|
|
410
|
+
if (linkedUser && !(await isUnusedSignInLinkUser(context, linkedUser))) {
|
|
411
|
+
return { issued: false, reason: "linked" };
|
|
412
|
+
}
|
|
413
|
+
if (await hasLegacyPassword(target)) {
|
|
414
|
+
return { issued: false, reason: "has-password" };
|
|
415
|
+
}
|
|
416
|
+
if (linkedUser) {
|
|
417
|
+
await deleteResetTokens(context, linkedUser.id);
|
|
418
|
+
const { expiresAt, token } = await createResetToken(context, linkedUser.id);
|
|
419
|
+
return {
|
|
420
|
+
betterAuthId: linkedUser.id,
|
|
421
|
+
expiresAt: expiresAt.toUTC().toISO() ?? "",
|
|
422
|
+
issued: true,
|
|
423
|
+
url: (0, betterAuthSetup_1.betterAuthResetPasswordUrl)(publicAppUrl, token),
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
const email = typeof target.email === "string" ? target.email.trim().toLowerCase() : "";
|
|
427
|
+
if (!email) {
|
|
428
|
+
return { issued: false, reason: "no-email" };
|
|
429
|
+
}
|
|
430
|
+
if (await context.internalAdapter.findUserByEmail(email)) {
|
|
431
|
+
return { issued: false, reason: "email-taken" };
|
|
432
|
+
}
|
|
433
|
+
const name = target.name;
|
|
434
|
+
const now = luxon_1.DateTime.now().toJSDate();
|
|
435
|
+
// The adapter call skips Better Auth's user.create hooks on purpose: Terreno's guard there
|
|
436
|
+
// refuses an unverified user whose email matches an unclaimed app User, which is exactly the
|
|
437
|
+
// User an administrator is vouching for here. The email stays unverified: the administrator
|
|
438
|
+
// hands the link over themselves, so nothing proves the user controls the inbox.
|
|
439
|
+
const created = await context.adapter.create({
|
|
440
|
+
data: {
|
|
441
|
+
createdAt: now,
|
|
442
|
+
email,
|
|
443
|
+
emailVerified: false,
|
|
444
|
+
name: typeof name === "string" && name.length > 0 ? name : email.split("@")[0],
|
|
445
|
+
updatedAt: now,
|
|
446
|
+
},
|
|
447
|
+
model: "user",
|
|
448
|
+
});
|
|
449
|
+
const betterAuthId = String(created.id);
|
|
450
|
+
// Link only if nobody linked the User in the meantime (a concurrent link or sign-up).
|
|
451
|
+
const linked = await userModelInternals().updateOne({
|
|
452
|
+
_id: appUserObjectId(target),
|
|
453
|
+
betterAuthId: previousBetterAuthId ?? { $in: [null, ""] },
|
|
454
|
+
}, { $set: { betterAuthId } });
|
|
455
|
+
if (linked.modifiedCount === 0) {
|
|
456
|
+
await context.adapter.delete({ model: "user", where: [{ field: "id", value: betterAuthId }] });
|
|
457
|
+
return { issued: false, reason: "linked" };
|
|
458
|
+
}
|
|
459
|
+
const { expiresAt, token } = await createResetToken(context, betterAuthId);
|
|
460
|
+
return {
|
|
461
|
+
betterAuthId,
|
|
462
|
+
expiresAt: expiresAt.toUTC().toISO() ?? "",
|
|
463
|
+
issued: true,
|
|
464
|
+
url: (0, betterAuthSetup_1.betterAuthResetPasswordUrl)(publicAppUrl, token),
|
|
465
|
+
};
|
|
466
|
+
};
|
|
467
|
+
return {
|
|
468
|
+
deleteAccounts,
|
|
469
|
+
deletePasskey,
|
|
470
|
+
issueSignInLink,
|
|
471
|
+
loadTarget,
|
|
472
|
+
readCredentials,
|
|
473
|
+
readFeatures,
|
|
474
|
+
readState,
|
|
475
|
+
resetTwoFactor,
|
|
476
|
+
revokeSessions,
|
|
477
|
+
sendPasswordReset,
|
|
478
|
+
setDisabled,
|
|
479
|
+
};
|
|
480
|
+
};
|
|
481
|
+
exports.createAccountSecurityService = createAccountSecurityService;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential recovery actions: remove one of a user's passkeys, and unlink a sign-in provider.
|
|
3
|
+
*
|
|
4
|
+
* Unlinking never removes the password (`credential`) account. Neither action leaves a user with
|
|
5
|
+
* no way to sign in: removing the last sign-in method is allowed only when the user's email is
|
|
6
|
+
* verified, and then a password-reset link is mailed so they can set a password (Q5).
|
|
7
|
+
*/
|
|
8
|
+
import type { SecurityRouteAction } from "./accountSecurityApp";
|
|
9
|
+
/** `DELETE /:userId/security/passkeys/:passkeyId`: remove one of the user's passkeys. */
|
|
10
|
+
export declare const removePasskeyAction: SecurityRouteAction;
|
|
11
|
+
/**
|
|
12
|
+
* `DELETE /:userId/security/accounts/:providerId`: unlink every account the user has with that
|
|
13
|
+
* provider. Provider account ids are never exposed, so a user who linked two accounts of one
|
|
14
|
+
* provider loses both.
|
|
15
|
+
*/
|
|
16
|
+
export declare const unlinkProviderAction: SecurityRouteAction;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Credential recovery actions: remove one of a user's passkeys, and unlink a sign-in provider.
|
|
4
|
+
*
|
|
5
|
+
* Unlinking never removes the password (`credential`) account. Neither action leaves a user with
|
|
6
|
+
* no way to sign in: removing the last sign-in method is allowed only when the user's email is
|
|
7
|
+
* verified, and then a password-reset link is mailed so they can set a password (Q5).
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.unlinkProviderAction = exports.removePasskeyAction = void 0;
|
|
11
|
+
const errors_1 = require("../errors");
|
|
12
|
+
const logger_1 = require("../logger");
|
|
13
|
+
const accountSecurityService_1 = require("./accountSecurityService");
|
|
14
|
+
const securityEvents_1 = require("./securityEvents");
|
|
15
|
+
const PASSKEY_NOT_FOUND_TITLE = "Passkey not found";
|
|
16
|
+
const PROVIDER_NOT_LINKED_TITLE = "Provider not linked";
|
|
17
|
+
const LAST_METHOD_TITLE = "Cannot remove the last sign-in method";
|
|
18
|
+
const RESET_NOT_CONFIGURED_TITLE = "Password reset email is not configured";
|
|
19
|
+
const PASSWORD_NOT_UNLINKABLE_TITLE = "The password cannot be unlinked";
|
|
20
|
+
const routeParam = (req, name) => {
|
|
21
|
+
const value = req.params[name];
|
|
22
|
+
return typeof value === "string" ? value : "";
|
|
23
|
+
};
|
|
24
|
+
/** Every sign-in method the user still has: accounts (including the password) and passkeys. */
|
|
25
|
+
const signInMethodCount = (credentials) => credentials.accounts.length + credentials.passkeys.length;
|
|
26
|
+
/**
|
|
27
|
+
* Before removing a sign-in method: refuses (409) to remove the user's last one unless their
|
|
28
|
+
* email is verified, and then mails a password reset first, so a delivery failure removes nothing.
|
|
29
|
+
* Returns whether a reset was sent.
|
|
30
|
+
*/
|
|
31
|
+
const guardLastSignInMethod = async ({ remaining, credentials, service, target, }) => {
|
|
32
|
+
if (remaining > 0) {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if (!credentials.emailVerified) {
|
|
36
|
+
throw new errors_1.ConflictError({
|
|
37
|
+
detail: "The user's email is not verified, so a password reset cannot replace this method",
|
|
38
|
+
title: LAST_METHOD_TITLE,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const reset = await service.sendPasswordReset(target);
|
|
42
|
+
if (!reset.sent) {
|
|
43
|
+
throw new errors_1.ConflictError({
|
|
44
|
+
detail: "Configure sendMail and publicAppUrl in BetterAuthConfig so the user can set a password",
|
|
45
|
+
title: RESET_NOT_CONFIGURED_TITLE,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* After removing a sign-in method: a concurrent removal may have taken the user's last other
|
|
52
|
+
* method after the guard counted it. When nothing is left and no reset went out yet, mail one now
|
|
53
|
+
* if the email is verified. The removal already happened, so a failed send is logged, not thrown.
|
|
54
|
+
* Returns whether a reset has been sent for this action.
|
|
55
|
+
*/
|
|
56
|
+
const ensureRecoverable = async ({ features, resetSent, service, target, }) => {
|
|
57
|
+
if (resetSent) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
const after = await service.readCredentials(target, features);
|
|
61
|
+
if (!after || signInMethodCount(after) > 0) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (!after.emailVerified) {
|
|
65
|
+
logger_1.logger.error(`User ${(0, accountSecurityService_1.userIdOf)(target)} has no sign-in method left after concurrent recovery actions, and an unverified email`);
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
const reset = await service.sendPasswordReset(target);
|
|
70
|
+
return reset.sent;
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
logger_1.logger.error(`Could not mail a password reset to user ${(0, accountSecurityService_1.userIdOf)(target)}`, error);
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Records the reset mail of an action that then found nothing to remove (another request removed
|
|
79
|
+
* it first), so a reset link never goes out unaudited.
|
|
80
|
+
*/
|
|
81
|
+
const recordOrphanedReset = ({ actor, details, org, target, }) => {
|
|
82
|
+
void (0, securityEvents_1.recordSecurityAction)({
|
|
83
|
+
action: "send-password-reset",
|
|
84
|
+
actor: { id: (0, accountSecurityService_1.userIdOf)(actor) },
|
|
85
|
+
details: { ...details, reason: "last-sign-in-method" },
|
|
86
|
+
org,
|
|
87
|
+
target: { id: (0, accountSecurityService_1.userIdOf)(target) },
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
const runRemovePasskey = async ({ actor, features, org, req, service, target, }) => {
|
|
91
|
+
const passkeyId = routeParam(req, "passkeyId");
|
|
92
|
+
const credentials = await service.readCredentials(target, features);
|
|
93
|
+
const passkey = credentials?.passkeys.find((item) => item.id === passkeyId);
|
|
94
|
+
if (!credentials || !passkey) {
|
|
95
|
+
throw new errors_1.NotFoundError(PASSKEY_NOT_FOUND_TITLE);
|
|
96
|
+
}
|
|
97
|
+
const sentBefore = await guardLastSignInMethod({
|
|
98
|
+
credentials,
|
|
99
|
+
remaining: signInMethodCount(credentials) - 1,
|
|
100
|
+
service,
|
|
101
|
+
target,
|
|
102
|
+
});
|
|
103
|
+
const removed = await service.deletePasskey({
|
|
104
|
+
betterAuthId: credentials.betterAuthId,
|
|
105
|
+
passkeyId: passkey.id,
|
|
106
|
+
});
|
|
107
|
+
if (!removed) {
|
|
108
|
+
// Removed by someone else between the read and the delete.
|
|
109
|
+
if (sentBefore) {
|
|
110
|
+
recordOrphanedReset({ actor, details: { passkeyId: passkey.id }, org, target });
|
|
111
|
+
}
|
|
112
|
+
throw new errors_1.NotFoundError(PASSKEY_NOT_FOUND_TITLE);
|
|
113
|
+
}
|
|
114
|
+
const passwordResetSent = await ensureRecoverable({
|
|
115
|
+
features,
|
|
116
|
+
resetSent: sentBefore,
|
|
117
|
+
service,
|
|
118
|
+
target,
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
audit: { passkeyId: passkey.id, passkeyName: passkey.name, passwordResetSent },
|
|
122
|
+
changed: true,
|
|
123
|
+
data: { passkeyId: passkey.id, passwordResetSent },
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
const runUnlinkProvider = async ({ actor, features, org, req, service, target, }) => {
|
|
127
|
+
const providerId = routeParam(req, "providerId");
|
|
128
|
+
if (providerId === accountSecurityService_1.PASSWORD_PROVIDER_ID) {
|
|
129
|
+
throw new errors_1.BadRequestError({
|
|
130
|
+
detail: "Send a password reset instead; this route only unlinks sign-in providers",
|
|
131
|
+
title: PASSWORD_NOT_UNLINKABLE_TITLE,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const credentials = await service.readCredentials(target, features);
|
|
135
|
+
const accountCount = credentials?.accounts.filter((account) => account.providerId === providerId).length ?? 0;
|
|
136
|
+
if (!credentials || accountCount === 0) {
|
|
137
|
+
throw new errors_1.NotFoundError(PROVIDER_NOT_LINKED_TITLE);
|
|
138
|
+
}
|
|
139
|
+
const sentBefore = await guardLastSignInMethod({
|
|
140
|
+
credentials,
|
|
141
|
+
remaining: signInMethodCount(credentials) - accountCount,
|
|
142
|
+
service,
|
|
143
|
+
target,
|
|
144
|
+
});
|
|
145
|
+
const removed = await service.deleteAccounts({
|
|
146
|
+
betterAuthId: credentials.betterAuthId,
|
|
147
|
+
providerId,
|
|
148
|
+
});
|
|
149
|
+
if (removed === 0) {
|
|
150
|
+
// Unlinked by someone else between the read and the delete.
|
|
151
|
+
if (sentBefore) {
|
|
152
|
+
recordOrphanedReset({ actor, details: { providerId }, org, target });
|
|
153
|
+
}
|
|
154
|
+
throw new errors_1.NotFoundError(PROVIDER_NOT_LINKED_TITLE);
|
|
155
|
+
}
|
|
156
|
+
const passwordResetSent = await ensureRecoverable({
|
|
157
|
+
features,
|
|
158
|
+
resetSent: sentBefore,
|
|
159
|
+
service,
|
|
160
|
+
target,
|
|
161
|
+
});
|
|
162
|
+
return {
|
|
163
|
+
audit: { accountCount: removed, passwordResetSent, providerId },
|
|
164
|
+
changed: true,
|
|
165
|
+
data: { accountCount: removed, passwordResetSent, providerId },
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
/** `DELETE /:userId/security/passkeys/:passkeyId`: remove one of the user's passkeys. */
|
|
169
|
+
exports.removePasskeyAction = {
|
|
170
|
+
id: "remove-passkey",
|
|
171
|
+
isApplicable: ({ state }) => state.passkeys.count > 0,
|
|
172
|
+
isSupported: (features) => features.passkey,
|
|
173
|
+
method: "delete",
|
|
174
|
+
path: "/passkeys/:passkeyId",
|
|
175
|
+
run: runRemovePasskey,
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* `DELETE /:userId/security/accounts/:providerId`: unlink every account the user has with that
|
|
179
|
+
* provider. Provider account ids are never exposed, so a user who linked two accounts of one
|
|
180
|
+
* provider loses both.
|
|
181
|
+
*/
|
|
182
|
+
exports.unlinkProviderAction = {
|
|
183
|
+
id: "unlink-provider",
|
|
184
|
+
isApplicable: ({ state }) => state.providers.length > 0,
|
|
185
|
+
isSupported: (features) => features.betterAuth,
|
|
186
|
+
method: "delete",
|
|
187
|
+
path: "/accounts/:providerId",
|
|
188
|
+
run: runUnlinkProvider,
|
|
189
|
+
};
|