@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
package/src/betterAuthApp.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
mountBetterAuthRoutes,
|
|
17
17
|
setupBetterAuthUserSync,
|
|
18
18
|
} from "./betterAuthSetup";
|
|
19
|
+
import {APIError} from "./errors";
|
|
19
20
|
import {logger} from "./logger";
|
|
20
21
|
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
21
22
|
|
|
@@ -27,8 +28,15 @@ import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
|
27
28
|
export interface BetterAuthProvider {
|
|
28
29
|
getAuth: () => BetterAuthInstance | undefined;
|
|
29
30
|
ensureAuth?: () => BetterAuthInstance;
|
|
31
|
+
/**
|
|
32
|
+
* Hands the provider the host app's user model when it was given none of its own. TerrenoApp
|
|
33
|
+
* calls it before anything creates the Better Auth instance.
|
|
34
|
+
*/
|
|
35
|
+
adoptUserModel?: (userModel: UserModel) => void;
|
|
30
36
|
markSessionMiddlewareMounted?: () => void;
|
|
31
37
|
getBetterAuthBasePath?: () => string;
|
|
38
|
+
/** The Terreno config the instance was built from (for `publicAppUrl` and similar). */
|
|
39
|
+
getBetterAuthConfig?: () => BetterAuthConfig;
|
|
32
40
|
}
|
|
33
41
|
|
|
34
42
|
/** Whether a registered plugin provides the app's Better Auth instance. */
|
|
@@ -77,6 +85,26 @@ export class BetterAuthApp implements TerrenoPlugin {
|
|
|
77
85
|
return this.auth;
|
|
78
86
|
}
|
|
79
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Uses `userModel` (TerrenoApp's) when this plugin was constructed without one. The app User
|
|
90
|
+
* guard and sync (`terreno-app-user-sync`) are installed when the Better Auth instance is
|
|
91
|
+
* created, so a user model that arrives after that would leave sign-ups unguarded while the
|
|
92
|
+
* session middleware still links app Users: that is refused at boot instead.
|
|
93
|
+
*/
|
|
94
|
+
adoptUserModel(userModel: UserModel): void {
|
|
95
|
+
if (this.options.userModel) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (this.auth) {
|
|
99
|
+
throw new APIError({
|
|
100
|
+
detail: "Pass userModel to BetterAuthApp, or let TerrenoApp build it first.",
|
|
101
|
+
status: 500,
|
|
102
|
+
title: "BetterAuthApp created Better Auth before it was given a userModel",
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
this.options = {...this.options, userModel};
|
|
106
|
+
}
|
|
107
|
+
|
|
80
108
|
markSessionMiddlewareMounted(): void {
|
|
81
109
|
this.sessionMiddlewareMounted = true;
|
|
82
110
|
}
|
|
@@ -96,6 +124,10 @@ export class BetterAuthApp implements TerrenoPlugin {
|
|
|
96
124
|
logger.info("Better Auth initialized via BetterAuthApp plugin");
|
|
97
125
|
}
|
|
98
126
|
|
|
127
|
+
getBetterAuthConfig(): BetterAuthConfig {
|
|
128
|
+
return this.options.config;
|
|
129
|
+
}
|
|
130
|
+
|
|
99
131
|
getBetterAuthBasePath(): string {
|
|
100
132
|
return this.options.config.basePath ?? "/api/auth";
|
|
101
133
|
}
|
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import {DateTime} from "luxon";
|
|
4
|
+
import mongoose from "mongoose";
|
|
5
|
+
import supertest from "supertest";
|
|
6
|
+
import type {BetterAuthConfig} from "./betterAuth";
|
|
7
|
+
import {AUTH_CHALLENGE_EMPTY, AUTH_CHALLENGE_HEADER} from "./betterAuthChallengeHeaders";
|
|
8
|
+
import {buildFeaturePlugins} from "./betterAuthFeatures";
|
|
9
|
+
import {
|
|
10
|
+
createBetterAuth,
|
|
11
|
+
getMongoClientFromMongoose,
|
|
12
|
+
mountBetterAuthRoutes,
|
|
13
|
+
} from "./betterAuthSetup";
|
|
14
|
+
import {
|
|
15
|
+
API_ORIGIN,
|
|
16
|
+
cookieHeaderFrom,
|
|
17
|
+
enrollTwoFactor,
|
|
18
|
+
PASSWORD,
|
|
19
|
+
SECRET,
|
|
20
|
+
setCookies,
|
|
21
|
+
totpCode,
|
|
22
|
+
totpSecretFromURI,
|
|
23
|
+
uniqueEmail,
|
|
24
|
+
} from "./tests/betterAuthStubs";
|
|
25
|
+
import {createSoftwareAuthenticator} from "./tests/softwareAuthenticator";
|
|
26
|
+
|
|
27
|
+
// Every request below is cookie-free, as a bearer-mode web client on another site sends it,
|
|
28
|
+
// unless a case says otherwise.
|
|
29
|
+
|
|
30
|
+
const RP_ID = "localhost";
|
|
31
|
+
const TWO_FACTOR_COOKIE = "better-auth.two_factor";
|
|
32
|
+
const TRUST_DEVICE_COOKIE = "better-auth.trust_device";
|
|
33
|
+
const PASSKEY_COOKIE = "better-auth.better-auth-passkey";
|
|
34
|
+
const SESSION_COOKIE = "better-auth.session_token";
|
|
35
|
+
const DONT_REMEMBER_COOKIE = "better-auth.dont_remember";
|
|
36
|
+
|
|
37
|
+
const buildApp = (overrides: Partial<BetterAuthConfig> = {}): express.Application => {
|
|
38
|
+
const config: BetterAuthConfig = {
|
|
39
|
+
baseURL: API_ORIGIN,
|
|
40
|
+
enabled: true,
|
|
41
|
+
passkey: {origin: [API_ORIGIN], rpID: RP_ID, rpName: "Terreno"},
|
|
42
|
+
secret: SECRET,
|
|
43
|
+
twoFactor: {issuer: "Terreno"},
|
|
44
|
+
...overrides,
|
|
45
|
+
};
|
|
46
|
+
const auth = createBetterAuth({config, mongoClient: getMongoClientFromMongoose()});
|
|
47
|
+
const app = express();
|
|
48
|
+
mountBetterAuthRoutes(app, auth, config.basePath);
|
|
49
|
+
return app;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const challengeOf = (res: supertest.Response): URLSearchParams =>
|
|
53
|
+
new URLSearchParams(String(res.headers[AUTH_CHALLENGE_HEADER.toLowerCase()] ?? ""));
|
|
54
|
+
|
|
55
|
+
const exposedHeaders = (res: supertest.Response): string[] =>
|
|
56
|
+
String(res.headers["access-control-expose-headers"] ?? "")
|
|
57
|
+
.split(",")
|
|
58
|
+
.map((header) => header.trim().toLowerCase());
|
|
59
|
+
|
|
60
|
+
/** Merges a response's challenge header into what the client holds, as rtk does. */
|
|
61
|
+
const mergeChallenge = (held: string, res: supertest.Response): string => {
|
|
62
|
+
const next = new URLSearchParams(held === AUTH_CHALLENGE_EMPTY ? "" : held);
|
|
63
|
+
for (const [name, value] of challengeOf(res)) {
|
|
64
|
+
if (value) {
|
|
65
|
+
next.set(name, value);
|
|
66
|
+
} else {
|
|
67
|
+
next.delete(name);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return next.size > 0 ? next.toString() : AUTH_CHALLENGE_EMPTY;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Whether a response's `set-auth-token` signs in. */
|
|
74
|
+
const isLiveToken = async (app: express.Application, res: supertest.Response): Promise<boolean> => {
|
|
75
|
+
const token = res.headers["set-auth-token"];
|
|
76
|
+
if (!token) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
const session = await supertest(app)
|
|
80
|
+
.get("/api/auth/get-session")
|
|
81
|
+
.set("authorization", `Bearer ${token}`);
|
|
82
|
+
return Boolean(session.body?.session);
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const signIn = (
|
|
86
|
+
app: express.Application,
|
|
87
|
+
email: string,
|
|
88
|
+
challenge: string = AUTH_CHALLENGE_EMPTY
|
|
89
|
+
): supertest.Test =>
|
|
90
|
+
supertest(app)
|
|
91
|
+
.post("/api/auth/sign-in/email")
|
|
92
|
+
.set("content-type", "application/json")
|
|
93
|
+
.set(AUTH_CHALLENGE_HEADER, challenge)
|
|
94
|
+
.send({email, password: PASSWORD});
|
|
95
|
+
|
|
96
|
+
const verifyTotp = (
|
|
97
|
+
app: express.Application,
|
|
98
|
+
challenge: string,
|
|
99
|
+
code: string,
|
|
100
|
+
trustDevice = false
|
|
101
|
+
): supertest.Test =>
|
|
102
|
+
supertest(app)
|
|
103
|
+
.post("/api/auth/two-factor/verify-totp")
|
|
104
|
+
.set("content-type", "application/json")
|
|
105
|
+
.set(AUTH_CHALLENGE_HEADER, challenge)
|
|
106
|
+
.send({code, trustDevice});
|
|
107
|
+
|
|
108
|
+
// Flips one character of the signed identifier, keeping the signature as it was.
|
|
109
|
+
const tamper = (challenge: string, name: string): string => {
|
|
110
|
+
const pairs = new URLSearchParams(challenge);
|
|
111
|
+
const value = pairs.get(name) ?? "";
|
|
112
|
+
pairs.set(name, `${value[0] === "a" ? "b" : "a"}${value.slice(1)}`);
|
|
113
|
+
return pairs.toString();
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
describe("cookie-free two-factor challenge", () => {
|
|
117
|
+
it("sign-in returns the two-factor challenge in the header, exposed to the page", async () => {
|
|
118
|
+
const app = buildApp();
|
|
119
|
+
const email = uniqueEmail("challenge-sign-in");
|
|
120
|
+
await enrollTwoFactor(app, email);
|
|
121
|
+
|
|
122
|
+
const res = await signIn(app, email);
|
|
123
|
+
|
|
124
|
+
expect(res.status).toBe(200);
|
|
125
|
+
expect(res.body.twoFactorRedirect).toBe(true);
|
|
126
|
+
expect(challengeOf(res).get(TWO_FACTOR_COOKIE)).toBeTruthy();
|
|
127
|
+
expect(Array.from(challengeOf(res).keys())).toEqual([TWO_FACTOR_COOKIE]);
|
|
128
|
+
expect(exposedHeaders(res)).toContain(AUTH_CHALLENGE_HEADER.toLowerCase());
|
|
129
|
+
// bearer()'s hook ran before two-factor deleted that session; its dead token is dropped.
|
|
130
|
+
expect(res.headers["set-auth-token"]).toBeUndefined();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("verify-totp succeeds with only the header and returns a bearer token", async () => {
|
|
134
|
+
const app = buildApp();
|
|
135
|
+
const email = uniqueEmail("challenge-verify");
|
|
136
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
137
|
+
const signInRes = await signIn(app, email);
|
|
138
|
+
const challenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, signInRes);
|
|
139
|
+
|
|
140
|
+
const verify = await verifyTotp(app, challenge, totpCode(secret));
|
|
141
|
+
|
|
142
|
+
expect(verify.status).toBe(200);
|
|
143
|
+
const token = verify.headers["set-auth-token"] as string;
|
|
144
|
+
expect(token).toBeTruthy();
|
|
145
|
+
// The spent challenge comes back empty, so the client forgets it.
|
|
146
|
+
expect(challengeOf(verify).get(TWO_FACTOR_COOKIE)).toBe("");
|
|
147
|
+
expect(exposedHeaders(verify)).toEqual(
|
|
148
|
+
expect.arrayContaining(["set-auth-token", AUTH_CHALLENGE_HEADER.toLowerCase()])
|
|
149
|
+
);
|
|
150
|
+
const session = await supertest(app)
|
|
151
|
+
.get("/api/auth/get-session")
|
|
152
|
+
.set("authorization", `Bearer ${token}`);
|
|
153
|
+
expect(session.body.user.email).toBe(email);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("refuses a tampered challenge with 401", async () => {
|
|
157
|
+
const app = buildApp();
|
|
158
|
+
const email = uniqueEmail("challenge-tamper");
|
|
159
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
160
|
+
const challenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, await signIn(app, email));
|
|
161
|
+
|
|
162
|
+
const verify = await verifyTotp(app, tamper(challenge, TWO_FACTOR_COOKIE), totpCode(secret));
|
|
163
|
+
|
|
164
|
+
expect(verify.status).toBe(401);
|
|
165
|
+
expect(await isLiveToken(app, verify)).toBe(false);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it("refuses verify-totp with no header and no cookie", async () => {
|
|
169
|
+
const app = buildApp();
|
|
170
|
+
const email = uniqueEmail("challenge-missing");
|
|
171
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
172
|
+
await signIn(app, email);
|
|
173
|
+
|
|
174
|
+
const verify = await supertest(app)
|
|
175
|
+
.post("/api/auth/two-factor/verify-totp")
|
|
176
|
+
.set("content-type", "application/json")
|
|
177
|
+
.send({code: totpCode(secret)});
|
|
178
|
+
|
|
179
|
+
expect(verify.status).toBe(401);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("lets a real cookie win over the header", async () => {
|
|
183
|
+
const app = buildApp();
|
|
184
|
+
const email = uniqueEmail("challenge-cookie-wins");
|
|
185
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
186
|
+
const signInRes = await signIn(app, email);
|
|
187
|
+
const challenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, signInRes);
|
|
188
|
+
|
|
189
|
+
const verify = await supertest(app)
|
|
190
|
+
.post("/api/auth/two-factor/verify-totp")
|
|
191
|
+
.set("content-type", "application/json")
|
|
192
|
+
.set("cookie", cookieHeaderFrom(signInRes))
|
|
193
|
+
.set(AUTH_CHALLENGE_HEADER, tamper(challenge, TWO_FACTOR_COOKIE))
|
|
194
|
+
.send({code: totpCode(secret)});
|
|
195
|
+
|
|
196
|
+
expect(verify.status).toBe(200);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("never sends the header to a client that did not ask for it", async () => {
|
|
200
|
+
const app = buildApp();
|
|
201
|
+
const email = uniqueEmail("challenge-cookie-client");
|
|
202
|
+
await enrollTwoFactor(app, email);
|
|
203
|
+
|
|
204
|
+
const res = await supertest(app)
|
|
205
|
+
.post("/api/auth/sign-in/email")
|
|
206
|
+
.set("content-type", "application/json")
|
|
207
|
+
.send({email, password: PASSWORD});
|
|
208
|
+
|
|
209
|
+
expect(res.body.twoFactorRedirect).toBe(true);
|
|
210
|
+
expect(setCookies(res).some((cookie) => cookie.startsWith(`${TWO_FACTOR_COOKIE}=`))).toBe(true);
|
|
211
|
+
expect(res.headers[AUTH_CHALLENGE_HEADER.toLowerCase()]).toBeUndefined();
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("never turns the header into a session cookie", async () => {
|
|
215
|
+
const app = buildApp();
|
|
216
|
+
const signUp = await supertest(app)
|
|
217
|
+
.post("/api/auth/sign-up/email")
|
|
218
|
+
.set("content-type", "application/json")
|
|
219
|
+
.send({email: uniqueEmail("challenge-no-session"), name: "Session", password: PASSWORD});
|
|
220
|
+
const signedSession = signUp.headers["set-auth-token"] as string;
|
|
221
|
+
const asBearer = await supertest(app)
|
|
222
|
+
.get("/api/auth/passkey/list-user-passkeys")
|
|
223
|
+
.set("authorization", `Bearer ${signedSession}`);
|
|
224
|
+
expect(asBearer.status).toBe(200);
|
|
225
|
+
|
|
226
|
+
const res = await supertest(app)
|
|
227
|
+
.get("/api/auth/passkey/list-user-passkeys")
|
|
228
|
+
.set(
|
|
229
|
+
AUTH_CHALLENGE_HEADER,
|
|
230
|
+
new URLSearchParams({[SESSION_COOKIE]: signedSession}).toString()
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
expect(res.status).toBe(401);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("keeps a rememberMe: false sign-in short-lived through the header", async () => {
|
|
237
|
+
const app = buildApp();
|
|
238
|
+
const email = uniqueEmail("challenge-dont-remember");
|
|
239
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
240
|
+
const signInRes = await supertest(app)
|
|
241
|
+
.post("/api/auth/sign-in/email")
|
|
242
|
+
.set("content-type", "application/json")
|
|
243
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY)
|
|
244
|
+
.send({email, password: PASSWORD, rememberMe: false});
|
|
245
|
+
const challenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, signInRes);
|
|
246
|
+
expect(Array.from(new URLSearchParams(challenge).keys()).sort()).toEqual([
|
|
247
|
+
DONT_REMEMBER_COOKIE,
|
|
248
|
+
TWO_FACTOR_COOKIE,
|
|
249
|
+
]);
|
|
250
|
+
|
|
251
|
+
const verify = await verifyTotp(app, challenge, totpCode(secret));
|
|
252
|
+
|
|
253
|
+
expect(verify.status).toBe(200);
|
|
254
|
+
// Read from the store: a bearer get-session carries no dont_remember cookie, so Better Auth
|
|
255
|
+
// would refresh the session to the full seven days.
|
|
256
|
+
const session = await mongoose.connection.db
|
|
257
|
+
?.collection("session")
|
|
258
|
+
.findOne({token: verify.body.token});
|
|
259
|
+
const expiresInHours = DateTime.fromJSDate(session?.expiresAt).diffNow("hours").as("hours");
|
|
260
|
+
// Better Auth's short session lasts one day; a remembered one lasts seven.
|
|
261
|
+
expect(expiresInHours).toBeGreaterThan(23);
|
|
262
|
+
expect(expiresInHours).toBeLessThanOrEqual(24);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it("carries dont_remember only with a two-factor challenge", async () => {
|
|
266
|
+
const app = buildApp();
|
|
267
|
+
const email = uniqueEmail("challenge-no-2fa");
|
|
268
|
+
const signUp = await supertest(app)
|
|
269
|
+
.post("/api/auth/sign-up/email")
|
|
270
|
+
.set("content-type", "application/json")
|
|
271
|
+
.send({email, name: "No 2FA", password: PASSWORD});
|
|
272
|
+
expect(signUp.status).toBe(200);
|
|
273
|
+
|
|
274
|
+
const res = await supertest(app)
|
|
275
|
+
.post("/api/auth/sign-in/email")
|
|
276
|
+
.set("content-type", "application/json")
|
|
277
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY)
|
|
278
|
+
.send({email, password: PASSWORD, rememberMe: false});
|
|
279
|
+
|
|
280
|
+
expect(res.status).toBe(200);
|
|
281
|
+
expect(res.headers[AUTH_CHALLENGE_HEADER.toLowerCase()]).toBeUndefined();
|
|
282
|
+
expect(await isLiveToken(app, res)).toBe(true);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("works under a custom basePath", async () => {
|
|
286
|
+
const app = buildApp({basePath: "/auth"});
|
|
287
|
+
const email = uniqueEmail("challenge-base-path");
|
|
288
|
+
const signUp = await supertest(app)
|
|
289
|
+
.post("/auth/sign-up/email")
|
|
290
|
+
.set("content-type", "application/json")
|
|
291
|
+
.send({email, name: "Base Path", password: PASSWORD});
|
|
292
|
+
expect(signUp.status).toBe(200);
|
|
293
|
+
const bearer = `Bearer ${signUp.body.token}`;
|
|
294
|
+
const enable = await supertest(app)
|
|
295
|
+
.post("/auth/two-factor/enable")
|
|
296
|
+
.set("authorization", bearer)
|
|
297
|
+
.set("content-type", "application/json")
|
|
298
|
+
.send({password: PASSWORD});
|
|
299
|
+
const secret = totpSecretFromURI(enable.body.totpURI);
|
|
300
|
+
const confirm = await supertest(app)
|
|
301
|
+
.post("/auth/two-factor/verify-totp")
|
|
302
|
+
.set("authorization", bearer)
|
|
303
|
+
.set("content-type", "application/json")
|
|
304
|
+
.send({code: totpCode(secret)});
|
|
305
|
+
expect(confirm.status).toBe(200);
|
|
306
|
+
const signInRes = await supertest(app)
|
|
307
|
+
.post("/auth/sign-in/email")
|
|
308
|
+
.set("content-type", "application/json")
|
|
309
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY)
|
|
310
|
+
.send({email, password: PASSWORD});
|
|
311
|
+
expect(signInRes.body.twoFactorRedirect).toBe(true);
|
|
312
|
+
|
|
313
|
+
const verify = await supertest(app)
|
|
314
|
+
.post("/auth/two-factor/verify-totp")
|
|
315
|
+
.set("content-type", "application/json")
|
|
316
|
+
.set(AUTH_CHALLENGE_HEADER, mergeChallenge(AUTH_CHALLENGE_EMPTY, signInRes))
|
|
317
|
+
.send({code: totpCode(secret)});
|
|
318
|
+
|
|
319
|
+
expect(verify.status).toBe(200);
|
|
320
|
+
expect(verify.headers["set-auth-token"]).toBeTruthy();
|
|
321
|
+
});
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
describe("cookie-free trusted device", () => {
|
|
325
|
+
it("a trusted device skips the challenge on the next sign-in when it sends the trust value", async () => {
|
|
326
|
+
const app = buildApp();
|
|
327
|
+
const email = uniqueEmail("challenge-trust");
|
|
328
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
329
|
+
let held = mergeChallenge(AUTH_CHALLENGE_EMPTY, await signIn(app, email));
|
|
330
|
+
const verify = await verifyTotp(app, held, totpCode(secret), true);
|
|
331
|
+
expect(verify.status).toBe(200);
|
|
332
|
+
held = mergeChallenge(held, verify);
|
|
333
|
+
expect(Array.from(new URLSearchParams(held).keys())).toEqual([TRUST_DEVICE_COOKIE]);
|
|
334
|
+
|
|
335
|
+
const trusted = await signIn(app, email, held);
|
|
336
|
+
|
|
337
|
+
expect(trusted.status).toBe(200);
|
|
338
|
+
expect(trusted.body.twoFactorRedirect).toBeUndefined();
|
|
339
|
+
expect(await isLiveToken(app, trusted)).toBe(true);
|
|
340
|
+
// Better Auth rotates the trust token on each use; the client keeps the new one.
|
|
341
|
+
const rotated = challengeOf(trusted).get(TRUST_DEVICE_COOKIE);
|
|
342
|
+
expect(rotated).toBeTruthy();
|
|
343
|
+
expect(rotated).not.toBe(new URLSearchParams(held).get(TRUST_DEVICE_COOKIE));
|
|
344
|
+
|
|
345
|
+
const untrusted = await signIn(app, email);
|
|
346
|
+
expect(untrusted.body.twoFactorRedirect).toBe(true);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it("asks for the second factor when the trust value is tampered", async () => {
|
|
350
|
+
const app = buildApp();
|
|
351
|
+
const email = uniqueEmail("challenge-trust-tamper");
|
|
352
|
+
const {secret} = await enrollTwoFactor(app, email);
|
|
353
|
+
let held = mergeChallenge(AUTH_CHALLENGE_EMPTY, await signIn(app, email));
|
|
354
|
+
held = mergeChallenge(held, await verifyTotp(app, held, totpCode(secret), true));
|
|
355
|
+
|
|
356
|
+
const res = await signIn(app, email, tamper(held, TRUST_DEVICE_COOKIE));
|
|
357
|
+
|
|
358
|
+
expect(res.body.twoFactorRedirect).toBe(true);
|
|
359
|
+
expect(res.headers["set-auth-token"]).toBeUndefined();
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
describe("cookie-free passkey ceremonies", () => {
|
|
364
|
+
it("registers a passkey and signs in with it using only the header and the bearer", async () => {
|
|
365
|
+
const app = buildApp();
|
|
366
|
+
const email = uniqueEmail("challenge-passkey");
|
|
367
|
+
const signUp = await supertest(app)
|
|
368
|
+
.post("/api/auth/sign-up/email")
|
|
369
|
+
.set("content-type", "application/json")
|
|
370
|
+
.send({email, name: "Passkey", password: PASSWORD});
|
|
371
|
+
expect(signUp.status).toBe(200);
|
|
372
|
+
const bearer = `Bearer ${signUp.headers["set-auth-token"]}`;
|
|
373
|
+
const authenticator = createSoftwareAuthenticator({origin: API_ORIGIN, rpID: RP_ID});
|
|
374
|
+
|
|
375
|
+
const registerOptions = await supertest(app)
|
|
376
|
+
.get("/api/auth/passkey/generate-register-options")
|
|
377
|
+
.set("authorization", bearer)
|
|
378
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY);
|
|
379
|
+
expect(registerOptions.status).toBe(200);
|
|
380
|
+
const registerChallenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, registerOptions);
|
|
381
|
+
expect(Array.from(new URLSearchParams(registerChallenge).keys())).toEqual([PASSKEY_COOKIE]);
|
|
382
|
+
|
|
383
|
+
// Needs the session (from the bearer) and the challenge (from the header) together.
|
|
384
|
+
const registered = await supertest(app)
|
|
385
|
+
.post("/api/auth/passkey/verify-registration")
|
|
386
|
+
.set("authorization", bearer)
|
|
387
|
+
.set("content-type", "application/json")
|
|
388
|
+
.set(AUTH_CHALLENGE_HEADER, registerChallenge)
|
|
389
|
+
.send({name: "Laptop", response: authenticator.register(registerOptions.body)});
|
|
390
|
+
expect(registered.status).toBe(200);
|
|
391
|
+
expect(registered.body.name).toBe("Laptop");
|
|
392
|
+
|
|
393
|
+
const authenticateOptions = await supertest(app)
|
|
394
|
+
.get("/api/auth/passkey/generate-authenticate-options")
|
|
395
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY);
|
|
396
|
+
expect(authenticateOptions.status).toBe(200);
|
|
397
|
+
const signInChallenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, authenticateOptions);
|
|
398
|
+
|
|
399
|
+
const signedIn = await supertest(app)
|
|
400
|
+
.post("/api/auth/passkey/verify-authentication")
|
|
401
|
+
.set("content-type", "application/json")
|
|
402
|
+
.set(AUTH_CHALLENGE_HEADER, signInChallenge)
|
|
403
|
+
.send({response: authenticator.authenticate(authenticateOptions.body)});
|
|
404
|
+
|
|
405
|
+
expect(signedIn.status).toBe(200);
|
|
406
|
+
expect(signedIn.body.user.email).toBe(email);
|
|
407
|
+
const token = signedIn.headers["set-auth-token"] as string;
|
|
408
|
+
expect(token).toBeTruthy();
|
|
409
|
+
const session = await supertest(app)
|
|
410
|
+
.get("/api/auth/get-session")
|
|
411
|
+
.set("authorization", `Bearer ${token}`);
|
|
412
|
+
expect(session.body.user.email).toBe(email);
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
it("refuses passkey sign-in without the challenge header", async () => {
|
|
416
|
+
const app = buildApp();
|
|
417
|
+
const authenticator = createSoftwareAuthenticator({origin: API_ORIGIN, rpID: RP_ID});
|
|
418
|
+
const options = await supertest(app).get("/api/auth/passkey/generate-authenticate-options");
|
|
419
|
+
|
|
420
|
+
const res = await supertest(app)
|
|
421
|
+
.post("/api/auth/passkey/verify-authentication")
|
|
422
|
+
.set("content-type", "application/json")
|
|
423
|
+
.send({response: authenticator.authenticate(options.body)});
|
|
424
|
+
|
|
425
|
+
expect(res.status).toBe(400);
|
|
426
|
+
expect(res.body.code).toBe("CHALLENGE_NOT_FOUND");
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it("refuses a tampered passkey challenge", async () => {
|
|
430
|
+
const app = buildApp();
|
|
431
|
+
const authenticator = createSoftwareAuthenticator({origin: API_ORIGIN, rpID: RP_ID});
|
|
432
|
+
const options = await supertest(app)
|
|
433
|
+
.get("/api/auth/passkey/generate-authenticate-options")
|
|
434
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY);
|
|
435
|
+
const challenge = mergeChallenge(AUTH_CHALLENGE_EMPTY, options);
|
|
436
|
+
|
|
437
|
+
const res = await supertest(app)
|
|
438
|
+
.post("/api/auth/passkey/verify-authentication")
|
|
439
|
+
.set("content-type", "application/json")
|
|
440
|
+
.set(AUTH_CHALLENGE_HEADER, tamper(challenge, PASSKEY_COOKIE))
|
|
441
|
+
.send({response: authenticator.authenticate(options.body)});
|
|
442
|
+
|
|
443
|
+
expect(res.status).toBe(400);
|
|
444
|
+
expect(res.body.code).toBe("CHALLENGE_NOT_FOUND");
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
describe("challenge headers plugin wiring", () => {
|
|
449
|
+
it("is added with two-factor alone and with passkeys alone", () => {
|
|
450
|
+
const ids = (config: Partial<BetterAuthConfig>): string[] =>
|
|
451
|
+
buildFeaturePlugins({enabled: true, ...config}).map((plugin) => plugin.id);
|
|
452
|
+
expect(ids({twoFactor: {issuer: "Terreno"}})).toEqual([
|
|
453
|
+
"two-factor",
|
|
454
|
+
"terreno-challenge-headers",
|
|
455
|
+
]);
|
|
456
|
+
expect(ids({passkey: {origin: [API_ORIGIN], rpID: RP_ID, rpName: "Terreno"}})).toEqual([
|
|
457
|
+
"passkey",
|
|
458
|
+
"terreno-challenge-headers",
|
|
459
|
+
]);
|
|
460
|
+
expect(ids({})).toEqual([]);
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it("adds the challenge header only when two-factor or passkeys are on", async () => {
|
|
464
|
+
const app = buildApp({passkey: undefined, twoFactor: undefined});
|
|
465
|
+
const email = uniqueEmail("challenge-off");
|
|
466
|
+
|
|
467
|
+
const res = await supertest(app)
|
|
468
|
+
.post("/api/auth/sign-up/email")
|
|
469
|
+
.set("content-type", "application/json")
|
|
470
|
+
.set(AUTH_CHALLENGE_HEADER, AUTH_CHALLENGE_EMPTY)
|
|
471
|
+
.send({email, name: "Off", password: PASSWORD});
|
|
472
|
+
|
|
473
|
+
expect(res.status).toBe(200);
|
|
474
|
+
expect(res.headers[AUTH_CHALLENGE_HEADER.toLowerCase()]).toBeUndefined();
|
|
475
|
+
});
|
|
476
|
+
});
|