@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.
- package/CHANGELOG.md +2071 -2
- 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,844 @@
|
|
|
1
|
+
import {afterEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import mongoose, {Schema} from "mongoose";
|
|
4
|
+
import passportLocalMongoose from "passport-local-mongoose";
|
|
5
|
+
import supertest from "supertest";
|
|
6
|
+
import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
|
|
7
|
+
import type {BetterAuthConfig, BetterAuthUser} from "./betterAuth";
|
|
8
|
+
import {BetterAuthApp} from "./betterAuthApp";
|
|
9
|
+
import {
|
|
10
|
+
type BetterAuthInstance,
|
|
11
|
+
createBetterAuth,
|
|
12
|
+
createBetterAuthSessionMiddleware,
|
|
13
|
+
getMongoClientFromMongoose,
|
|
14
|
+
mountBetterAuthRoutes,
|
|
15
|
+
syncBetterAuthUser,
|
|
16
|
+
VERIFY_EMAIL_TO_USE_ACCOUNT,
|
|
17
|
+
} from "./betterAuthSetup";
|
|
18
|
+
import {isAPIError} from "./errors";
|
|
19
|
+
import {TerrenoApp} from "./terrenoApp";
|
|
20
|
+
import {
|
|
21
|
+
API_ORIGIN,
|
|
22
|
+
betterAuthAccounts,
|
|
23
|
+
betterAuthUsers,
|
|
24
|
+
newStubIdentity,
|
|
25
|
+
PASSWORD,
|
|
26
|
+
SECRET,
|
|
27
|
+
type StubIdentity,
|
|
28
|
+
signInWithStub,
|
|
29
|
+
stubGoogleIdTokenOptions,
|
|
30
|
+
stubOidcPlugin,
|
|
31
|
+
uniqueEmail,
|
|
32
|
+
} from "./tests/betterAuthStubs";
|
|
33
|
+
|
|
34
|
+
// A legacy (JWT/passport) app User model, as an app that adds Better Auth later has it.
|
|
35
|
+
// `configure` adjusts the schema before the model is compiled (once per name).
|
|
36
|
+
const legacyUserModel = (
|
|
37
|
+
name: string,
|
|
38
|
+
passportOptions: Record<string, unknown> = {},
|
|
39
|
+
configure?: (schema: Schema) => void
|
|
40
|
+
): mongoose.Model<Record<string, unknown>> => {
|
|
41
|
+
const existing = mongoose.models[name] as mongoose.Model<Record<string, unknown>> | undefined;
|
|
42
|
+
if (existing) {
|
|
43
|
+
return existing;
|
|
44
|
+
}
|
|
45
|
+
const schema = new Schema({
|
|
46
|
+
admin: {default: false, description: "Whether the user is an admin", type: Boolean},
|
|
47
|
+
betterAuthId: {description: "The linked Better Auth user id", type: String},
|
|
48
|
+
email: {description: "The user's email", required: true, type: String},
|
|
49
|
+
name: {description: "The user's display name", type: String},
|
|
50
|
+
oauthProvider: {description: "The provider the user first signed in with", type: String},
|
|
51
|
+
});
|
|
52
|
+
schema.plugin(
|
|
53
|
+
passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
|
|
54
|
+
{usernameCaseInsensitive: true, usernameField: "email", ...passportOptions}
|
|
55
|
+
);
|
|
56
|
+
configure?.(schema);
|
|
57
|
+
return mongoose.model<Record<string, unknown>>(name, schema);
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const LinkingUser = legacyUserModel("BetterAuthLinkingUser");
|
|
61
|
+
const userModel = LinkingUser as unknown as UserModel;
|
|
62
|
+
|
|
63
|
+
const OTHER_PASSWORD = "another-password-987";
|
|
64
|
+
|
|
65
|
+
interface LinkingApp {
|
|
66
|
+
app: express.Application;
|
|
67
|
+
auth: BetterAuthInstance;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Mounted as BetterAuthApp mounts it: session middleware, then Better Auth's routes, then a
|
|
71
|
+
// route that reports the app User the request resolved to.
|
|
72
|
+
const buildApp = (overrides: Partial<BetterAuthConfig> = {}): LinkingApp => {
|
|
73
|
+
const config: BetterAuthConfig = {
|
|
74
|
+
baseURL: API_ORIGIN,
|
|
75
|
+
enabled: true,
|
|
76
|
+
secret: SECRET,
|
|
77
|
+
...overrides,
|
|
78
|
+
};
|
|
79
|
+
const auth = createBetterAuth({config, mongoClient: getMongoClientFromMongoose(), userModel});
|
|
80
|
+
const app = express();
|
|
81
|
+
app.use(createBetterAuthSessionMiddleware(auth, userModel));
|
|
82
|
+
mountBetterAuthRoutes(app, auth, config.basePath);
|
|
83
|
+
app.get("/me", (req, res) => {
|
|
84
|
+
const user = req.user as {email?: string; id?: string} | undefined;
|
|
85
|
+
if (!user) {
|
|
86
|
+
return res.status(401).json({title: "Unauthorized"});
|
|
87
|
+
}
|
|
88
|
+
return res.json({email: user.email, id: user.id});
|
|
89
|
+
});
|
|
90
|
+
return {app, auth};
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// An app that offers Google ID-token sign-in, with Google reporting `identity`.
|
|
94
|
+
const buildGoogleApp = (
|
|
95
|
+
identity: StubIdentity,
|
|
96
|
+
overrides: Partial<BetterAuthConfig> = {}
|
|
97
|
+
): LinkingApp =>
|
|
98
|
+
buildApp({
|
|
99
|
+
googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
|
|
100
|
+
options: stubGoogleIdTokenOptions(identity),
|
|
101
|
+
...overrides,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
const signUpEmail = (
|
|
105
|
+
app: express.Application,
|
|
106
|
+
email: string,
|
|
107
|
+
password = PASSWORD
|
|
108
|
+
): Promise<supertest.Response> =>
|
|
109
|
+
supertest(app)
|
|
110
|
+
.post("/api/auth/sign-up/email")
|
|
111
|
+
.set("content-type", "application/json")
|
|
112
|
+
.send({email, name: "Email User", password});
|
|
113
|
+
|
|
114
|
+
const signInWithGoogle = (app: express.Application): Promise<supertest.Response> =>
|
|
115
|
+
supertest(app)
|
|
116
|
+
.post("/api/auth/sign-in/social")
|
|
117
|
+
.set("content-type", "application/json")
|
|
118
|
+
.send({idToken: {token: "stub-id-token"}, provider: "google"});
|
|
119
|
+
|
|
120
|
+
const linkGoogle = (app: express.Application, token: string): Promise<supertest.Response> =>
|
|
121
|
+
supertest(app)
|
|
122
|
+
.post("/api/auth/link-social")
|
|
123
|
+
.set("authorization", `Bearer ${token}`)
|
|
124
|
+
.set("content-type", "application/json")
|
|
125
|
+
.send({idToken: {token: "stub-id-token"}, provider: "google"});
|
|
126
|
+
|
|
127
|
+
// Marks the Better Auth user's email verified, as clicking the verification link does.
|
|
128
|
+
const markEmailVerified = async (email: string): Promise<void> => {
|
|
129
|
+
await betterAuthUsers().updateOne({email}, {$set: {emailVerified: true}});
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const accountCount = async (email: string): Promise<number> => {
|
|
133
|
+
const user = await betterAuthUsers().findOne({email});
|
|
134
|
+
if (!user) {
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
return betterAuthAccounts().countDocuments({userId: user._id});
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const appUsers = (email: string): Promise<number> => LinkingUser.countDocuments({email});
|
|
141
|
+
|
|
142
|
+
// A legacy app User with a passport-local-mongoose hash, or none (a GitHub-JWT user).
|
|
143
|
+
const createLegacyUser = async (
|
|
144
|
+
email: string,
|
|
145
|
+
password?: string,
|
|
146
|
+
model: mongoose.Model<Record<string, unknown>> = LinkingUser
|
|
147
|
+
): Promise<mongoose.HydratedDocument<Record<string, unknown>>> => {
|
|
148
|
+
const user = new model({email, name: "Legacy User"});
|
|
149
|
+
if (password) {
|
|
150
|
+
await setPasswordForUser(user as unknown as HasSetPassword, password);
|
|
151
|
+
}
|
|
152
|
+
await user.save();
|
|
153
|
+
return user;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// Proves nothing was left behind for `email` at the Better Auth layer.
|
|
157
|
+
const expectNoBetterAuthUser = async (email: string): Promise<void> => {
|
|
158
|
+
expect(await betterAuthUsers().countDocuments({email})).toBe(0);
|
|
159
|
+
expect(await accountCount(email)).toBe(0);
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const signInEmail = (
|
|
163
|
+
app: express.Application,
|
|
164
|
+
email: string,
|
|
165
|
+
password = PASSWORD
|
|
166
|
+
): Promise<supertest.Response> =>
|
|
167
|
+
supertest(app)
|
|
168
|
+
.post("/api/auth/sign-in/email")
|
|
169
|
+
.set("content-type", "application/json")
|
|
170
|
+
.send({email, password});
|
|
171
|
+
|
|
172
|
+
afterEach(async () => {
|
|
173
|
+
await LinkingUser.deleteMany({});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
describe("accountLinking: verified-email", () => {
|
|
177
|
+
it("joins a verified Google sign-in to the verified email account", async () => {
|
|
178
|
+
const identity = newStubIdentity("verified-join");
|
|
179
|
+
const {app} = buildGoogleApp(identity, {accountLinking: {mode: "verified-email"}});
|
|
180
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
181
|
+
expect(signUp.status).toBe(200);
|
|
182
|
+
await markEmailVerified(identity.email);
|
|
183
|
+
|
|
184
|
+
const google = await signInWithGoogle(app);
|
|
185
|
+
|
|
186
|
+
expect(google.status).toBe(200);
|
|
187
|
+
expect(google.body.user.email).toBe(identity.email);
|
|
188
|
+
expect(await betterAuthUsers().countDocuments({email: identity.email})).toBe(1);
|
|
189
|
+
expect(await accountCount(identity.email)).toBe(2);
|
|
190
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
191
|
+
const me = await supertest(app).get("/me").set("authorization", `Bearer ${google.body.token}`);
|
|
192
|
+
expect(me.body.email).toBe(identity.email);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it("refuses with account_not_linked while the local email is unverified", async () => {
|
|
196
|
+
const identity = newStubIdentity("verified-unverified-local");
|
|
197
|
+
const {app} = buildGoogleApp(identity, {
|
|
198
|
+
accountLinking: {mode: "verified-email"},
|
|
199
|
+
plugins: [stubOidcPlugin(identity)],
|
|
200
|
+
});
|
|
201
|
+
expect((await signUpEmail(app, identity.email)).status).toBe(200);
|
|
202
|
+
|
|
203
|
+
const google = await signInWithGoogle(app);
|
|
204
|
+
const redirect = await signInWithStub(app);
|
|
205
|
+
|
|
206
|
+
expect(google.status).toBe(401);
|
|
207
|
+
expect(google.body.message).toBe("account not linked");
|
|
208
|
+
expect(redirect.searchParams.get("error")).toBe("account_not_linked");
|
|
209
|
+
expect(await betterAuthUsers().countDocuments({email: identity.email})).toBe(1);
|
|
210
|
+
expect(await accountCount(identity.email)).toBe(1);
|
|
211
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
describe("accountLinking: explicit", () => {
|
|
216
|
+
it("refuses the implicit sign-in, then links from the signed-in session", async () => {
|
|
217
|
+
const identity = newStubIdentity("explicit-link");
|
|
218
|
+
const {app} = buildGoogleApp(identity, {
|
|
219
|
+
accountLinking: {mode: "explicit"},
|
|
220
|
+
plugins: [stubOidcPlugin(identity)],
|
|
221
|
+
});
|
|
222
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
223
|
+
await markEmailVerified(identity.email);
|
|
224
|
+
|
|
225
|
+
const google = await signInWithGoogle(app);
|
|
226
|
+
const redirect = await signInWithStub(app);
|
|
227
|
+
|
|
228
|
+
expect(google.status).toBe(401);
|
|
229
|
+
expect(google.body.message).toBe("account not linked");
|
|
230
|
+
expect(redirect.searchParams.get("error")).toBe("account_not_linked");
|
|
231
|
+
expect(await accountCount(identity.email)).toBe(1);
|
|
232
|
+
|
|
233
|
+
const link = await linkGoogle(app, signUp.body.token);
|
|
234
|
+
expect(link.status).toBe(200);
|
|
235
|
+
expect(await accountCount(identity.email)).toBe(2);
|
|
236
|
+
|
|
237
|
+
const after = await signInWithGoogle(app);
|
|
238
|
+
expect(after.status).toBe(200);
|
|
239
|
+
expect(await betterAuthUsers().countDocuments({email: identity.email})).toBe(1);
|
|
240
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe("accountLinking: never", () => {
|
|
245
|
+
it("refuses /link-social with 403 and a same-email social sign-in", async () => {
|
|
246
|
+
const identity = newStubIdentity("never-link");
|
|
247
|
+
const {app} = buildGoogleApp(identity, {accountLinking: {mode: "never"}});
|
|
248
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
249
|
+
await markEmailVerified(identity.email);
|
|
250
|
+
|
|
251
|
+
const link = await linkGoogle(app, signUp.body.token);
|
|
252
|
+
const redirectLink = await supertest(app)
|
|
253
|
+
.post("/api/auth/link-social")
|
|
254
|
+
.set("authorization", `Bearer ${signUp.body.token}`)
|
|
255
|
+
.set("content-type", "application/json")
|
|
256
|
+
.send({callbackURL: `${API_ORIGIN}/done`, provider: "google"});
|
|
257
|
+
const google = await signInWithGoogle(app);
|
|
258
|
+
|
|
259
|
+
expect(link.status).toBe(403);
|
|
260
|
+
expect(link.body.code).toBe("LINKING_DISABLED");
|
|
261
|
+
expect(redirectLink.status).toBe(403);
|
|
262
|
+
expect(google.status).toBe(401);
|
|
263
|
+
expect(google.body.message).toBe("account not linked");
|
|
264
|
+
expect(await accountCount(identity.email)).toBe(1);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("refuses /link-social when options turn linking off", async () => {
|
|
268
|
+
const identity = newStubIdentity("options-never-link");
|
|
269
|
+
const {app} = buildApp({
|
|
270
|
+
googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
|
|
271
|
+
options: {
|
|
272
|
+
...stubGoogleIdTokenOptions(identity),
|
|
273
|
+
account: {accountLinking: {enabled: false}},
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
277
|
+
|
|
278
|
+
const link = await linkGoogle(app, signUp.body.token);
|
|
279
|
+
|
|
280
|
+
expect(link.status).toBe(403);
|
|
281
|
+
expect(link.body.code).toBe("LINKING_DISABLED");
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it("leaves /link-social alone in the other modes", async () => {
|
|
285
|
+
const identity = newStubIdentity("other-modes-link");
|
|
286
|
+
const {app} = buildGoogleApp(identity, {accountLinking: {mode: "verified-email"}});
|
|
287
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
288
|
+
|
|
289
|
+
const link = await linkGoogle(app, signUp.body.token);
|
|
290
|
+
|
|
291
|
+
expect(link.status).toBe(200);
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
describe("unverified provider emails", () => {
|
|
296
|
+
for (const mode of ["verified-email", "explicit"] as const) {
|
|
297
|
+
it(`never links an unverified provider email in ${mode} mode`, async () => {
|
|
298
|
+
const identity: StubIdentity = {
|
|
299
|
+
...newStubIdentity(`unverified-${mode}`),
|
|
300
|
+
emailVerified: false,
|
|
301
|
+
};
|
|
302
|
+
const {app} = buildGoogleApp(identity, {
|
|
303
|
+
accountLinking: {mode},
|
|
304
|
+
plugins: [stubOidcPlugin(identity)],
|
|
305
|
+
});
|
|
306
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
307
|
+
await markEmailVerified(identity.email);
|
|
308
|
+
|
|
309
|
+
const google = await signInWithGoogle(app);
|
|
310
|
+
const redirect = await signInWithStub(app);
|
|
311
|
+
const link = await linkGoogle(app, signUp.body.token);
|
|
312
|
+
|
|
313
|
+
expect(google.status).toBe(401);
|
|
314
|
+
expect(redirect.searchParams.get("error")).toBe("account_not_linked");
|
|
315
|
+
expect(link.status).toBe(401);
|
|
316
|
+
expect(link.body.code).toBe("LINKING_NOT_ALLOWED");
|
|
317
|
+
expect(await accountCount(identity.email)).toBe(1);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
describe("unlinking", () => {
|
|
323
|
+
it("refuses to unlink the only remaining sign-in method", async () => {
|
|
324
|
+
const {app} = buildApp();
|
|
325
|
+
const email = uniqueEmail("unlink-last");
|
|
326
|
+
const signUp = await signUpEmail(app, email);
|
|
327
|
+
|
|
328
|
+
const accounts = await supertest(app)
|
|
329
|
+
.get("/api/auth/list-accounts")
|
|
330
|
+
.set("authorization", `Bearer ${signUp.body.token}`);
|
|
331
|
+
expect(accounts.body).toHaveLength(1);
|
|
332
|
+
|
|
333
|
+
const unlink = await supertest(app)
|
|
334
|
+
.post("/api/auth/unlink-account")
|
|
335
|
+
.set("authorization", `Bearer ${signUp.body.token}`)
|
|
336
|
+
.set("content-type", "application/json")
|
|
337
|
+
.send({accountId: accounts.body[0].id});
|
|
338
|
+
|
|
339
|
+
expect(unlink.status).toBe(400);
|
|
340
|
+
expect(unlink.body.code).toBe("FAILED_TO_UNLINK_LAST_ACCOUNT");
|
|
341
|
+
expect(await accountCount(email)).toBe(1);
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
describe("legacy app User migration", () => {
|
|
346
|
+
it("links a Better Auth sign-up whose password matches the legacy hash", async () => {
|
|
347
|
+
const {app} = buildApp();
|
|
348
|
+
const email = uniqueEmail("legacy-same");
|
|
349
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
350
|
+
|
|
351
|
+
const signUp = await signUpEmail(app, email);
|
|
352
|
+
|
|
353
|
+
expect(signUp.status).toBe(200);
|
|
354
|
+
expect(await appUsers(email)).toBe(1);
|
|
355
|
+
const stored = await LinkingUser.findById(legacy._id).lean();
|
|
356
|
+
expect(stored?.betterAuthId).toBe(signUp.body.user.id);
|
|
357
|
+
const me = await supertest(app).get("/me").set("authorization", `Bearer ${signUp.body.token}`);
|
|
358
|
+
expect(me.body.id).toBe(String(legacy._id));
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it("refuses a sign-up with a different password before anything is created", async () => {
|
|
362
|
+
const sent: string[] = [];
|
|
363
|
+
const {app} = buildApp({
|
|
364
|
+
publicAppUrl: "http://localhost:8082",
|
|
365
|
+
sendMail: async (message): Promise<void> => {
|
|
366
|
+
sent.push(message.to);
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
const email = uniqueEmail("legacy-different");
|
|
370
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
371
|
+
|
|
372
|
+
const signUp = await signUpEmail(app, email, OTHER_PASSWORD);
|
|
373
|
+
|
|
374
|
+
expect(signUp.status).toBe(409);
|
|
375
|
+
expect(signUp.body.message).toBe(VERIFY_EMAIL_TO_USE_ACCOUNT);
|
|
376
|
+
expect(signUp.body.code).toBe("VERIFY_EMAIL_TO_USE_ACCOUNT");
|
|
377
|
+
await expectNoBetterAuthUser(email);
|
|
378
|
+
expect(sent).toEqual([]);
|
|
379
|
+
expect(await appUsers(email)).toBe(1);
|
|
380
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBeUndefined();
|
|
381
|
+
|
|
382
|
+
// The attacker's password opens nothing: there is no Better Auth user to sign in to.
|
|
383
|
+
const signIn = await signInEmail(app, email, OTHER_PASSWORD);
|
|
384
|
+
expect(signIn.status).toBe(401);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
it("refuses a sign-up for a User bound to another Better Auth account before anything is created", async () => {
|
|
388
|
+
const {app} = buildApp();
|
|
389
|
+
const email = uniqueEmail("legacy-bound");
|
|
390
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
391
|
+
await LinkingUser.updateOne({_id: legacy._id}, {$set: {betterAuthId: "ba-gone"}});
|
|
392
|
+
|
|
393
|
+
const signUp = await signUpEmail(app, email);
|
|
394
|
+
|
|
395
|
+
expect(signUp.status).toBe(409);
|
|
396
|
+
expect(signUp.body.code).toBe("ACCOUNT_ALREADY_EXISTS");
|
|
397
|
+
await expectNoBetterAuthUser(email);
|
|
398
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBe("ba-gone");
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
it("leaves nothing for a later verification to link when a legacy User has no hash", async () => {
|
|
402
|
+
const identity = newStubIdentity("legacy-no-hash");
|
|
403
|
+
const {app} = buildGoogleApp(identity);
|
|
404
|
+
const legacy = await createLegacyUser(identity.email);
|
|
405
|
+
|
|
406
|
+
const signUp = await signUpEmail(app, identity.email);
|
|
407
|
+
|
|
408
|
+
expect(signUp.status).toBe(409);
|
|
409
|
+
expect(signUp.body.message).toBe(VERIFY_EMAIL_TO_USE_ACCOUNT);
|
|
410
|
+
await expectNoBetterAuthUser(identity.email);
|
|
411
|
+
|
|
412
|
+
// Verifying the email (the link mail, an admin action) has no Better Auth user to act on,
|
|
413
|
+
// so the refused sign-up's password never opens the legacy User.
|
|
414
|
+
await markEmailVerified(identity.email);
|
|
415
|
+
const signIn = await signInEmail(app, identity.email);
|
|
416
|
+
expect(signIn.status).toBe(401);
|
|
417
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBeUndefined();
|
|
418
|
+
|
|
419
|
+
// A provider sign-in with a verified email is the way in.
|
|
420
|
+
const google = await signInWithGoogle(app);
|
|
421
|
+
expect(google.status).toBe(200);
|
|
422
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
423
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBe(google.body.user.id);
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
it("links a legacy User to a verified Google sign-in and records the provider", async () => {
|
|
427
|
+
const identity = newStubIdentity("legacy-google");
|
|
428
|
+
const {app} = buildGoogleApp(identity);
|
|
429
|
+
const legacy = await createLegacyUser(identity.email, PASSWORD);
|
|
430
|
+
|
|
431
|
+
const google = await signInWithGoogle(app);
|
|
432
|
+
|
|
433
|
+
expect(google.status).toBe(200);
|
|
434
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
435
|
+
const stored = await LinkingUser.findById(legacy._id).lean();
|
|
436
|
+
expect(stored?.betterAuthId).toBe(google.body.user.id);
|
|
437
|
+
expect(stored?.oauthProvider).toBe("google");
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
it("refuses an unverified provider email for a legacy User before anything is created", async () => {
|
|
441
|
+
const identity: StubIdentity = {...newStubIdentity("legacy-unverified"), emailVerified: false};
|
|
442
|
+
const {app} = buildApp({plugins: [stubOidcPlugin(identity)]});
|
|
443
|
+
await createLegacyUser(identity.email, PASSWORD);
|
|
444
|
+
|
|
445
|
+
const redirect = await signInWithStub(app);
|
|
446
|
+
|
|
447
|
+
expect(redirect.searchParams.get("error")).toBe("VERIFY_EMAIL_TO_USE_ACCOUNT");
|
|
448
|
+
await expectNoBetterAuthUser(identity.email);
|
|
449
|
+
expect(await appUsers(identity.email)).toBe(1);
|
|
450
|
+
expect((await LinkingUser.findOne({email: identity.email}).lean())?.betterAuthId).toBe(
|
|
451
|
+
undefined
|
|
452
|
+
);
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
it("refuses an unverified ID-token email for a legacy User before anything is created", async () => {
|
|
456
|
+
const identity: StubIdentity = {
|
|
457
|
+
...newStubIdentity("legacy-unverified-id-token"),
|
|
458
|
+
emailVerified: false,
|
|
459
|
+
};
|
|
460
|
+
const {app} = buildGoogleApp(identity);
|
|
461
|
+
await createLegacyUser(identity.email, PASSWORD);
|
|
462
|
+
|
|
463
|
+
const google = await signInWithGoogle(app);
|
|
464
|
+
|
|
465
|
+
expect(google.status).toBe(409);
|
|
466
|
+
expect(google.body.code).toBe("VERIFY_EMAIL_TO_USE_ACCOUNT");
|
|
467
|
+
await expectNoBetterAuthUser(identity.email);
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
it("records the provider on a User created by an ID-token sign-in", async () => {
|
|
471
|
+
const identity = newStubIdentity("new-google");
|
|
472
|
+
const {app} = buildGoogleApp(identity);
|
|
473
|
+
|
|
474
|
+
const google = await signInWithGoogle(app);
|
|
475
|
+
|
|
476
|
+
expect(google.status).toBe(200);
|
|
477
|
+
const stored = await LinkingUser.findOne({email: identity.email}).lean();
|
|
478
|
+
expect(stored?.betterAuthId).toBe(google.body.user.id);
|
|
479
|
+
expect(stored?.oauthProvider).toBe("google");
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it("records the provider on a User created by an OAuth redirect sign-in", async () => {
|
|
483
|
+
const identity = newStubIdentity("new-stub");
|
|
484
|
+
const {app} = buildApp({plugins: [stubOidcPlugin(identity)]});
|
|
485
|
+
|
|
486
|
+
const redirect = await signInWithStub(app);
|
|
487
|
+
|
|
488
|
+
expect(redirect.searchParams.get("error")).toBeNull();
|
|
489
|
+
const stored = await LinkingUser.findOne({email: identity.email}).lean();
|
|
490
|
+
expect(stored?.oauthProvider).toBe("stub-oidc");
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
it("creates a User for an unverified sign-up when no User has the email", async () => {
|
|
494
|
+
const {app} = buildApp();
|
|
495
|
+
const email = uniqueEmail("fresh");
|
|
496
|
+
|
|
497
|
+
const signUp = await signUpEmail(app, email);
|
|
498
|
+
|
|
499
|
+
expect(signUp.status).toBe(200);
|
|
500
|
+
const stored = await LinkingUser.findOne({email}).lean();
|
|
501
|
+
expect(stored?.betterAuthId).toBe(signUp.body.user.id);
|
|
502
|
+
expect(stored?.oauthProvider).toBeUndefined();
|
|
503
|
+
});
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
describe("TerrenoApp wiring without a userModel on BetterAuthApp", () => {
|
|
507
|
+
// TerrenoApp's userModel is the only one in play; BetterAuthApp must adopt it so the guard
|
|
508
|
+
// runs, since TerrenoApp's session middleware links app Users with it.
|
|
509
|
+
const buildTerrenoApp = (config: Partial<BetterAuthConfig> = {}): express.Application =>
|
|
510
|
+
new TerrenoApp({
|
|
511
|
+
configureApp: (app: express.Application): void => {
|
|
512
|
+
app.get("/me", (req, res) => {
|
|
513
|
+
const user = req.user as {id?: string} | undefined;
|
|
514
|
+
return user ? res.json({id: user.id}) : res.status(401).json({});
|
|
515
|
+
});
|
|
516
|
+
},
|
|
517
|
+
skipListen: true,
|
|
518
|
+
userModel,
|
|
519
|
+
} as never)
|
|
520
|
+
.register(
|
|
521
|
+
new BetterAuthApp({config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET, ...config}})
|
|
522
|
+
)
|
|
523
|
+
.build();
|
|
524
|
+
|
|
525
|
+
it("refuses an unverified sign-up for a legacy User and leaves nothing behind", async () => {
|
|
526
|
+
const sent: string[] = [];
|
|
527
|
+
const app = buildTerrenoApp({
|
|
528
|
+
publicAppUrl: "http://localhost:8082",
|
|
529
|
+
sendMail: async (message): Promise<void> => {
|
|
530
|
+
sent.push(message.to);
|
|
531
|
+
},
|
|
532
|
+
});
|
|
533
|
+
const email = uniqueEmail("terreno-app-guard");
|
|
534
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
535
|
+
|
|
536
|
+
const signUp = await signUpEmail(app, email, OTHER_PASSWORD);
|
|
537
|
+
|
|
538
|
+
expect(signUp.status).toBe(409);
|
|
539
|
+
expect(signUp.body.code).toBe("VERIFY_EMAIL_TO_USE_ACCOUNT");
|
|
540
|
+
await expectNoBetterAuthUser(email);
|
|
541
|
+
expect(sent).toEqual([]);
|
|
542
|
+
await markEmailVerified(email);
|
|
543
|
+
expect((await signInEmail(app, email, OTHER_PASSWORD)).status).toBe(401);
|
|
544
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBeUndefined();
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it("links a sign-up whose password matches the legacy hash", async () => {
|
|
548
|
+
const app = buildTerrenoApp();
|
|
549
|
+
const email = uniqueEmail("terreno-app-link");
|
|
550
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
551
|
+
|
|
552
|
+
const signUp = await signUpEmail(app, email);
|
|
553
|
+
|
|
554
|
+
expect(signUp.status).toBe(200);
|
|
555
|
+
const me = await supertest(app).get("/me").set("authorization", `Bearer ${signUp.body.token}`);
|
|
556
|
+
expect(me.body.id).toBe(String(legacy._id));
|
|
557
|
+
expect(await appUsers(email)).toBe(1);
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
it("refuses at boot when Better Auth was created before the userModel arrived", () => {
|
|
561
|
+
const betterAuthApp = new BetterAuthApp({
|
|
562
|
+
config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET},
|
|
563
|
+
});
|
|
564
|
+
betterAuthApp.ensureAuth();
|
|
565
|
+
|
|
566
|
+
expect(() => betterAuthApp.adoptUserModel(userModel)).toThrow(
|
|
567
|
+
"BetterAuthApp created Better Auth before it was given a userModel"
|
|
568
|
+
);
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
it("keeps a userModel BetterAuthApp was given", () => {
|
|
572
|
+
const betterAuthApp = new BetterAuthApp({
|
|
573
|
+
config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET},
|
|
574
|
+
userModel,
|
|
575
|
+
});
|
|
576
|
+
betterAuthApp.ensureAuth();
|
|
577
|
+
|
|
578
|
+
expect(() => betterAuthApp.adoptUserModel(userModel)).not.toThrow();
|
|
579
|
+
});
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
describe("legacy Users stored with a mixed-case email", () => {
|
|
583
|
+
const mixedCase = (label: string): string => {
|
|
584
|
+
const email = uniqueEmail(label);
|
|
585
|
+
return `${email[0].toUpperCase()}${email.slice(1, email.indexOf("@"))}@Example.COM`;
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
it("refuses an unverified sign-up on the lowercased email and leaves nothing behind", async () => {
|
|
589
|
+
const {app} = buildApp();
|
|
590
|
+
const stored = mixedCase("mixed-refuse");
|
|
591
|
+
const legacy = await createLegacyUser(stored, PASSWORD);
|
|
592
|
+
|
|
593
|
+
const signUp = await signUpEmail(app, stored.toLowerCase(), OTHER_PASSWORD);
|
|
594
|
+
|
|
595
|
+
expect(signUp.status).toBe(409);
|
|
596
|
+
await expectNoBetterAuthUser(stored.toLowerCase());
|
|
597
|
+
expect(await LinkingUser.countDocuments({})).toBe(1);
|
|
598
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBeUndefined();
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
it("links the mixed-case User on a matching password without a duplicate", async () => {
|
|
602
|
+
const {app} = buildApp();
|
|
603
|
+
const stored = mixedCase("mixed-link");
|
|
604
|
+
const legacy = await createLegacyUser(stored, PASSWORD);
|
|
605
|
+
|
|
606
|
+
const signUp = await signUpEmail(app, stored);
|
|
607
|
+
|
|
608
|
+
expect(signUp.status).toBe(200);
|
|
609
|
+
expect(await LinkingUser.countDocuments({})).toBe(1);
|
|
610
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBe(signUp.body.user.id);
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
it("matches the email literally, not as a pattern", async () => {
|
|
614
|
+
const {app} = buildApp();
|
|
615
|
+
const suffix = new mongoose.Types.ObjectId().toString();
|
|
616
|
+
// Unescaped, the "." in the sign-up email would match the "x" in the legacy one.
|
|
617
|
+
await createLegacyUser(`axb-${suffix}@example.com`, PASSWORD);
|
|
618
|
+
|
|
619
|
+
const signUp = await signUpEmail(app, `a.b-${suffix}@example.com`, OTHER_PASSWORD);
|
|
620
|
+
|
|
621
|
+
expect(signUp.status).toBe(200);
|
|
622
|
+
expect(await LinkingUser.countDocuments({})).toBe(2);
|
|
623
|
+
});
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
describe("legacy password checks with limitAttempts", () => {
|
|
627
|
+
const LimitedUser = legacyUserModel("BetterAuthLinkingLimitedUser", {
|
|
628
|
+
limitAttempts: true,
|
|
629
|
+
maxAttempts: 2,
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
afterEach(async () => {
|
|
633
|
+
await LimitedUser.deleteMany({});
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
it("does not count Better Auth sign-ups against the legacy JWT login", async () => {
|
|
637
|
+
const auth = createBetterAuth({
|
|
638
|
+
config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET},
|
|
639
|
+
mongoClient: getMongoClientFromMongoose(),
|
|
640
|
+
userModel: LimitedUser as unknown as UserModel,
|
|
641
|
+
});
|
|
642
|
+
const app = express();
|
|
643
|
+
mountBetterAuthRoutes(app, auth);
|
|
644
|
+
const email = uniqueEmail("limited");
|
|
645
|
+
const legacy = await createLegacyUser(email, PASSWORD, LimitedUser);
|
|
646
|
+
|
|
647
|
+
for (const attempt of [1, 2, 3]) {
|
|
648
|
+
const signUp = await signUpEmail(app, email, `${OTHER_PASSWORD}-${attempt}`);
|
|
649
|
+
expect(signUp.status).toBe(409);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const stored = await LimitedUser.findById(legacy._id).lean();
|
|
653
|
+
expect(stored?.attempts).toBe(0);
|
|
654
|
+
const jwtLogin = await (
|
|
655
|
+
LimitedUser as unknown as {
|
|
656
|
+
authenticate: () => (
|
|
657
|
+
email: string,
|
|
658
|
+
password: string,
|
|
659
|
+
done: (error: unknown, user: unknown) => void
|
|
660
|
+
) => void;
|
|
661
|
+
}
|
|
662
|
+
).authenticate();
|
|
663
|
+
const loggedIn = await new Promise<unknown>((resolve, reject) => {
|
|
664
|
+
jwtLogin(email, PASSWORD, (error, user) => (error ? reject(error) : resolve(user)));
|
|
665
|
+
});
|
|
666
|
+
expect(loggedIn).toBeTruthy();
|
|
667
|
+
|
|
668
|
+
const signUp = await signUpEmail(app, email);
|
|
669
|
+
expect(signUp.status).toBe(200);
|
|
670
|
+
expect((await LimitedUser.findById(legacy._id).lean())?.betterAuthId).toBe(signUp.body.user.id);
|
|
671
|
+
});
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
describe("app User sync on sign-in failures", () => {
|
|
675
|
+
it("still signs in when the sync fails for a reason other than an unverified email", async () => {
|
|
676
|
+
// A consumer User schema that requires a field the sync does not set.
|
|
677
|
+
const Demanding =
|
|
678
|
+
(mongoose.models.BetterAuthLinkingDemandingUser as mongoose.Model<unknown> | undefined) ??
|
|
679
|
+
mongoose.model(
|
|
680
|
+
"BetterAuthLinkingDemandingUser",
|
|
681
|
+
new Schema({
|
|
682
|
+
betterAuthId: {description: "The linked Better Auth user id", type: String},
|
|
683
|
+
email: {description: "The user's email", required: true, type: String},
|
|
684
|
+
orgId: {description: "The user's organization", required: true, type: String},
|
|
685
|
+
})
|
|
686
|
+
);
|
|
687
|
+
const auth = createBetterAuth({
|
|
688
|
+
config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET},
|
|
689
|
+
mongoClient: getMongoClientFromMongoose(),
|
|
690
|
+
userModel: Demanding as unknown as UserModel,
|
|
691
|
+
});
|
|
692
|
+
const app = express();
|
|
693
|
+
mountBetterAuthRoutes(app, auth);
|
|
694
|
+
const email = uniqueEmail("sync-failure");
|
|
695
|
+
|
|
696
|
+
const signUp = await signUpEmail(app, email);
|
|
697
|
+
|
|
698
|
+
expect(signUp.status).toBe(200);
|
|
699
|
+
expect(await Demanding.countDocuments({email})).toBe(0);
|
|
700
|
+
});
|
|
701
|
+
|
|
702
|
+
it("fails the sign-in when a password-proven link cannot be saved, then links on retry", async () => {
|
|
703
|
+
let isLinkFailing = true;
|
|
704
|
+
const FlakyUser = legacyUserModel("BetterAuthLinkingFlakyUser", {}, (schema) => {
|
|
705
|
+
schema.pre("save", function () {
|
|
706
|
+
if (isLinkFailing && this.isModified("betterAuthId")) {
|
|
707
|
+
throw new Error("primary stepped down");
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
});
|
|
711
|
+
const auth = createBetterAuth({
|
|
712
|
+
config: {baseURL: API_ORIGIN, enabled: true, secret: SECRET},
|
|
713
|
+
mongoClient: getMongoClientFromMongoose(),
|
|
714
|
+
userModel: FlakyUser as unknown as UserModel,
|
|
715
|
+
});
|
|
716
|
+
const app = express();
|
|
717
|
+
mountBetterAuthRoutes(app, auth);
|
|
718
|
+
const email = uniqueEmail("flaky-link");
|
|
719
|
+
const legacy = await createLegacyUser(email, PASSWORD, FlakyUser);
|
|
720
|
+
|
|
721
|
+
try {
|
|
722
|
+
const signUp = await signUpEmail(app, email);
|
|
723
|
+
|
|
724
|
+
expect(signUp.status).toBe(500);
|
|
725
|
+
expect(signUp.body.code).toBe("APP_USER_LINK_FAILED");
|
|
726
|
+
expect(signUp.body.token).toBeUndefined();
|
|
727
|
+
expect((await FlakyUser.findById(legacy._id).lean())?.betterAuthId).toBeUndefined();
|
|
728
|
+
|
|
729
|
+
isLinkFailing = false;
|
|
730
|
+
const signIn = await signInEmail(app, email);
|
|
731
|
+
expect(signIn.status).toBe(200);
|
|
732
|
+
expect((await FlakyUser.findById(legacy._id).lean())?.betterAuthId).toBe(signIn.body.user.id);
|
|
733
|
+
} finally {
|
|
734
|
+
await FlakyUser.deleteMany({});
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
});
|
|
738
|
+
|
|
739
|
+
describe("syncBetterAuthUser email matches", () => {
|
|
740
|
+
const unverifiedUser = (email: string): BetterAuthUser => ({
|
|
741
|
+
createdAt: new Date(),
|
|
742
|
+
email,
|
|
743
|
+
emailVerified: false,
|
|
744
|
+
id: new mongoose.Types.ObjectId().toString(),
|
|
745
|
+
image: null,
|
|
746
|
+
name: "Unverified",
|
|
747
|
+
updatedAt: new Date(),
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
it("throws a 409 APIError instead of claiming the User for an unverified email", async () => {
|
|
751
|
+
const email = uniqueEmail("sync-unverified");
|
|
752
|
+
await createLegacyUser(email, PASSWORD);
|
|
753
|
+
|
|
754
|
+
let caught: unknown;
|
|
755
|
+
try {
|
|
756
|
+
await syncBetterAuthUser(userModel, unverifiedUser(email));
|
|
757
|
+
} catch (error) {
|
|
758
|
+
caught = error;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
expect(isAPIError(caught)).toBe(true);
|
|
762
|
+
expect((caught as {status?: number}).status).toBe(409);
|
|
763
|
+
expect((caught as Error).message).toBe(VERIFY_EMAIL_TO_USE_ACCOUNT);
|
|
764
|
+
expect(await appUsers(email)).toBe(1);
|
|
765
|
+
});
|
|
766
|
+
|
|
767
|
+
it("links an unverified user when the password matches the legacy hash", async () => {
|
|
768
|
+
const email = uniqueEmail("sync-password");
|
|
769
|
+
await createLegacyUser(email, PASSWORD);
|
|
770
|
+
const betterAuthUser = unverifiedUser(email);
|
|
771
|
+
|
|
772
|
+
const linked = await syncBetterAuthUser(userModel, betterAuthUser, undefined, {
|
|
773
|
+
password: PASSWORD,
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
expect(linked.betterAuthId).toBe(betterAuthUser.id);
|
|
777
|
+
});
|
|
778
|
+
|
|
779
|
+
it("keeps the legacy password a password-proven link relied on", async () => {
|
|
780
|
+
const email = uniqueEmail("sync-password-keeps");
|
|
781
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
782
|
+
|
|
783
|
+
await syncBetterAuthUser(userModel, unverifiedUser(email), undefined, {password: PASSWORD});
|
|
784
|
+
|
|
785
|
+
const stored = await LinkingUser.collection.findOne({_id: legacy._id});
|
|
786
|
+
expect(typeof stored?.hash).toBe("string");
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
it("refuses a password-proven claim on a User bound to another Better Auth account", async () => {
|
|
790
|
+
const email = uniqueEmail("sync-password-bound");
|
|
791
|
+
const legacy = await createLegacyUser(email, PASSWORD);
|
|
792
|
+
await LinkingUser.updateOne({_id: legacy._id}, {$set: {betterAuthId: "ba-other"}});
|
|
793
|
+
|
|
794
|
+
await expect(
|
|
795
|
+
syncBetterAuthUser(userModel, unverifiedUser(email), undefined, {password: PASSWORD})
|
|
796
|
+
).rejects.toThrow("An account with this email already exists");
|
|
797
|
+
|
|
798
|
+
expect((await LinkingUser.findById(legacy._id).lean())?.betterAuthId).toBe("ba-other");
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
it("refuses when the passport password check throws", async () => {
|
|
802
|
+
const BrokenUser = legacyUserModel("BetterAuthLinkingBrokenUser", {}, (schema) => {
|
|
803
|
+
schema.methods.authenticate = async (): Promise<never> => {
|
|
804
|
+
throw new Error("hash store unavailable");
|
|
805
|
+
};
|
|
806
|
+
});
|
|
807
|
+
const email = uniqueEmail("sync-throws");
|
|
808
|
+
await createLegacyUser(email, PASSWORD, BrokenUser);
|
|
809
|
+
|
|
810
|
+
try {
|
|
811
|
+
await expect(
|
|
812
|
+
syncBetterAuthUser(BrokenUser as unknown as UserModel, unverifiedUser(email), undefined, {
|
|
813
|
+
password: PASSWORD,
|
|
814
|
+
})
|
|
815
|
+
).rejects.toThrow(VERIFY_EMAIL_TO_USE_ACCOUNT);
|
|
816
|
+
} finally {
|
|
817
|
+
await BrokenUser.deleteMany({});
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
it("refuses a password against a model without passport-local-mongoose", async () => {
|
|
822
|
+
const Plain =
|
|
823
|
+
(mongoose.models.BetterAuthLinkingPlainUser as mongoose.Model<unknown> | undefined) ??
|
|
824
|
+
mongoose.model(
|
|
825
|
+
"BetterAuthLinkingPlainUser",
|
|
826
|
+
new Schema({
|
|
827
|
+
betterAuthId: {description: "The linked Better Auth user id", type: String},
|
|
828
|
+
email: {description: "The user's email", required: true, type: String},
|
|
829
|
+
})
|
|
830
|
+
);
|
|
831
|
+
const email = uniqueEmail("sync-plain");
|
|
832
|
+
await Plain.create({email});
|
|
833
|
+
|
|
834
|
+
try {
|
|
835
|
+
await expect(
|
|
836
|
+
syncBetterAuthUser(Plain as unknown as UserModel, unverifiedUser(email), undefined, {
|
|
837
|
+
password: PASSWORD,
|
|
838
|
+
})
|
|
839
|
+
).rejects.toThrow(VERIFY_EMAIL_TO_USE_ACCOUNT);
|
|
840
|
+
} finally {
|
|
841
|
+
await Plain.deleteMany({});
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
});
|