@terreno/api 57.19.2 → 57.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +393 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
|
@@ -8,14 +8,17 @@ import {
|
|
|
8
8
|
findOneOrNone,
|
|
9
9
|
} from "../plugins";
|
|
10
10
|
|
|
11
|
-
export type AuditEventVerb = "created" | "deleted" | "updated";
|
|
12
|
-
|
|
11
|
+
export type AuditEventVerb = "created" | "deleted" | "updated" | "viewed";
|
|
12
|
+
/** Every framework surface that writes `AuditEvent` rows. `security` is AccountSecurityApp. */
|
|
13
|
+
export const AUDIT_EVENT_SOURCES = ["admin", "modelRouter", "rbac", "security"] as const;
|
|
14
|
+
export type AuditEventSource = (typeof AUDIT_EVENT_SOURCES)[number];
|
|
13
15
|
export type AuditEventOperation =
|
|
14
16
|
| "arrayPush"
|
|
15
17
|
| "arrayRemove"
|
|
16
18
|
| "arrayUpdate"
|
|
17
19
|
| "create"
|
|
18
20
|
| "delete"
|
|
21
|
+
| "read"
|
|
19
22
|
| "update";
|
|
20
23
|
|
|
21
24
|
type AuditEventMethods = Record<string, never>;
|
|
@@ -74,8 +77,8 @@ const auditEventSchema: AuditEventSchema = new mongoose.Schema<
|
|
|
74
77
|
type: String,
|
|
75
78
|
},
|
|
76
79
|
operation: {
|
|
77
|
-
description: "Fine-grained mutation kind",
|
|
78
|
-
enum: ["arrayPush", "arrayRemove", "arrayUpdate", "create", "delete", "update"],
|
|
80
|
+
description: "Fine-grained mutation kind, or read for an audited read",
|
|
81
|
+
enum: ["arrayPush", "arrayRemove", "arrayUpdate", "create", "delete", "read", "update"],
|
|
79
82
|
required: true,
|
|
80
83
|
type: String,
|
|
81
84
|
},
|
|
@@ -96,14 +99,14 @@ const auditEventSchema: AuditEventSchema = new mongoose.Schema<
|
|
|
96
99
|
},
|
|
97
100
|
source: {
|
|
98
101
|
description: "Which framework surface wrote this event",
|
|
99
|
-
enum: [
|
|
102
|
+
enum: [...AUDIT_EVENT_SOURCES],
|
|
100
103
|
index: true,
|
|
101
104
|
required: true,
|
|
102
105
|
type: String,
|
|
103
106
|
},
|
|
104
107
|
verb: {
|
|
105
|
-
description: "Widget-compatible mutation verb",
|
|
106
|
-
enum: ["created", "deleted", "updated"],
|
|
108
|
+
description: "Widget-compatible mutation verb, or viewed for an audited read",
|
|
109
|
+
enum: ["created", "deleted", "updated", "viewed"],
|
|
107
110
|
index: true,
|
|
108
111
|
required: true,
|
|
109
112
|
type: String,
|
|
@@ -3,6 +3,7 @@ import {timingSafeEqual} from "node:crypto";
|
|
|
3
3
|
import type {Request, Response} from "express";
|
|
4
4
|
|
|
5
5
|
import {APIError} from "../errors";
|
|
6
|
+
import {AUDIT_EVENT_SOURCES} from "./auditEventModel";
|
|
6
7
|
import {AUDIT_SECRET_HEADER} from "./cloudTasksEnqueue";
|
|
7
8
|
import type {AuditEventWrite} from "./record";
|
|
8
9
|
import {persistEnqueuedAuditEvent} from "./record";
|
|
@@ -30,10 +31,11 @@ const isAuditEventWrite = (value: unknown): value is AuditEventWrite => {
|
|
|
30
31
|
"arrayUpdate",
|
|
31
32
|
"create",
|
|
32
33
|
"delete",
|
|
34
|
+
"read",
|
|
33
35
|
"update",
|
|
34
36
|
];
|
|
35
|
-
const validSources: AuditEventWrite["source"][] =
|
|
36
|
-
const validVerbs: AuditEventWrite["verb"][] = ["created", "deleted", "updated"];
|
|
37
|
+
const validSources: readonly AuditEventWrite["source"][] = AUDIT_EVENT_SOURCES;
|
|
38
|
+
const validVerbs: AuditEventWrite["verb"][] = ["created", "deleted", "updated", "viewed"];
|
|
37
39
|
return (
|
|
38
40
|
typeof record.modelName === "string" &&
|
|
39
41
|
record.modelName.length > 0 &&
|
package/src/audit/record.test.ts
CHANGED
|
@@ -96,6 +96,21 @@ describe("audit record helpers", () => {
|
|
|
96
96
|
assert.equal(events[0]?.source, "admin");
|
|
97
97
|
});
|
|
98
98
|
|
|
99
|
+
it("maps the viewed verb to the read operation", async () => {
|
|
100
|
+
registerAuditApp();
|
|
101
|
+
const req = {user: {id: new mongoose.Types.ObjectId().toString()}} as express.Request;
|
|
102
|
+
await maybeRecordAdminAudit({
|
|
103
|
+
after: {_id: "food-1", name: "Soup"},
|
|
104
|
+
modelName: "Food",
|
|
105
|
+
req,
|
|
106
|
+
verb: "viewed",
|
|
107
|
+
});
|
|
108
|
+
const events = await mongoose.connection.collection("auditevents").find({}).toArray();
|
|
109
|
+
assert.equal(events.length, 1);
|
|
110
|
+
assert.equal(events[0]?.operation, "read");
|
|
111
|
+
assert.equal(events[0]?.verb, "viewed");
|
|
112
|
+
});
|
|
113
|
+
|
|
99
114
|
it("omits hidden fields from admin diffs", async () => {
|
|
100
115
|
registerAuditApp();
|
|
101
116
|
await maybeRecordAdminAudit({
|
package/src/audit/record.ts
CHANGED
|
@@ -3,7 +3,12 @@ import mongoose from "mongoose";
|
|
|
3
3
|
|
|
4
4
|
import {logger} from "../logger";
|
|
5
5
|
import {getOrgContext, ORGANIZATION_ID_HEADER} from "../orgs/orgContext";
|
|
6
|
-
import type {
|
|
6
|
+
import type {
|
|
7
|
+
AuditEventModel,
|
|
8
|
+
AuditEventOperation,
|
|
9
|
+
AuditEventSource,
|
|
10
|
+
AuditEventVerb,
|
|
11
|
+
} from "./auditEventModel";
|
|
7
12
|
import {changedFieldDiff, recordLabelFromDoc, toAuditPlain} from "./diff";
|
|
8
13
|
|
|
9
14
|
export interface ModelRouterAuditOptions {
|
|
@@ -28,7 +33,7 @@ export interface AuditEventWrite {
|
|
|
28
33
|
organizationId?: string;
|
|
29
34
|
recordId?: string;
|
|
30
35
|
recordLabel?: string;
|
|
31
|
-
source:
|
|
36
|
+
source: AuditEventSource;
|
|
32
37
|
verb: AuditEventVerb;
|
|
33
38
|
}
|
|
34
39
|
|
|
@@ -69,6 +74,9 @@ const operationFromVerb = (verb: AuditEventVerb): AuditEventOperation => {
|
|
|
69
74
|
if (verb === "deleted") {
|
|
70
75
|
return "delete";
|
|
71
76
|
}
|
|
77
|
+
if (verb === "viewed") {
|
|
78
|
+
return "read";
|
|
79
|
+
}
|
|
72
80
|
return "update";
|
|
73
81
|
};
|
|
74
82
|
|
package/src/authRecovery.test.ts
CHANGED
|
@@ -291,6 +291,29 @@ describe("password reset routes", () => {
|
|
|
291
291
|
.expect(200);
|
|
292
292
|
});
|
|
293
293
|
|
|
294
|
+
it("lets an account with no password set one in a pure JWT app", async () => {
|
|
295
|
+
// Without Better Auth the legacy routes are the only recovery path, so they keep working for
|
|
296
|
+
// an account that has no password yet (for example one an admin created).
|
|
297
|
+
await UserModel.create({email: "no-password@example.com"});
|
|
298
|
+
const stored = await UserModel.collection.findOne({email: "no-password@example.com"});
|
|
299
|
+
assert.isUndefined(stored?.hash);
|
|
300
|
+
|
|
301
|
+
await supertest(app)
|
|
302
|
+
.post("/auth/forgotPassword")
|
|
303
|
+
.send({email: "no-password@example.com"})
|
|
304
|
+
.expect(202);
|
|
305
|
+
assert.lengthOf(sentMail, 1);
|
|
306
|
+
const token = tokenFromResetUrl(sentMail[0]?.text ?? "");
|
|
307
|
+
await supertest(app)
|
|
308
|
+
.post("/auth/resetPassword")
|
|
309
|
+
.send({password: "first-password-123", token})
|
|
310
|
+
.expect(200);
|
|
311
|
+
await supertest(app)
|
|
312
|
+
.post("/auth/login")
|
|
313
|
+
.send({email: "no-password@example.com", password: "first-password-123"})
|
|
314
|
+
.expect(200);
|
|
315
|
+
});
|
|
316
|
+
|
|
294
317
|
it("returns 202 without issuing a token when publicAppUrl is missing", async () => {
|
|
295
318
|
const noUrlApp = new TerrenoApp({
|
|
296
319
|
authOptions: {
|
package/src/authRecovery.ts
CHANGED
|
@@ -206,6 +206,16 @@ export const sendEmailChangedNotice = async ({
|
|
|
206
206
|
}
|
|
207
207
|
};
|
|
208
208
|
|
|
209
|
+
/** Whether the app User has a legacy JWT (passport) password. */
|
|
210
|
+
const hasLegacyPassword = async (userModel: UserModel, user: User): Promise<boolean> => {
|
|
211
|
+
if (userModel.schema.path("hash") === undefined) {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
return Boolean(
|
|
215
|
+
await userModel.exists({_id: user._id, hash: {$exists: true, $ne: null}} as never)
|
|
216
|
+
);
|
|
217
|
+
};
|
|
218
|
+
|
|
209
219
|
const incrementTokenEpoch = (user: User): void => {
|
|
210
220
|
user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
|
|
211
221
|
};
|
|
@@ -256,12 +266,27 @@ export const addAuthRecoveryRoutes = (
|
|
|
256
266
|
if (authOptions) {
|
|
257
267
|
app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
|
|
258
268
|
}
|
|
269
|
+
// With Better Auth registered (TerrenoApp wires syncPasswordResetToBetterAuth after these routes
|
|
270
|
+
// are added, so read it per request), the legacy routes only replace an existing JWT password:
|
|
271
|
+
// POST /auth/login has no second factor, so an account without one (such as a social-only
|
|
272
|
+
// account) must not gain a way to sign in there. Pure JWT apps keep today's behaviour.
|
|
273
|
+
const canResetWithLegacyRoute = async (user: User): Promise<boolean> => {
|
|
274
|
+
if (!authOptions?.syncPasswordResetToBetterAuth) {
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
return hasLegacyPassword(userModel, user);
|
|
278
|
+
};
|
|
279
|
+
|
|
259
280
|
const forgotPassword = asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
260
281
|
const email = normalizeEmail(req.body?.email);
|
|
261
282
|
if (email) {
|
|
262
283
|
try {
|
|
263
284
|
const user = await findUserByEmail(userModel, email);
|
|
264
|
-
if (user) {
|
|
285
|
+
if (user && !(await canResetWithLegacyRoute(user))) {
|
|
286
|
+
logger.info(
|
|
287
|
+
"[auth] Skipped legacy password reset mail for an account without a JWT password"
|
|
288
|
+
);
|
|
289
|
+
} else if (user) {
|
|
265
290
|
if (!authOptions?.publicAppUrl) {
|
|
266
291
|
logger.error("[auth] publicAppUrl is required to send password reset mail");
|
|
267
292
|
} else {
|
|
@@ -307,6 +332,14 @@ export const addAuthRecoveryRoutes = (
|
|
|
307
332
|
if (isUserDisabled(user)) {
|
|
308
333
|
throw new APIError({status: 401, title: "User is disabled"});
|
|
309
334
|
}
|
|
335
|
+
if (!(await canResetWithLegacyRoute(user))) {
|
|
336
|
+
throw new APIError({
|
|
337
|
+
code: "legacy-password-reset-unavailable",
|
|
338
|
+
detail: "Request a new reset link from the sign-in page.",
|
|
339
|
+
status: 400,
|
|
340
|
+
title: "This account cannot reset its password here",
|
|
341
|
+
});
|
|
342
|
+
}
|
|
310
343
|
await changeUserPassword(user, password, {authOptions});
|
|
311
344
|
const tokens = await generateTokens(user, authOptions);
|
|
312
345
|
return res.json({
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The legacy JWT recovery routes (`POST /auth/forgotPassword`, `POST /auth/resetPassword`) on an
|
|
3
|
+
* app that also runs Better Auth. JWT login (`POST /auth/login`) has no second factor, so these
|
|
4
|
+
* routes must only replace an existing JWT password: an account without one (for example a
|
|
5
|
+
* social-only account) is not mailed a legacy link and a legacy token cannot give it a password.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
9
|
+
import mongoose from "mongoose";
|
|
10
|
+
import supertest from "supertest";
|
|
11
|
+
|
|
12
|
+
import {AuthToken} from "./authTokens";
|
|
13
|
+
import type {AuthRecoveryMail} from "./expressServer";
|
|
14
|
+
import {
|
|
15
|
+
access,
|
|
16
|
+
buildApp,
|
|
17
|
+
resetAccountSecurityState,
|
|
18
|
+
SecurityUser,
|
|
19
|
+
signUp,
|
|
20
|
+
} from "./tests/accountSecurityTestApp";
|
|
21
|
+
import {
|
|
22
|
+
betterAuthAccounts,
|
|
23
|
+
newStubIdentity,
|
|
24
|
+
stubGoogleIdTokenOptions,
|
|
25
|
+
} from "./tests/betterAuthStubs";
|
|
26
|
+
|
|
27
|
+
const NEW_PASSWORD = "legacy-reset-password-987";
|
|
28
|
+
const OLD_JWT_PASSWORD = "old-jwt-password-123";
|
|
29
|
+
|
|
30
|
+
const legacyTokenFrom = (mail: AuthRecoveryMail | undefined): string => {
|
|
31
|
+
const match = /resetPassword\?token=([0-9a-f]+)/i.exec(mail?.text ?? "");
|
|
32
|
+
return match?.[1] ?? "";
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** An app with Better Auth (Google ID-token sign-in) and legacy recovery mail captured. */
|
|
36
|
+
const buildRecoveryApp = (
|
|
37
|
+
identity = newStubIdentity("legacy-reset")
|
|
38
|
+
): {
|
|
39
|
+
app: ReturnType<typeof buildApp>["app"];
|
|
40
|
+
identity: typeof identity;
|
|
41
|
+
sent: AuthRecoveryMail[];
|
|
42
|
+
} => {
|
|
43
|
+
const sent: AuthRecoveryMail[] = [];
|
|
44
|
+
const {app} = buildApp({
|
|
45
|
+
authOptions: {
|
|
46
|
+
publicAppUrl: "https://app.example.com",
|
|
47
|
+
sendMail: async (message): Promise<void> => {
|
|
48
|
+
sent.push(message);
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
config: {
|
|
52
|
+
googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
|
|
53
|
+
options: stubGoogleIdTokenOptions(identity),
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
return {app, identity, sent};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const signInWithGoogle = async (
|
|
60
|
+
app: ReturnType<typeof buildApp>["app"],
|
|
61
|
+
email: string
|
|
62
|
+
): Promise<string> => {
|
|
63
|
+
await supertest(app)
|
|
64
|
+
.post("/api/auth/sign-in/social")
|
|
65
|
+
.send({idToken: {token: "stub-id-token"}, provider: "google"})
|
|
66
|
+
.expect(200);
|
|
67
|
+
const stored = await SecurityUser.collection.findOne({email});
|
|
68
|
+
return String(stored?._id);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
describe("legacy JWT password reset with Better Auth on", () => {
|
|
72
|
+
beforeAll(async () => {
|
|
73
|
+
await access.roles.seedDefaults();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
beforeEach(async () => {
|
|
77
|
+
await resetAccountSecurityState();
|
|
78
|
+
await AuthToken.deleteMany({});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("does not mail a legacy reset link to a social-only account", async () => {
|
|
82
|
+
const {app, identity, sent} = buildRecoveryApp();
|
|
83
|
+
await signInWithGoogle(app, identity.email);
|
|
84
|
+
|
|
85
|
+
const known = await supertest(app)
|
|
86
|
+
.post("/auth/forgotPassword")
|
|
87
|
+
.send({email: identity.email})
|
|
88
|
+
.expect(202);
|
|
89
|
+
const unknown = await supertest(app)
|
|
90
|
+
.post("/auth/forgotPassword")
|
|
91
|
+
.send({email: "nobody-legacy@example.com"})
|
|
92
|
+
.expect(202);
|
|
93
|
+
|
|
94
|
+
// The response does not say whether the account exists or which kind it is.
|
|
95
|
+
expect(known.body).toEqual(unknown.body);
|
|
96
|
+
expect(sent).toHaveLength(0);
|
|
97
|
+
expect(await AuthToken.countDocuments({type: "passwordReset"})).toBe(0);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("refuses a legacy reset token for a social-only account and sets no password", async () => {
|
|
101
|
+
const {app, identity} = buildRecoveryApp();
|
|
102
|
+
const userId = await signInWithGoogle(app, identity.email);
|
|
103
|
+
// A link mailed before this rule, or a token issued by app code.
|
|
104
|
+
const {token} = await AuthToken.issueFor({_id: userId}, "passwordReset");
|
|
105
|
+
|
|
106
|
+
const reset = await supertest(app)
|
|
107
|
+
.post("/auth/resetPassword")
|
|
108
|
+
.send({password: NEW_PASSWORD, token});
|
|
109
|
+
|
|
110
|
+
expect(reset.status).toBe(400);
|
|
111
|
+
expect(reset.body.data?.token).toBeUndefined();
|
|
112
|
+
const stored = await SecurityUser.collection.findOne({email: identity.email});
|
|
113
|
+
expect(stored?.hash).toBeUndefined();
|
|
114
|
+
expect(stored?.salt).toBeUndefined();
|
|
115
|
+
await supertest(app)
|
|
116
|
+
.post("/auth/login")
|
|
117
|
+
.send({email: identity.email, password: NEW_PASSWORD})
|
|
118
|
+
.expect(401);
|
|
119
|
+
// Better Auth stores account.userId as an ObjectId; the social account proves the filter matches.
|
|
120
|
+
const betterAuthUserId = new mongoose.Types.ObjectId(String(stored?.betterAuthId));
|
|
121
|
+
const accounts = await betterAuthAccounts().find({userId: betterAuthUserId}).toArray();
|
|
122
|
+
expect(accounts.map((account) => account.providerId)).toEqual(["google"]);
|
|
123
|
+
// The token is spent either way.
|
|
124
|
+
await supertest(app)
|
|
125
|
+
.post("/auth/resetPassword")
|
|
126
|
+
.send({password: NEW_PASSWORD, token})
|
|
127
|
+
.expect(400);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("refuses the legacy POST /resetPassword alias the same way", async () => {
|
|
131
|
+
const {app, identity} = buildRecoveryApp();
|
|
132
|
+
const userId = await signInWithGoogle(app, identity.email);
|
|
133
|
+
const {token} = await AuthToken.issueFor({_id: userId}, "passwordReset");
|
|
134
|
+
|
|
135
|
+
await supertest(app).post("/resetPassword").send({password: NEW_PASSWORD, token}).expect(400);
|
|
136
|
+
|
|
137
|
+
const stored = await SecurityUser.collection.findOne({email: identity.email});
|
|
138
|
+
expect(stored?.hash).toBeUndefined();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("still resets an account that already has a JWT password", async () => {
|
|
142
|
+
const {app, sent} = buildRecoveryApp();
|
|
143
|
+
const user = await signUp(app, "legacy-reset-dual");
|
|
144
|
+
const appUser = (await SecurityUser.findById(user.id)) as unknown as {
|
|
145
|
+
save: () => Promise<unknown>;
|
|
146
|
+
setPassword: (password: string) => Promise<unknown>;
|
|
147
|
+
};
|
|
148
|
+
await appUser.setPassword(OLD_JWT_PASSWORD);
|
|
149
|
+
await appUser.save();
|
|
150
|
+
|
|
151
|
+
await supertest(app).post("/auth/forgotPassword").send({email: user.email}).expect(202);
|
|
152
|
+
expect(sent).toHaveLength(1);
|
|
153
|
+
const token = legacyTokenFrom(sent[0]);
|
|
154
|
+
|
|
155
|
+
const reset = await supertest(app)
|
|
156
|
+
.post("/auth/resetPassword")
|
|
157
|
+
.send({password: NEW_PASSWORD, token})
|
|
158
|
+
.expect(200);
|
|
159
|
+
expect(typeof reset.body.data.token).toBe("string");
|
|
160
|
+
await supertest(app)
|
|
161
|
+
.post("/auth/login")
|
|
162
|
+
.send({email: user.email, password: NEW_PASSWORD})
|
|
163
|
+
.expect(200);
|
|
164
|
+
await supertest(app)
|
|
165
|
+
.post("/auth/login")
|
|
166
|
+
.send({email: user.email, password: OLD_JWT_PASSWORD})
|
|
167
|
+
.expect(401);
|
|
168
|
+
});
|
|
169
|
+
});
|
package/src/betterAuth.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type {BetterAuthOptions, BetterAuthPlugin} from "better-auth";
|
|
9
|
+
import type {SecurityMailTemplateId} from "./accountSecurity/securityNotifications";
|
|
10
|
+
import type {BetterAuthAccountLinkingMode} from "./betterAuthMethods";
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* Makes nested option objects optional too, so `options` can set one nested field (such as
|
|
@@ -29,6 +31,128 @@ export interface BetterAuthOAuthProvider {
|
|
|
29
31
|
clientSecret: string;
|
|
30
32
|
}
|
|
31
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Sign in with Apple configured with a pre-made client secret (a signed JWT you rotate yourself
|
|
36
|
+
* before it expires).
|
|
37
|
+
*/
|
|
38
|
+
export interface BetterAuthAppleSecretProvider extends BetterAuthOAuthProvider {
|
|
39
|
+
/** The iOS bundle id, used as the audience of native ID tokens. */
|
|
40
|
+
appBundleIdentifier?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Sign in with Apple configured with the Sign in with Apple key itself. Terreno signs the
|
|
45
|
+
* ES256 client-secret JWT when Better Auth is created; it is valid for 180 days, so restart
|
|
46
|
+
* (redeploy) the server at least that often.
|
|
47
|
+
*/
|
|
48
|
+
export interface BetterAuthAppleKeyProvider {
|
|
49
|
+
/** The iOS bundle id, used as the audience of native ID tokens. */
|
|
50
|
+
appBundleIdentifier?: string;
|
|
51
|
+
/** The Services ID (web) the sign-in uses. */
|
|
52
|
+
clientId: string;
|
|
53
|
+
/** The key id of the Sign in with Apple key. */
|
|
54
|
+
keyId: string;
|
|
55
|
+
/**
|
|
56
|
+
* The `.p8` key contents in PEM (PKCS#8) form. Escaped `\n` sequences, as env vars often carry
|
|
57
|
+
* them, are turned back into newlines.
|
|
58
|
+
*/
|
|
59
|
+
privateKey: string;
|
|
60
|
+
/** The Apple developer team id. */
|
|
61
|
+
teamId: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* How a sign-in with a new method relates to an existing account with the same email.
|
|
66
|
+
* Better Auth's `requireLocalEmailVerified` stays `true` in every mode.
|
|
67
|
+
*/
|
|
68
|
+
export interface BetterAuthAccountLinkingConfig {
|
|
69
|
+
/**
|
|
70
|
+
* - `verified-email`: a sign-in whose verified email matches an account whose own email is
|
|
71
|
+
* verified joins that account.
|
|
72
|
+
* - `explicit`: no linking at sign-in; a signed-in user links a method themselves.
|
|
73
|
+
* - `never`: no linking. A same-email sign-in with a new method is refused.
|
|
74
|
+
*/
|
|
75
|
+
mode: BetterAuthAccountLinkingMode;
|
|
76
|
+
/**
|
|
77
|
+
* Providers Better Auth trusts to own the email they report: their sign-ins link even without
|
|
78
|
+
* a verified-email claim, and Better Auth also skips the verified-email check for them on an
|
|
79
|
+
* explicit `/link-social` and its callback. List only providers that prove email ownership
|
|
80
|
+
* (such as Google for Gmail addresses); a provider that lets users set any email turns this
|
|
81
|
+
* into an account-takeover path.
|
|
82
|
+
*/
|
|
83
|
+
trustedProviders?: string[];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Time-based one-time-password two-factor authentication (Better Auth `twoFactor`).
|
|
88
|
+
*/
|
|
89
|
+
export interface BetterAuthTwoFactorConfig {
|
|
90
|
+
/** Issuer shown in authenticator apps, usually the app name. */
|
|
91
|
+
issuer: string;
|
|
92
|
+
/** How many backup codes enrollment makes (default 10) and how long each is (default 10). */
|
|
93
|
+
backupCodes?: {amount?: number; length?: number};
|
|
94
|
+
/** Days a "trust this device" choice skips the second factor. Defaults to 30. */
|
|
95
|
+
trustDeviceDays?: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* WebAuthn passkeys (`@better-auth/passkey`).
|
|
100
|
+
*/
|
|
101
|
+
export interface BetterAuthPasskeyConfig {
|
|
102
|
+
/** Relying party id: the registrable domain passkeys are bound to, such as `example.com`. */
|
|
103
|
+
rpID: string;
|
|
104
|
+
/** Relying party name shown by the authenticator. */
|
|
105
|
+
rpName: string;
|
|
106
|
+
/** Exact web origins allowed to use passkeys, such as `https://app.example.com`. */
|
|
107
|
+
origin: string[];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Whether new users can create accounts.
|
|
112
|
+
*/
|
|
113
|
+
export interface BetterAuthSignUpConfig {
|
|
114
|
+
/**
|
|
115
|
+
* - `open` (default): anyone can sign up.
|
|
116
|
+
* - `closed`: email sign-up is refused, and a social or generic OAuth sign-in for an unknown
|
|
117
|
+
* email fails with `signup_disabled`, even with `requestSignUp: true`.
|
|
118
|
+
*
|
|
119
|
+
* `closed` covers email and password, `socialProviders`, and every OAuth provider in Better
|
|
120
|
+
* Auth's provider list (including `genericOAuth` ones from `plugins`). Other sign-in plugins
|
|
121
|
+
* added through `plugins` (`magicLink`, `emailOTP`, `phoneNumber`, `anonymous`, ...) create
|
|
122
|
+
* users on their own terms and need their own `disableSignUp` (or equivalent) option. With
|
|
123
|
+
* `oauthProxy`, a preview's OAuth sign-in is finished by the production server, so it follows
|
|
124
|
+
* the production server's sign-up mode: give both the same `signUp.mode`.
|
|
125
|
+
*/
|
|
126
|
+
mode: "open" | "closed";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Several signed-in accounts on one device (Better Auth `multiSession`).
|
|
131
|
+
*/
|
|
132
|
+
export interface BetterAuthMultiSessionConfig {
|
|
133
|
+
/** Most accounts signed in at once on a device. Defaults to 5. */
|
|
134
|
+
maximumSessions?: number;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Lets preview deploys sign in through the stable deploy's registered OAuth callbacks
|
|
139
|
+
* (Better Auth `oAuthProxy`).
|
|
140
|
+
*/
|
|
141
|
+
export interface BetterAuthOAuthProxyConfig {
|
|
142
|
+
/** The base URL of the deploy that owns the registered callback URLs. */
|
|
143
|
+
productionURL: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Auth mail template ids: recovery links plus security notifications. */
|
|
147
|
+
export type BetterAuthMailTemplateId = "resetPassword" | "verifyEmail" | SecurityMailTemplateId;
|
|
148
|
+
|
|
149
|
+
/** A rendered (or overriding) auth mail template. */
|
|
150
|
+
export interface BetterAuthMailTemplate {
|
|
151
|
+
html?: string;
|
|
152
|
+
subject: string;
|
|
153
|
+
text?: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
32
156
|
/**
|
|
33
157
|
* Configuration options for Better Auth integration.
|
|
34
158
|
*/
|
|
@@ -44,9 +168,10 @@ export interface BetterAuthConfig {
|
|
|
44
168
|
googleOAuth?: BetterAuthOAuthProvider;
|
|
45
169
|
|
|
46
170
|
/**
|
|
47
|
-
* Apple OAuth provider configuration
|
|
171
|
+
* Apple OAuth provider configuration: either a pre-made client secret or the Sign in with
|
|
172
|
+
* Apple key, from which Terreno signs the client secret at startup.
|
|
48
173
|
*/
|
|
49
|
-
appleOAuth?:
|
|
174
|
+
appleOAuth?: BetterAuthAppleSecretProvider | BetterAuthAppleKeyProvider;
|
|
50
175
|
|
|
51
176
|
/**
|
|
52
177
|
* GitHub OAuth provider configuration.
|
|
@@ -97,7 +222,8 @@ export interface BetterAuthConfig {
|
|
|
97
222
|
|
|
98
223
|
/**
|
|
99
224
|
* Render reset/verify mail. Pass `@terreno/comms` `renderAuthMail` so JWT and
|
|
100
|
-
* Better Auth send identical templates.
|
|
225
|
+
* Better Auth send identical templates. Security notifications do not use it; see
|
|
226
|
+
* `AccountSecurityApp` `notifications.render`.
|
|
101
227
|
*/
|
|
102
228
|
renderAuthMail?: (options: {
|
|
103
229
|
publicAppUrl: string;
|
|
@@ -108,10 +234,11 @@ export interface BetterAuthConfig {
|
|
|
108
234
|
>;
|
|
109
235
|
}) => {html?: string; subject: string; text?: string};
|
|
110
236
|
|
|
111
|
-
/**
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
237
|
+
/**
|
|
238
|
+
* Optional per-app subject/text/html overrides for auth mail, including the `security*`
|
|
239
|
+
* notification templates `AccountSecurityApp` sends.
|
|
240
|
+
*/
|
|
241
|
+
authMailTemplates?: Partial<Record<BetterAuthMailTemplateId, BetterAuthMailTemplate>>;
|
|
115
242
|
|
|
116
243
|
/**
|
|
117
244
|
* Disable Better Auth's built-in IP limiter. Use only on throwaway in-process
|
|
@@ -131,7 +258,40 @@ export interface BetterAuthConfig {
|
|
|
131
258
|
options?: BetterAuthOptionsOverride;
|
|
132
259
|
|
|
133
260
|
/**
|
|
134
|
-
*
|
|
261
|
+
* Account linking policy for same-email sign-ins. Maps to Better Auth's
|
|
262
|
+
* `account.accountLinking`. Unset keeps Better Auth's default (`verified-email`).
|
|
263
|
+
*/
|
|
264
|
+
accountLinking?: BetterAuthAccountLinkingConfig;
|
|
265
|
+
|
|
266
|
+
/** Two-factor authentication. Unset by default. */
|
|
267
|
+
twoFactor?: BetterAuthTwoFactorConfig;
|
|
268
|
+
|
|
269
|
+
/** Passkey sign-in and registration. Unset by default. */
|
|
270
|
+
passkey?: BetterAuthPasskeyConfig;
|
|
271
|
+
|
|
272
|
+
/** Open or closed sign-up. Defaults to `{mode: "open"}`. */
|
|
273
|
+
signUp?: BetterAuthSignUpConfig;
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Remember the method each user last signed in with, in a cookie and on the Better Auth user
|
|
277
|
+
* (`lastLoginMethod`). Off by default.
|
|
278
|
+
*/
|
|
279
|
+
lastLoginMethod?: boolean;
|
|
280
|
+
|
|
281
|
+
/** Several signed-in accounts per device. Unset by default. */
|
|
282
|
+
multiSession?: BetterAuthMultiSessionConfig;
|
|
283
|
+
|
|
284
|
+
/** Proxy OAuth callbacks from the stable deploy to preview deploys. Unset by default. */
|
|
285
|
+
oauthProxy?: BetterAuthOAuthProxyConfig;
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Register the `@better-auth/expo` server plugin so native apps can sign in with social
|
|
289
|
+
* providers through the system browser. Off by default.
|
|
290
|
+
*/
|
|
291
|
+
nativeApps?: boolean;
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Better Auth plugins, appended after Terreno's `bearer()`, methods and feature plugins. Their endpoints mount
|
|
135
295
|
* under `basePath`. They are not added to the `auth.api` type.
|
|
136
296
|
*/
|
|
137
297
|
plugins?: BetterAuthPlugin[];
|
|
@@ -172,6 +332,32 @@ export interface BetterAuthConfig {
|
|
|
172
332
|
* The handoff is for bearer clients only. A handed-off callback redirect carries no session
|
|
173
333
|
* cookie for the API's origin, and verify drops every Set-Cookie it would send (the session
|
|
174
334
|
* cookies and any a plugin adds there), so a cookie-mode app gets no session from it.
|
|
335
|
+
*
|
|
336
|
+
* Linking a provider to the signed-in user takes two steps, because the link must also start
|
|
337
|
+
* from a top-level navigation and a bearer cannot ride along on one:
|
|
338
|
+
* - `POST {basePath}/oauth-handoff/link-intent`, authenticated with the bearer (or a cookie
|
|
339
|
+
* session), body `{provider, callbackURL, errorCallbackURL?}`, answers
|
|
340
|
+
* `{token, startURL}`. Both URLs must be absolute and on one of `webOrigins` that
|
|
341
|
+
* `trustedOrigins` allows; `callbackPaths` do not apply, since no token travels on a link's
|
|
342
|
+
* return (400 otherwise; Better Auth's own origin check answers 403 first for an untrusted
|
|
343
|
+
* one). It answers 403
|
|
344
|
+
* `LINKING_DISABLED` when account linking is off. The token is single-use, expires in three
|
|
345
|
+
* minutes, and is stored hashed in the verification table (`terreno-link-intent:<hash>`),
|
|
346
|
+
* bound to the caller's session.
|
|
347
|
+
* - `POST {basePath}/oauth-handoff/link-start`, a form post (`token=<token>`) the web app
|
|
348
|
+
* submits as a page navigation, so the token never appears in a URL. It answers 400 when
|
|
349
|
+
* `Sec-Fetch-Dest` is set and is not `document`, and 403 when `Origin` is missing, `null`, or
|
|
350
|
+
* not one of `webOrigins`; neither uses the token. The web origins must therefore not serve
|
|
351
|
+
* `Referrer-Policy: no-referrer` or `same-origin`, which make the form's `Origin` `null`. It then uses the token up (400 with no redirect
|
|
352
|
+
* when it is unknown, used, or expired), runs Better Auth's link flow as the token's
|
|
353
|
+
* session, sets only the OAuth state cookie, and redirects to the provider.
|
|
354
|
+
* A link that cannot start redirects to `errorCallbackURL` (or `callbackURL`) with
|
|
355
|
+
* `error=session_expired` (the session was revoked after the intent),
|
|
356
|
+
* `error=provider_not_found`, or `error=link_failed`.
|
|
357
|
+
*
|
|
358
|
+
* The provider callback links the account and redirects to `callbackURL` without a token,
|
|
359
|
+
* since no session is created. Better Auth's limiter allows three link intents and three link
|
|
360
|
+
* starts per ten seconds per IP.
|
|
175
361
|
*/
|
|
176
362
|
oauthHandoff?: BetterAuthOAuthHandoffConfig;
|
|
177
363
|
}
|