@terreno/api 57.18.0 → 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.
Files changed (169) hide show
  1. package/CHANGELOG.md +2071 -2
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -0,0 +1,867 @@
1
+ import {afterEach, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import type express from "express";
3
+ import {DateTime} from "luxon";
4
+ import mongoose from "mongoose";
5
+ import supertest from "supertest";
6
+
7
+ import {resetAuditRecorderForTests} from "../audit/record";
8
+ import type {BetterAuthApp} from "../betterAuthApp";
9
+ import {logger} from "../logger";
10
+ import {
11
+ access,
12
+ betterAuthCollection,
13
+ betterAuthIdFor,
14
+ buildApp,
15
+ getSummary,
16
+ resetAccountSecurityState,
17
+ resetTokenFrom,
18
+ SecurityUser,
19
+ type SentMail,
20
+ securityEventsFor,
21
+ signInWithPassword,
22
+ signUp,
23
+ } from "../tests/accountSecurityTestApp";
24
+ import {clearSecurityActionListenersForTests} from "./securityEvents";
25
+
26
+ const NEW_PASSWORD = "new-password-654321";
27
+
28
+ const removePasskey = (
29
+ app: express.Application,
30
+ token: string,
31
+ userId: string,
32
+ passkeyId: string
33
+ ): supertest.Test =>
34
+ supertest(app)
35
+ .delete(`/users/${userId}/security/passkeys/${passkeyId}`)
36
+ .set("authorization", `Bearer ${token}`);
37
+
38
+ const unlinkProvider = (
39
+ app: express.Application,
40
+ token: string,
41
+ userId: string,
42
+ providerId: string
43
+ ): supertest.Test =>
44
+ supertest(app)
45
+ .delete(`/users/${userId}/security/accounts/${providerId}`)
46
+ .set("authorization", `Bearer ${token}`);
47
+
48
+ const betterAuthContext = async (
49
+ betterAuthApp: BetterAuthApp
50
+ ): Promise<Awaited<ReturnType<BetterAuthApp["ensureAuth"]>["$context"]>> =>
51
+ betterAuthApp.ensureAuth().$context;
52
+
53
+ /** Adds a passkey row for the app User and returns its Better Auth id. */
54
+ const addPasskey = async (
55
+ betterAuthApp: BetterAuthApp,
56
+ userId: string,
57
+ name: string
58
+ ): Promise<string> => {
59
+ const context = await betterAuthContext(betterAuthApp);
60
+ const row = await context.adapter.create<Record<string, unknown>, {id: string}>({
61
+ data: {
62
+ backedUp: false,
63
+ counter: 0,
64
+ credentialID: `credential-${name}`,
65
+ deviceType: "singleDevice",
66
+ name,
67
+ publicKey: `public-key-${name}`,
68
+ userId: await betterAuthIdFor(userId),
69
+ },
70
+ model: "passkey",
71
+ });
72
+ return String(row.id);
73
+ };
74
+
75
+ const linkProvider = async (
76
+ betterAuthApp: BetterAuthApp,
77
+ userId: string,
78
+ providerId: string,
79
+ accountId = `${providerId}-account`
80
+ ): Promise<void> => {
81
+ const context = await betterAuthContext(betterAuthApp);
82
+ await context.internalAdapter.createAccount({
83
+ accessToken: `${providerId}-access-token`,
84
+ accountId,
85
+ providerId,
86
+ userId: await betterAuthIdFor(userId),
87
+ });
88
+ };
89
+
90
+ /** Removes the user's password, so their only sign-in methods are the ones the test adds. */
91
+ const removePassword = async (betterAuthApp: BetterAuthApp, userId: string): Promise<void> => {
92
+ const context = await betterAuthContext(betterAuthApp);
93
+ await context.adapter.deleteMany({
94
+ model: "account",
95
+ where: [
96
+ {field: "userId", value: await betterAuthIdFor(userId)},
97
+ {field: "providerId", value: "credential"},
98
+ ],
99
+ });
100
+ };
101
+
102
+ const markEmailVerified = async (email: string): Promise<void> => {
103
+ await betterAuthCollection("user").updateOne({email}, {$set: {emailVerified: true}});
104
+ };
105
+
106
+ const providerIdsOf = async (betterAuthApp: BetterAuthApp, userId: string): Promise<string[]> => {
107
+ const context = await betterAuthContext(betterAuthApp);
108
+ const accounts = await context.internalAdapter.findAccounts(await betterAuthIdFor(userId));
109
+ return accounts.map((account) => account.providerId).sort();
110
+ };
111
+
112
+ const passkeyCount = async (betterAuthApp: BetterAuthApp, userId: string): Promise<number> => {
113
+ const context = await betterAuthContext(betterAuthApp);
114
+ const rows = await context.adapter.findMany({
115
+ model: "passkey",
116
+ where: [{field: "userId", value: await betterAuthIdFor(userId)}],
117
+ });
118
+ return rows.length;
119
+ };
120
+
121
+ const CREDENTIAL_ACTION_IDS = new Set(["remove-passkey", "unlink-provider"]);
122
+
123
+ /** The summary's credential actions (the access actions are covered in accessActions.test.ts). */
124
+ const credentialActionsOf = (
125
+ res: supertest.Response
126
+ ): {destructive: boolean; id: string; label: string; method: string; path: string}[] =>
127
+ (
128
+ res.body.data.actions as {
129
+ destructive: boolean;
130
+ id: string;
131
+ label: string;
132
+ method: string;
133
+ path: string;
134
+ }[]
135
+ ).filter((action) => CREDENTIAL_ACTION_IDS.has(action.id));
136
+
137
+ const actionIdsOf = (res: supertest.Response): string[] =>
138
+ credentialActionsOf(res).map((action) => action.id);
139
+
140
+ /** A build with a capturing mailer and `publicAppUrl`, so reset mail can be sent. */
141
+ const buildMailingApp = (
142
+ sendMail?: (message: SentMail) => Promise<void>
143
+ ): ReturnType<typeof buildApp> & {sent: SentMail[]} => {
144
+ const sent: SentMail[] = [];
145
+ const built = buildApp({
146
+ config: {
147
+ publicAppUrl: "https://app.example.com",
148
+ sendMail:
149
+ sendMail ??
150
+ (async (message): Promise<void> => {
151
+ sent.push(message);
152
+ }),
153
+ },
154
+ });
155
+ return {...built, sent};
156
+ };
157
+
158
+ const resetMailsIn = (sent: SentMail[]): SentMail[] =>
159
+ sent.filter((mail) => mail.subject === "Reset your password");
160
+
161
+ type DeleteMany = (args: {
162
+ model: string;
163
+ where: {field: string; value: unknown}[];
164
+ }) => Promise<number>;
165
+
166
+ /**
167
+ * Makes the next Better Auth `deleteMany` on `model` run `concurrently` first, as if another
168
+ * recovery request removed something between this request's count and its delete.
169
+ */
170
+ const interleaveNextDelete = async (
171
+ betterAuthApp: BetterAuthApp,
172
+ model: string,
173
+ concurrently: (deleteMany: DeleteMany) => Promise<unknown>
174
+ ): Promise<void> => {
175
+ const context = await betterAuthContext(betterAuthApp);
176
+ const adapter = context.adapter as unknown as {deleteMany: DeleteMany};
177
+ const original = adapter.deleteMany.bind(adapter);
178
+ const spy = spyOn(adapter, "deleteMany");
179
+ spy.mockImplementation(async (args) => {
180
+ if (args.model !== model) {
181
+ return original(args);
182
+ }
183
+ spy.mockRestore();
184
+ await concurrently(original);
185
+ return original(args);
186
+ });
187
+ };
188
+
189
+ describe("credential recovery actions", () => {
190
+ beforeAll(async () => {
191
+ await access.roles.seedDefaults();
192
+ });
193
+
194
+ beforeEach(async () => {
195
+ await resetAccountSecurityState();
196
+ });
197
+
198
+ afterEach(() => {
199
+ resetAuditRecorderForTests();
200
+ clearSecurityActionListenersForTests();
201
+ });
202
+
203
+ describe("remove passkey", () => {
204
+ it("removes the passkey, so it is no longer listed, and audits which one", async () => {
205
+ const {app, betterAuthApp} = buildApp();
206
+ const operator = await signUp(app, "operator", ["operator"]);
207
+ const target = await signUp(app, "passkey-target");
208
+ const laptop = await addPasskey(betterAuthApp, target.id, "Work laptop");
209
+ await addPasskey(betterAuthApp, target.id, "Phone");
210
+
211
+ const res = await removePasskey(app, operator.token, target.id, laptop);
212
+
213
+ expect(res.status).toBe(200);
214
+ expect(res.body.data).toEqual({
215
+ action: "remove-passkey",
216
+ changed: true,
217
+ passkeyId: laptop,
218
+ passwordResetSent: false,
219
+ });
220
+ const summary = await getSummary(app, operator.token, target.id);
221
+ expect(summary.body.data.passkeys.count).toBe(1);
222
+ expect(summary.body.data.passkeys.items.map((item: {name: string}) => item.name)).toEqual([
223
+ "Phone",
224
+ ]);
225
+ const events = await securityEventsFor(target.id);
226
+ expect(events).toHaveLength(1);
227
+ expect(String(events[0].actorId)).toBe(operator.id);
228
+ expect(events[0].after).toEqual({
229
+ passkeyId: laptop,
230
+ passkeyName: "Work laptop",
231
+ passwordResetSent: false,
232
+ securityAction: "remove-passkey",
233
+ });
234
+ });
235
+
236
+ it("answers 404 for another user's passkey and leaves it in place", async () => {
237
+ const {app, betterAuthApp} = buildApp();
238
+ const operator = await signUp(app, "operator-other", ["operator"]);
239
+ const target = await signUp(app, "passkey-target-other");
240
+ const bystander = await signUp(app, "passkey-bystander");
241
+ await addPasskey(betterAuthApp, target.id, "Target key");
242
+ const bystanderKey = await addPasskey(betterAuthApp, bystander.id, "Bystander key");
243
+
244
+ const res = await removePasskey(app, operator.token, target.id, bystanderKey);
245
+
246
+ expect(res.status).toBe(404);
247
+ expect(res.body.title).toBe("Passkey not found");
248
+ expect(await passkeyCount(betterAuthApp, bystander.id)).toBe(1);
249
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(1);
250
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
251
+ expect(await securityEventsFor(bystander.id)).toHaveLength(0);
252
+ });
253
+
254
+ it("answers 404 for an unknown or malformed passkey id", async () => {
255
+ const {app, betterAuthApp} = buildApp();
256
+ const operator = await signUp(app, "operator-unknown", ["operator"]);
257
+ const target = await signUp(app, "passkey-target-unknown");
258
+ await addPasskey(betterAuthApp, target.id, "Only key");
259
+
260
+ const unknown = await removePasskey(
261
+ app,
262
+ operator.token,
263
+ target.id,
264
+ new mongoose.Types.ObjectId().toString()
265
+ );
266
+ const malformed = await removePasskey(app, operator.token, target.id, "not-a-passkey-id");
267
+
268
+ expect(unknown.status).toBe(404);
269
+ expect(malformed.status).toBe(404);
270
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(1);
271
+ });
272
+
273
+ it("answers 404 for a user with no Better Auth link", async () => {
274
+ const {app} = buildApp();
275
+ const operator = await signUp(app, "operator-legacy", ["operator"]);
276
+ const legacy = await SecurityUser.create({email: "legacy-passkey@example.com"});
277
+
278
+ const res = await removePasskey(app, operator.token, String(legacy._id), "pk-1");
279
+
280
+ expect(res.status).toBe(404);
281
+ expect(res.body.title).toBe("Passkey not found");
282
+ });
283
+
284
+ it("answers 404 when passkeys are not enabled on the server", async () => {
285
+ const {app} = buildApp({config: {passkey: undefined}});
286
+ const operator = await signUp(app, "operator-no-passkeys", ["operator"]);
287
+ const target = await signUp(app, "passkey-target-off");
288
+
289
+ const res = await removePasskey(app, operator.token, target.id, "pk-1");
290
+
291
+ expect(res.status).toBe(404);
292
+ expect(res.body.title).toBe("Security action not available");
293
+ });
294
+ });
295
+
296
+ describe("remove passkey: last sign-in method", () => {
297
+ it("refuses with 409 to remove the only passkey of a user whose email is unverified", async () => {
298
+ const {app, betterAuthApp} = buildApp();
299
+ const operator = await signUp(app, "operator-last-key", ["operator"]);
300
+ const target = await signUp(app, "last-key");
301
+ await removePassword(betterAuthApp, target.id);
302
+ const key = await addPasskey(betterAuthApp, target.id, "Only key");
303
+
304
+ const res = await removePasskey(app, operator.token, target.id, key);
305
+
306
+ expect(res.status).toBe(409);
307
+ expect(res.body.title).toBe("Cannot remove the last sign-in method");
308
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(1);
309
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
310
+ });
311
+
312
+ it("removes the only passkey of a verified user after mailing a password reset", async () => {
313
+ const {app, betterAuthApp, sent} = buildMailingApp();
314
+ const operator = await signUp(app, "operator-key-reset", ["operator"]);
315
+ const target = await signUp(app, "key-reset");
316
+ await removePassword(betterAuthApp, target.id);
317
+ await markEmailVerified(target.email);
318
+ const key = await addPasskey(betterAuthApp, target.id, "Only key");
319
+
320
+ const res = await removePasskey(app, operator.token, target.id, key);
321
+
322
+ expect(res.status).toBe(200);
323
+ expect(res.body.data.passwordResetSent).toBe(true);
324
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(0);
325
+ expect(resetMailsIn(sent).map((mail) => mail.to)).toEqual([target.email]);
326
+ const events = await securityEventsFor(target.id);
327
+ expect(events).toHaveLength(1);
328
+ expect(events[0].after).toEqual({
329
+ passkeyId: key,
330
+ passkeyName: "Only key",
331
+ passwordResetSent: true,
332
+ securityAction: "remove-passkey",
333
+ });
334
+ });
335
+
336
+ it("refuses with 409 when the only passkey would go but reset mail is not configured", async () => {
337
+ const {app, betterAuthApp} = buildApp();
338
+ const operator = await signUp(app, "operator-key-no-mail", ["operator"]);
339
+ const target = await signUp(app, "key-no-mail");
340
+ await removePassword(betterAuthApp, target.id);
341
+ await markEmailVerified(target.email);
342
+ const key = await addPasskey(betterAuthApp, target.id, "Only key");
343
+
344
+ const res = await removePasskey(app, operator.token, target.id, key);
345
+
346
+ expect(res.status).toBe(409);
347
+ expect(res.body.title).toBe("Password reset email is not configured");
348
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(1);
349
+ });
350
+
351
+ it("removes one of two passkeys without a reset, even with no password", async () => {
352
+ const {app, betterAuthApp, sent} = buildMailingApp();
353
+ const operator = await signUp(app, "operator-two-keys", ["operator"]);
354
+ const target = await signUp(app, "two-keys");
355
+ await removePassword(betterAuthApp, target.id);
356
+ const key = await addPasskey(betterAuthApp, target.id, "First key");
357
+ await addPasskey(betterAuthApp, target.id, "Second key");
358
+ sent.length = 0;
359
+
360
+ const res = await removePasskey(app, operator.token, target.id, key);
361
+
362
+ expect(res.status).toBe(200);
363
+ expect(res.body.data.passwordResetSent).toBe(false);
364
+ expect(resetMailsIn(sent)).toHaveLength(0);
365
+ });
366
+ });
367
+
368
+ describe("concurrent removals", () => {
369
+ it("mails a reset when a concurrent removal took the user's other method", async () => {
370
+ const {app, betterAuthApp, sent} = buildMailingApp();
371
+ const operator = await signUp(app, "operator-race", ["operator"]);
372
+ const target = await signUp(app, "race");
373
+ await removePassword(betterAuthApp, target.id);
374
+ await markEmailVerified(target.email);
375
+ await linkProvider(betterAuthApp, target.id, "github");
376
+ await linkProvider(betterAuthApp, target.id, "google");
377
+ const betterAuthId = await betterAuthIdFor(target.id);
378
+ sent.length = 0;
379
+ await interleaveNextDelete(betterAuthApp, "account", (deleteMany) =>
380
+ deleteMany({
381
+ model: "account",
382
+ where: [
383
+ {field: "userId", value: betterAuthId},
384
+ {field: "providerId", value: "google"},
385
+ ],
386
+ })
387
+ );
388
+
389
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
390
+
391
+ expect(res.status).toBe(200);
392
+ expect(res.body.data.passwordResetSent).toBe(true);
393
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual([]);
394
+ expect(resetMailsIn(sent).map((mail) => mail.to)).toEqual([target.email]);
395
+ const events = await securityEventsFor(target.id);
396
+ expect(events).toHaveLength(1);
397
+ expect(events[0].after).toEqual({
398
+ accountCount: 1,
399
+ passwordResetSent: true,
400
+ providerId: "github",
401
+ securityAction: "unlink-provider",
402
+ });
403
+ });
404
+
405
+ it("logs, and sends nothing, when the race leaves an unverified user with no method", async () => {
406
+ const {app, betterAuthApp, sent} = buildMailingApp();
407
+ const operator = await signUp(app, "operator-race-unverified", ["operator"]);
408
+ const target = await signUp(app, "race-unverified");
409
+ await removePassword(betterAuthApp, target.id);
410
+ await linkProvider(betterAuthApp, target.id, "github");
411
+ const key = await addPasskey(betterAuthApp, target.id, "Racing key");
412
+ sent.length = 0;
413
+ const errorSpy = spyOn(logger, "error");
414
+ await interleaveNextDelete(betterAuthApp, "account", (deleteMany) =>
415
+ deleteMany({model: "passkey", where: [{field: "id", value: key}]})
416
+ );
417
+
418
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
419
+
420
+ expect(res.status).toBe(200);
421
+ expect(res.body.data.passwordResetSent).toBe(false);
422
+ expect(resetMailsIn(sent)).toHaveLength(0);
423
+ expect(
424
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("no sign-in method left"))
425
+ ).toBe(true);
426
+ errorSpy.mockRestore();
427
+ });
428
+
429
+ it("still answers 200 when the late reset mail fails, and reports it was not sent", async () => {
430
+ const {app, betterAuthApp} = buildMailingApp(async (message): Promise<void> => {
431
+ if (message.subject === "Reset your password") {
432
+ throw new Error("SMTP is down");
433
+ }
434
+ });
435
+ const operator = await signUp(app, "operator-race-smtp", ["operator"]);
436
+ const target = await signUp(app, "race-smtp");
437
+ await removePassword(betterAuthApp, target.id);
438
+ await markEmailVerified(target.email);
439
+ await linkProvider(betterAuthApp, target.id, "github");
440
+ const key = await addPasskey(betterAuthApp, target.id, "Racing key");
441
+ const betterAuthId = await betterAuthIdFor(target.id);
442
+ const errorSpy = spyOn(logger, "error");
443
+ await interleaveNextDelete(betterAuthApp, "passkey", (deleteMany) =>
444
+ deleteMany({
445
+ model: "account",
446
+ where: [
447
+ {field: "userId", value: betterAuthId},
448
+ {field: "providerId", value: "github"},
449
+ ],
450
+ })
451
+ );
452
+
453
+ const res = await removePasskey(app, operator.token, target.id, key);
454
+
455
+ expect(res.status).toBe(200);
456
+ expect(res.body.data.passwordResetSent).toBe(false);
457
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(0);
458
+ expect(
459
+ errorSpy.mock.calls.some((call) => String(call[0]).includes("Could not mail a password"))
460
+ ).toBe(true);
461
+ errorSpy.mockRestore();
462
+ });
463
+
464
+ it("audits the reset it mailed when a concurrent request unlinked the provider first", async () => {
465
+ const {app, betterAuthApp, sent} = buildMailingApp();
466
+ const operator = await signUp(app, "operator-race-404", ["operator"]);
467
+ const target = await signUp(app, "race-404");
468
+ await removePassword(betterAuthApp, target.id);
469
+ await markEmailVerified(target.email);
470
+ await linkProvider(betterAuthApp, target.id, "github");
471
+ const betterAuthId = await betterAuthIdFor(target.id);
472
+ sent.length = 0;
473
+ await interleaveNextDelete(betterAuthApp, "account", (deleteMany) =>
474
+ deleteMany({
475
+ model: "account",
476
+ where: [
477
+ {field: "userId", value: betterAuthId},
478
+ {field: "providerId", value: "github"},
479
+ ],
480
+ })
481
+ );
482
+
483
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
484
+
485
+ expect(res.status).toBe(404);
486
+ expect(res.body.title).toBe("Provider not linked");
487
+ expect(resetMailsIn(sent)).toHaveLength(1);
488
+ const events = await securityEventsFor(target.id);
489
+ expect(events).toHaveLength(1);
490
+ expect(String(events[0].actorId)).toBe(operator.id);
491
+ expect(events[0].after).toEqual({
492
+ providerId: "github",
493
+ reason: "last-sign-in-method",
494
+ securityAction: "send-password-reset",
495
+ });
496
+ });
497
+
498
+ it("audits the reset it mailed when a concurrent request removed the passkey first", async () => {
499
+ const {app, betterAuthApp, sent} = buildMailingApp();
500
+ const operator = await signUp(app, "operator-race-key-404", ["operator"]);
501
+ const target = await signUp(app, "race-key-404");
502
+ await removePassword(betterAuthApp, target.id);
503
+ await markEmailVerified(target.email);
504
+ const key = await addPasskey(betterAuthApp, target.id, "Only key");
505
+ sent.length = 0;
506
+ await interleaveNextDelete(betterAuthApp, "passkey", (deleteMany) =>
507
+ deleteMany({model: "passkey", where: [{field: "id", value: key}]})
508
+ );
509
+
510
+ const res = await removePasskey(app, operator.token, target.id, key);
511
+
512
+ expect(res.status).toBe(404);
513
+ expect(resetMailsIn(sent)).toHaveLength(1);
514
+ const events = await securityEventsFor(target.id);
515
+ expect(events.map((event) => event.after)).toEqual([
516
+ {passkeyId: key, reason: "last-sign-in-method", securityAction: "send-password-reset"},
517
+ ]);
518
+ });
519
+ });
520
+
521
+ describe("unlink provider", () => {
522
+ it("removes the provider's account row, keeps the password, and audits the unlink", async () => {
523
+ const {app, betterAuthApp} = buildApp();
524
+ const operator = await signUp(app, "operator-unlink", ["operator"]);
525
+ const target = await signUp(app, "unlink-target");
526
+ await linkProvider(betterAuthApp, target.id, "github");
527
+
528
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
529
+
530
+ expect(res.status).toBe(200);
531
+ expect(res.body.data).toEqual({
532
+ accountCount: 1,
533
+ action: "unlink-provider",
534
+ changed: true,
535
+ passwordResetSent: false,
536
+ providerId: "github",
537
+ });
538
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["credential"]);
539
+ const summary = await getSummary(app, operator.token, target.id);
540
+ expect(summary.body.data.providers).toEqual([]);
541
+ expect(summary.body.data.password).toBe(true);
542
+ const events = await securityEventsFor(target.id);
543
+ expect(events).toHaveLength(1);
544
+ expect(String(events[0].actorId)).toBe(operator.id);
545
+ expect(events[0].after).toEqual({
546
+ accountCount: 1,
547
+ passwordResetSent: false,
548
+ providerId: "github",
549
+ securityAction: "unlink-provider",
550
+ });
551
+ });
552
+
553
+ it("removes every account the user has with that provider, and only that provider", async () => {
554
+ const {app, betterAuthApp} = buildApp();
555
+ const operator = await signUp(app, "operator-multi", ["operator"]);
556
+ const target = await signUp(app, "unlink-multi");
557
+ await linkProvider(betterAuthApp, target.id, "github", "github-one");
558
+ await linkProvider(betterAuthApp, target.id, "github", "github-two");
559
+ await linkProvider(betterAuthApp, target.id, "google");
560
+
561
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
562
+
563
+ expect(res.status).toBe(200);
564
+ expect(res.body.data.accountCount).toBe(2);
565
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["credential", "google"]);
566
+ });
567
+
568
+ it("never unlinks the password credential", async () => {
569
+ const {app, betterAuthApp} = buildApp();
570
+ const operator = await signUp(app, "operator-credential", ["operator"]);
571
+ const target = await signUp(app, "unlink-credential");
572
+ await linkProvider(betterAuthApp, target.id, "github");
573
+
574
+ const res = await unlinkProvider(app, operator.token, target.id, "credential");
575
+
576
+ expect(res.status).toBe(400);
577
+ expect(res.body.title).toBe("The password cannot be unlinked");
578
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["credential", "github"]);
579
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
580
+ });
581
+
582
+ it("answers 404 for a provider the user has not linked, and for a legacy user", async () => {
583
+ const {app} = buildApp();
584
+ const operator = await signUp(app, "operator-not-linked", ["operator"]);
585
+ const target = await signUp(app, "unlink-not-linked");
586
+ const legacy = await SecurityUser.create({email: "legacy-unlink@example.com"});
587
+
588
+ const notLinked = await unlinkProvider(app, operator.token, target.id, "github");
589
+ const unlinkedLegacy = await unlinkProvider(
590
+ app,
591
+ operator.token,
592
+ String(legacy._id),
593
+ "github"
594
+ );
595
+
596
+ expect(notLinked.status).toBe(404);
597
+ expect(notLinked.body.title).toBe("Provider not linked");
598
+ expect(unlinkedLegacy.status).toBe(404);
599
+ });
600
+
601
+ it("refuses with 409 to remove the last sign-in method of a user whose email is unverified", async () => {
602
+ const {app, betterAuthApp} = buildApp();
603
+ const operator = await signUp(app, "operator-last", ["operator"]);
604
+ const target = await signUp(app, "unlink-last");
605
+ await linkProvider(betterAuthApp, target.id, "github");
606
+ await removePassword(betterAuthApp, target.id);
607
+
608
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
609
+
610
+ expect(res.status).toBe(409);
611
+ expect(res.body.title).toBe("Cannot remove the last sign-in method");
612
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["github"]);
613
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
614
+ });
615
+
616
+ it("counts passkeys as a remaining sign-in method", async () => {
617
+ const {app, betterAuthApp} = buildApp();
618
+ const operator = await signUp(app, "operator-passkey-left", ["operator"]);
619
+ const target = await signUp(app, "unlink-passkey-left");
620
+ await linkProvider(betterAuthApp, target.id, "github");
621
+ await removePassword(betterAuthApp, target.id);
622
+ await addPasskey(betterAuthApp, target.id, "Security key");
623
+
624
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
625
+
626
+ expect(res.status).toBe(200);
627
+ expect(res.body.data.passwordResetSent).toBe(false);
628
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual([]);
629
+ });
630
+
631
+ it("does not count passkeys when the server no longer accepts them", async () => {
632
+ const {app, betterAuthApp} = buildApp();
633
+ const operator = await signUp(app, "operator-passkey-off", ["operator"]);
634
+ const target = await signUp(app, "unlink-passkey-off");
635
+ await linkProvider(betterAuthApp, target.id, "github");
636
+ await removePassword(betterAuthApp, target.id);
637
+ await addPasskey(betterAuthApp, target.id, "Orphaned key");
638
+ const {app: passkeylessApp} = buildApp({config: {passkey: undefined}});
639
+
640
+ const res = await unlinkProvider(passkeylessApp, operator.token, target.id, "github");
641
+
642
+ expect(res.status).toBe(409);
643
+ expect(res.body.title).toBe("Cannot remove the last sign-in method");
644
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["github"]);
645
+ });
646
+
647
+ it("unlinks the last method of a verified user and mails a password-reset link", async () => {
648
+ const sent: SentMail[] = [];
649
+ const {app, betterAuthApp} = buildApp({
650
+ config: {
651
+ publicAppUrl: "https://app.example.com",
652
+ sendMail: async (message): Promise<void> => {
653
+ sent.push(message);
654
+ },
655
+ },
656
+ });
657
+ const operator = await signUp(app, "operator-reset", ["operator"]);
658
+ const target = await signUp(app, "unlink-reset");
659
+ await linkProvider(betterAuthApp, target.id, "github");
660
+ await removePassword(betterAuthApp, target.id);
661
+ await markEmailVerified(target.email);
662
+ sent.length = 0;
663
+
664
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
665
+
666
+ expect(res.status).toBe(200);
667
+ expect(res.body.data.passwordResetSent).toBe(true);
668
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual([]);
669
+ const resetMails = sent.filter((mail) => mail.subject === "Reset your password");
670
+ expect(resetMails).toHaveLength(1);
671
+ expect(resetMails[0].to).toBe(target.email);
672
+ expect(resetMails[0].text).toContain("https://app.example.com/resetPassword?token=");
673
+ const events = await securityEventsFor(target.id);
674
+ expect(events).toHaveLength(1);
675
+ expect(events[0].after).toEqual({
676
+ accountCount: 1,
677
+ passwordResetSent: true,
678
+ providerId: "github",
679
+ securityAction: "unlink-provider",
680
+ });
681
+
682
+ // The link carries a token Better Auth's own /reset-password endpoint accepts.
683
+ const context = await betterAuthContext(betterAuthApp);
684
+ const verification = await context.internalAdapter.findVerificationValue(
685
+ `reset-password:${resetTokenFrom(resetMails[0])}`
686
+ );
687
+ if (!verification) {
688
+ throw new Error("The reset link has no verification row");
689
+ }
690
+ expect(verification.value).toBe(await betterAuthIdFor(target.id));
691
+ expect(DateTime.fromJSDate(verification.expiresAt) > DateTime.now()).toBe(true);
692
+
693
+ // The user follows the link, sets a password, and signs in with it.
694
+ await supertest(app)
695
+ .post("/api/auth/reset-password")
696
+ .set("content-type", "application/json")
697
+ .send({newPassword: NEW_PASSWORD, token: resetTokenFrom(resetMails[0])})
698
+ .expect(200);
699
+ const signIn = await supertest(app)
700
+ .post("/api/auth/sign-in/email")
701
+ .set("content-type", "application/json")
702
+ .send({email: target.email, password: NEW_PASSWORD});
703
+ expect(signIn.status).toBe(200);
704
+ });
705
+
706
+ it("refuses with 409 when a verified user's last method would go but reset mail is not configured", async () => {
707
+ const {app, betterAuthApp} = buildApp();
708
+ const operator = await signUp(app, "operator-no-mail", ["operator"]);
709
+ const target = await signUp(app, "unlink-no-mail");
710
+ await linkProvider(betterAuthApp, target.id, "github");
711
+ await removePassword(betterAuthApp, target.id);
712
+ await markEmailVerified(target.email);
713
+
714
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
715
+
716
+ expect(res.status).toBe(409);
717
+ expect(res.body.title).toBe("Password reset email is not configured");
718
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["github"]);
719
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
720
+ });
721
+
722
+ it("keeps the provider when the reset mail cannot be built without publicAppUrl", async () => {
723
+ const sent: SentMail[] = [];
724
+ const {app, betterAuthApp} = buildApp({
725
+ config: {
726
+ sendMail: async (message): Promise<void> => {
727
+ sent.push(message);
728
+ },
729
+ },
730
+ });
731
+ const operator = await signUp(app, "operator-no-url", ["operator"]);
732
+ const target = await signUp(app, "unlink-no-url");
733
+ await linkProvider(betterAuthApp, target.id, "github");
734
+ await removePassword(betterAuthApp, target.id);
735
+ await markEmailVerified(target.email);
736
+
737
+ const res = await unlinkProvider(app, operator.token, target.id, "github");
738
+
739
+ expect(res.status).toBe(501);
740
+ expect(res.body.title).toBe("publicAppUrl is required to send recovery mail");
741
+ expect(sent.filter((mail) => mail.subject === "Reset your password")).toHaveLength(0);
742
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["github"]);
743
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
744
+ });
745
+ });
746
+
747
+ describe("summary actions", () => {
748
+ it("lists both actions only when the user has passkeys and linked providers", async () => {
749
+ const {app, betterAuthApp} = buildApp();
750
+ const operator = await signUp(app, "operator-actions", ["operator"]);
751
+ const target = await signUp(app, "actions-target");
752
+
753
+ const before = await getSummary(app, operator.token, target.id);
754
+ expect(actionIdsOf(before)).toEqual([]);
755
+
756
+ await addPasskey(betterAuthApp, target.id, "Laptop");
757
+ await linkProvider(betterAuthApp, target.id, "github");
758
+ const after = await getSummary(app, operator.token, target.id);
759
+
760
+ expect(actionIdsOf(after)).toEqual(["remove-passkey", "unlink-provider"]);
761
+ expect(credentialActionsOf(after)).toEqual([
762
+ {
763
+ destructive: true,
764
+ id: "remove-passkey",
765
+ label: "Remove passkey",
766
+ method: "DELETE",
767
+ path: "/passkeys/:passkeyId",
768
+ },
769
+ {
770
+ destructive: true,
771
+ id: "unlink-provider",
772
+ label: "Unlink provider",
773
+ method: "DELETE",
774
+ path: "/accounts/:providerId",
775
+ },
776
+ ]);
777
+ });
778
+ });
779
+
780
+ describe("summary actions by state", () => {
781
+ it("lists only remove-passkey for a user with a passkey and no provider", async () => {
782
+ const {app, betterAuthApp} = buildApp();
783
+ const operator = await signUp(app, "operator-only-key", ["operator"]);
784
+ const target = await signUp(app, "only-key");
785
+ await addPasskey(betterAuthApp, target.id, "Laptop");
786
+
787
+ expect(actionIdsOf(await getSummary(app, operator.token, target.id))).toEqual([
788
+ "remove-passkey",
789
+ ]);
790
+ });
791
+
792
+ it("lists only unlink-provider for a user with a provider and no passkey", async () => {
793
+ const {app, betterAuthApp} = buildApp();
794
+ const operator = await signUp(app, "operator-only-provider", ["operator"]);
795
+ const target = await signUp(app, "only-provider");
796
+ await linkProvider(betterAuthApp, target.id, "github");
797
+
798
+ expect(actionIdsOf(await getSummary(app, operator.token, target.id))).toEqual([
799
+ "unlink-provider",
800
+ ]);
801
+ });
802
+
803
+ it("leaves out remove-passkey when the server has passkeys off", async () => {
804
+ const {app, betterAuthApp} = buildApp({config: {passkey: undefined}});
805
+ const operator = await signUp(app, "operator-keys-off", ["operator"]);
806
+ const target = await signUp(app, "keys-off");
807
+ // A passkey stored while the feature was on; this server's adapter has no passkey model.
808
+ const {betterAuthApp: passkeyApp} = buildApp();
809
+ await addPasskey(passkeyApp, target.id, "Stored key");
810
+ await linkProvider(betterAuthApp, target.id, "github");
811
+
812
+ expect(actionIdsOf(await getSummary(app, operator.token, target.id))).toEqual([
813
+ "unlink-provider",
814
+ ]);
815
+ });
816
+ });
817
+
818
+ describe("authorization", () => {
819
+ it("refuses a member with 403 and changes nothing", async () => {
820
+ const {app, betterAuthApp} = buildApp();
821
+ const member = await signUp(app, "member");
822
+ const target = await signUp(app, "member-target");
823
+ const passkeyId = await addPasskey(betterAuthApp, target.id, "Laptop");
824
+ await linkProvider(betterAuthApp, target.id, "github");
825
+
826
+ expect((await removePasskey(app, member.token, target.id, passkeyId)).status).toBe(403);
827
+ expect((await unlinkProvider(app, member.token, target.id, "github")).status).toBe(403);
828
+ expect(await passkeyCount(betterAuthApp, target.id)).toBe(1);
829
+ expect(await providerIdsOf(betterAuthApp, target.id)).toEqual(["credential", "github"]);
830
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
831
+ });
832
+
833
+ it("refuses an operator acting on a superadmin or on themselves", async () => {
834
+ const {app, betterAuthApp} = buildApp();
835
+ const operator = await signUp(app, "operator-reach", ["operator"]);
836
+ const superadmin = await signUp(app, "superadmin-target", ["superadmin"]);
837
+ const superadminKey = await addPasskey(betterAuthApp, superadmin.id, "Admin key");
838
+ await linkProvider(betterAuthApp, superadmin.id, "github");
839
+ const ownKey = await addPasskey(betterAuthApp, operator.id, "Own key");
840
+ await linkProvider(betterAuthApp, operator.id, "github", "operator-github");
841
+
842
+ const refused = [
843
+ await removePasskey(app, operator.token, superadmin.id, superadminKey),
844
+ await unlinkProvider(app, operator.token, superadmin.id, "github"),
845
+ await removePasskey(app, operator.token, operator.id, ownKey),
846
+ await unlinkProvider(app, operator.token, operator.id, "github"),
847
+ ];
848
+
849
+ expect(refused.map((res) => res.status)).toEqual([403, 403, 403, 403]);
850
+ expect(await passkeyCount(betterAuthApp, superadmin.id)).toBe(1);
851
+ expect(await passkeyCount(betterAuthApp, operator.id)).toBe(1);
852
+ expect(await providerIdsOf(betterAuthApp, superadmin.id)).toEqual(["credential", "github"]);
853
+ expect(await providerIdsOf(betterAuthApp, operator.id)).toEqual(["credential", "github"]);
854
+ });
855
+
856
+ it("still lets the user sign in with their password after an operator unlinks a provider", async () => {
857
+ const {app, betterAuthApp} = buildApp();
858
+ const operator = await signUp(app, "operator-signin", ["operator"]);
859
+ const target = await signUp(app, "unlink-signin");
860
+ await linkProvider(betterAuthApp, target.id, "github");
861
+
862
+ await unlinkProvider(app, operator.token, target.id, "github").expect(200);
863
+
864
+ expect((await signInWithPassword(app, target.email)).status).toBe(200);
865
+ });
866
+ });
867
+ });