@terreno/api 57.16.1 → 57.17.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/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
|
|
2
|
+
import type {BetterAuthPlugin} from "better-auth";
|
|
2
3
|
import {assert} from "chai";
|
|
3
4
|
import express, {type Request, type Response} from "express";
|
|
5
|
+
import {DateTime} from "luxon";
|
|
4
6
|
import {MongoMemoryServer} from "mongodb-memory-server";
|
|
5
7
|
import mongoose, {Schema} from "mongoose";
|
|
6
8
|
import passportLocalMongoose from "passport-local-mongoose";
|
|
9
|
+
import supertest from "supertest";
|
|
7
10
|
import type {UserModel} from "./auth";
|
|
8
11
|
import type {BetterAuthConfig, BetterAuthSessionData, BetterAuthUser} from "./betterAuth";
|
|
9
12
|
import {
|
|
@@ -19,8 +22,10 @@ import {
|
|
|
19
22
|
type MongoClientLike,
|
|
20
23
|
mountBetterAuthRoutes,
|
|
21
24
|
readPasswordFromBetterAuthResetRequest,
|
|
25
|
+
resolveBetterAuthAppUser,
|
|
22
26
|
setupBetterAuthUserSync,
|
|
23
27
|
syncBetterAuthUser,
|
|
28
|
+
verifyBetterAuthCredentialPassword,
|
|
24
29
|
} from "./betterAuthSetup";
|
|
25
30
|
|
|
26
31
|
type SessionRequest = Request & {betterAuthSession?: BetterAuthSessionData};
|
|
@@ -42,6 +47,7 @@ let DualAuthUser: UserModel;
|
|
|
42
47
|
const testUserSchema = new Schema({
|
|
43
48
|
admin: {default: false, type: Boolean},
|
|
44
49
|
betterAuthId: {type: String},
|
|
50
|
+
disabled: {default: false, type: Boolean},
|
|
45
51
|
email: {required: true, type: String},
|
|
46
52
|
name: {type: String},
|
|
47
53
|
oauthProvider: {type: String},
|
|
@@ -51,6 +57,7 @@ const dualAuthUserSchema = new Schema({
|
|
|
51
57
|
admin: {default: false, type: Boolean},
|
|
52
58
|
betterAuthId: {type: String},
|
|
53
59
|
email: {required: true, type: String},
|
|
60
|
+
emailVerified: {type: Boolean},
|
|
54
61
|
name: {type: String},
|
|
55
62
|
tokenEpoch: {default: 0, type: Number},
|
|
56
63
|
});
|
|
@@ -288,7 +295,7 @@ describe("createBetterAuth", () => {
|
|
|
288
295
|
it("sends reset and verification mail through the injected renderer", async () => {
|
|
289
296
|
await setup;
|
|
290
297
|
const renderedCalls: Array<{templateId: string; token: string}> = [];
|
|
291
|
-
const sent: Array<{subject: string; text?: string; to: string}> = [];
|
|
298
|
+
const sent: Array<{sensitive?: boolean; subject: string; text?: string; to: string}> = [];
|
|
292
299
|
const hooks = createBetterAuthEmailHooks({
|
|
293
300
|
enabled: true,
|
|
294
301
|
publicAppUrl: "https://app.example.com",
|
|
@@ -297,7 +304,12 @@ describe("createBetterAuth", () => {
|
|
|
297
304
|
return {subject: templateId, text: `link-${token}`};
|
|
298
305
|
},
|
|
299
306
|
sendMail: async (message) => {
|
|
300
|
-
sent.push({
|
|
307
|
+
sent.push({
|
|
308
|
+
sensitive: message.sensitive,
|
|
309
|
+
subject: message.subject,
|
|
310
|
+
text: message.text,
|
|
311
|
+
to: message.to,
|
|
312
|
+
});
|
|
301
313
|
},
|
|
302
314
|
});
|
|
303
315
|
assert.isDefined(hooks);
|
|
@@ -316,8 +328,18 @@ describe("createBetterAuth", () => {
|
|
|
316
328
|
{templateId: "verifyEmail", token: "verify-token"},
|
|
317
329
|
]);
|
|
318
330
|
assert.deepEqual(sent, [
|
|
319
|
-
{
|
|
320
|
-
|
|
331
|
+
{
|
|
332
|
+
sensitive: true,
|
|
333
|
+
subject: "resetPassword",
|
|
334
|
+
text: "link-reset-token",
|
|
335
|
+
to: "reset@example.com",
|
|
336
|
+
},
|
|
337
|
+
{
|
|
338
|
+
sensitive: true,
|
|
339
|
+
subject: "verifyEmail",
|
|
340
|
+
text: "link-verify-token",
|
|
341
|
+
to: "verify@example.com",
|
|
342
|
+
},
|
|
321
343
|
]);
|
|
322
344
|
});
|
|
323
345
|
|
|
@@ -630,6 +652,43 @@ describe("createBetterAuth email and password-reset wiring", () => {
|
|
|
630
652
|
});
|
|
631
653
|
});
|
|
632
654
|
|
|
655
|
+
describe("verifyBetterAuthCredentialPassword", () => {
|
|
656
|
+
const makeAuth = (): BetterAuthInstance =>
|
|
657
|
+
createBetterAuth({
|
|
658
|
+
config: {
|
|
659
|
+
baseURL: "http://localhost:3000",
|
|
660
|
+
enabled: true,
|
|
661
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
662
|
+
},
|
|
663
|
+
mongoClient: getClient(),
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
it("verifies the right password and rejects a wrong one for a credential account", async () => {
|
|
667
|
+
await setup;
|
|
668
|
+
const auth = makeAuth();
|
|
669
|
+
const signedUp = await auth.api.signUpEmail({
|
|
670
|
+
body: {email: "verify-me@example.com", name: "Verify Me", password: "right-password-123"},
|
|
671
|
+
});
|
|
672
|
+
const betterAuthId = signedUp.user.id;
|
|
673
|
+
|
|
674
|
+
expect(
|
|
675
|
+
await verifyBetterAuthCredentialPassword(auth, {betterAuthId}, "right-password-123")
|
|
676
|
+
).toBe("verified");
|
|
677
|
+
expect(await verifyBetterAuthCredentialPassword(auth, {betterAuthId}, "wrong-password")).toBe(
|
|
678
|
+
"wrong"
|
|
679
|
+
);
|
|
680
|
+
});
|
|
681
|
+
|
|
682
|
+
it("returns no-password without a linked Better Auth user or credential account", async () => {
|
|
683
|
+
await setup;
|
|
684
|
+
const auth = makeAuth();
|
|
685
|
+
expect(await verifyBetterAuthCredentialPassword(auth, {}, "anything")).toBe("no-password");
|
|
686
|
+
expect(
|
|
687
|
+
await verifyBetterAuthCredentialPassword(auth, {betterAuthId: "missing-user"}, "anything")
|
|
688
|
+
).toBe("no-password");
|
|
689
|
+
});
|
|
690
|
+
});
|
|
691
|
+
|
|
633
692
|
describe("applyJwtPasswordResetToBetterAuth lookups", () => {
|
|
634
693
|
const makeAuth = (): BetterAuthInstance =>
|
|
635
694
|
createBetterAuth({
|
|
@@ -829,6 +888,83 @@ describe("syncBetterAuthUser", () => {
|
|
|
829
888
|
expect(result.name).toBe("Keep This Name");
|
|
830
889
|
});
|
|
831
890
|
|
|
891
|
+
it("refuses to link an existing user by an unverified email", async () => {
|
|
892
|
+
await setup;
|
|
893
|
+
await TestUser.create({admin: true, email: "test@example.com", name: "Existing Admin"});
|
|
894
|
+
|
|
895
|
+
const baUser = makeBetterAuthUser({emailVerified: false});
|
|
896
|
+
await expect(syncBetterAuthUser(TestUser, baUser)).rejects.toThrow(
|
|
897
|
+
"An account with this email already exists"
|
|
898
|
+
);
|
|
899
|
+
|
|
900
|
+
const saved = await TestUser.findOne({email: "test@example.com"}).lean();
|
|
901
|
+
assert.isUndefined(saved?.betterAuthId);
|
|
902
|
+
expect(await TestUser.countDocuments()).toBe(1);
|
|
903
|
+
});
|
|
904
|
+
|
|
905
|
+
it("refuses to relink a user that is bound to another Better Auth account", async () => {
|
|
906
|
+
await setup;
|
|
907
|
+
await TestUser.create({betterAuthId: "ba-other", email: "test@example.com"});
|
|
908
|
+
|
|
909
|
+
await expect(syncBetterAuthUser(TestUser, makeBetterAuthUser())).rejects.toThrow(
|
|
910
|
+
"An account with this email already exists"
|
|
911
|
+
);
|
|
912
|
+
|
|
913
|
+
const saved = await TestUser.findOne({email: "test@example.com"}).lean();
|
|
914
|
+
assert.equal(saved?.betterAuthId, "ba-other");
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
it("links an unverified email when the caller trusts it, as seeds do", async () => {
|
|
918
|
+
await setup;
|
|
919
|
+
await TestUser.create({betterAuthId: "ba-other", email: "test@example.com"});
|
|
920
|
+
|
|
921
|
+
const result = await syncBetterAuthUser(
|
|
922
|
+
TestUser,
|
|
923
|
+
makeBetterAuthUser({emailVerified: false}),
|
|
924
|
+
undefined,
|
|
925
|
+
{trustEmail: true}
|
|
926
|
+
);
|
|
927
|
+
|
|
928
|
+
assert.equal(result.betterAuthId, "ba-user-123");
|
|
929
|
+
});
|
|
930
|
+
|
|
931
|
+
it("revokes an unproven legacy password when a verified email links the row", async () => {
|
|
932
|
+
await setup;
|
|
933
|
+
const registrable = DualAuthUser as unknown as {
|
|
934
|
+
register: (doc: Record<string, unknown>, password: string) => Promise<unknown>;
|
|
935
|
+
};
|
|
936
|
+
await registrable.register({email: "test@example.com", name: "Legacy"}, "legacy-pass-123");
|
|
937
|
+
|
|
938
|
+
const result = await syncBetterAuthUser(DualAuthUser, makeBetterAuthUser());
|
|
939
|
+
assert.equal(result.betterAuthId, "ba-user-123");
|
|
940
|
+
|
|
941
|
+
const saved = await DualAuthUser.findOne({email: "test@example.com"})
|
|
942
|
+
.select("+hash +salt")
|
|
943
|
+
.lean();
|
|
944
|
+
assert.isUndefined((saved as {hash?: string}).hash);
|
|
945
|
+
assert.isUndefined((saved as {salt?: string}).salt);
|
|
946
|
+
assert.equal((saved as {tokenEpoch?: number}).tokenEpoch, 1);
|
|
947
|
+
});
|
|
948
|
+
|
|
949
|
+
it("keeps the legacy password when the row proved the same email", async () => {
|
|
950
|
+
await setup;
|
|
951
|
+
const registrable = DualAuthUser as unknown as {
|
|
952
|
+
register: (doc: Record<string, unknown>, password: string) => Promise<unknown>;
|
|
953
|
+
};
|
|
954
|
+
await registrable.register(
|
|
955
|
+
{email: "test@example.com", emailVerified: true, name: "Legacy"},
|
|
956
|
+
"legacy-pass-123"
|
|
957
|
+
);
|
|
958
|
+
|
|
959
|
+
await syncBetterAuthUser(DualAuthUser, makeBetterAuthUser());
|
|
960
|
+
|
|
961
|
+
const saved = await DualAuthUser.findOne({email: "test@example.com"})
|
|
962
|
+
.select("+hash +salt")
|
|
963
|
+
.lean();
|
|
964
|
+
assert.isString((saved as {hash?: string}).hash);
|
|
965
|
+
assert.equal((saved as {tokenEpoch?: number}).tokenEpoch, 0);
|
|
966
|
+
});
|
|
967
|
+
|
|
832
968
|
it("logs and rethrows when the lookup fails", async () => {
|
|
833
969
|
await setup;
|
|
834
970
|
const failure = new Error("lookup exploded");
|
|
@@ -1010,6 +1146,246 @@ describe("createBetterAuthSessionMiddleware", () => {
|
|
|
1010
1146
|
});
|
|
1011
1147
|
});
|
|
1012
1148
|
|
|
1149
|
+
describe("createBetterAuth options and plugins passthrough", () => {
|
|
1150
|
+
const config: BetterAuthConfig = {
|
|
1151
|
+
baseURL: "http://localhost:3000",
|
|
1152
|
+
enabled: true,
|
|
1153
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
1154
|
+
};
|
|
1155
|
+
|
|
1156
|
+
const signInRequest = (email: string): globalThis.Request =>
|
|
1157
|
+
new globalThis.Request("http://localhost:3000/api/auth/sign-in/email", {
|
|
1158
|
+
body: JSON.stringify({email, password: "password-123456"}),
|
|
1159
|
+
headers: {"Content-Type": "application/json"},
|
|
1160
|
+
method: "POST",
|
|
1161
|
+
});
|
|
1162
|
+
|
|
1163
|
+
it("applies requireEmailVerification from options and keeps Terreno's defaults", async () => {
|
|
1164
|
+
await setup;
|
|
1165
|
+
const auth = createBetterAuth({
|
|
1166
|
+
config: {...config, options: {emailAndPassword: {requireEmailVerification: true}}},
|
|
1167
|
+
mongoClient: getClient(),
|
|
1168
|
+
});
|
|
1169
|
+
const email = `unverified-${DateTime.now().toMillis()}@example.com`;
|
|
1170
|
+
await auth.api.signUpEmail({body: {email, name: "Unverified", password: "password-123456"}});
|
|
1171
|
+
|
|
1172
|
+
const response = await auth.handler(signInRequest(email));
|
|
1173
|
+
|
|
1174
|
+
expect(response.status).toBe(403);
|
|
1175
|
+
expect(auth.options.emailAndPassword?.enabled).toBe(true);
|
|
1176
|
+
expect(auth.options.emailAndPassword?.revokeSessionsOnPasswordReset).toBe(true);
|
|
1177
|
+
expect(auth.options.session?.cookieCache).toEqual({enabled: true, maxAge: 300});
|
|
1178
|
+
});
|
|
1179
|
+
|
|
1180
|
+
it("lets an explicit option override a Terreno default", async () => {
|
|
1181
|
+
await setup;
|
|
1182
|
+
const auth = createBetterAuth({
|
|
1183
|
+
config: {...config, options: {session: {cookieCache: {enabled: false}}}},
|
|
1184
|
+
mongoClient: getClient(),
|
|
1185
|
+
});
|
|
1186
|
+
|
|
1187
|
+
expect(auth.options.session?.cookieCache).toEqual({enabled: false, maxAge: 300});
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
it("replaces arrays instead of merging them by index", async () => {
|
|
1191
|
+
await setup;
|
|
1192
|
+
const auth = createBetterAuth({
|
|
1193
|
+
config: {
|
|
1194
|
+
...config,
|
|
1195
|
+
options: {trustedOrigins: ["https://a.example.com"]},
|
|
1196
|
+
trustedOrigins: ["https://b.example.com", "https://c.example.com"],
|
|
1197
|
+
},
|
|
1198
|
+
mongoClient: getClient(),
|
|
1199
|
+
});
|
|
1200
|
+
|
|
1201
|
+
expect(auth.options.trustedOrigins).toEqual(["https://a.example.com"]);
|
|
1202
|
+
});
|
|
1203
|
+
|
|
1204
|
+
it("appends plugins after bearer and leaves defaults alone without the new fields", async () => {
|
|
1205
|
+
await setup;
|
|
1206
|
+
const plugin = {id: "terreno-test"} satisfies BetterAuthPlugin;
|
|
1207
|
+
const withPlugin = createBetterAuth({
|
|
1208
|
+
config: {...config, plugins: [plugin]},
|
|
1209
|
+
mongoClient: getClient(),
|
|
1210
|
+
});
|
|
1211
|
+
const plain = createBetterAuth({config, mongoClient: getClient()});
|
|
1212
|
+
|
|
1213
|
+
expect(withPlugin.options.plugins?.map((p) => p.id)).toEqual(["bearer", "terreno-test"]);
|
|
1214
|
+
expect(plain.options.plugins?.map((p) => p.id)).toEqual(["bearer"]);
|
|
1215
|
+
expect(plain.options.trustedOrigins).toEqual([]);
|
|
1216
|
+
});
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
describe("resolveBetterAuthAppUser", () => {
|
|
1220
|
+
it("resolves concurrent first contacts for a new user to one app user", async () => {
|
|
1221
|
+
await setup;
|
|
1222
|
+
const betterAuthUser: BetterAuthUser = {
|
|
1223
|
+
createdAt: new Date(),
|
|
1224
|
+
email: "first-contact@example.com",
|
|
1225
|
+
emailVerified: false,
|
|
1226
|
+
id: new mongoose.Types.ObjectId().toString(),
|
|
1227
|
+
name: "First Contact",
|
|
1228
|
+
updatedAt: new Date(),
|
|
1229
|
+
};
|
|
1230
|
+
|
|
1231
|
+
const results = await Promise.all([
|
|
1232
|
+
resolveBetterAuthAppUser({betterAuthUser, userModel: TestUser}),
|
|
1233
|
+
resolveBetterAuthAppUser({betterAuthUser, userModel: TestUser}),
|
|
1234
|
+
resolveBetterAuthAppUser({betterAuthUser, userModel: TestUser}),
|
|
1235
|
+
]);
|
|
1236
|
+
|
|
1237
|
+
expect(new Set(results.map((result) => String(result.user.id))).size).toBe(1);
|
|
1238
|
+
expect(await TestUser.countDocuments({betterAuthId: betterAuthUser.id})).toBe(1);
|
|
1239
|
+
});
|
|
1240
|
+
|
|
1241
|
+
it("uses the user a concurrent request created when the insert hits a duplicate key", async () => {
|
|
1242
|
+
// Another request (a REST call racing the socket handshake) inserts the same user
|
|
1243
|
+
// between this lookup and this insert.
|
|
1244
|
+
let insertedByOtherRequest: Record<string, unknown> | null = null;
|
|
1245
|
+
class RacingUser {
|
|
1246
|
+
constructor(doc: Record<string, unknown>) {
|
|
1247
|
+
Object.assign(this, doc);
|
|
1248
|
+
}
|
|
1249
|
+
async save(): Promise<void> {
|
|
1250
|
+
insertedByOtherRequest = {...this, id: "app-user-1"};
|
|
1251
|
+
throw Object.assign(new Error("E11000 duplicate key error"), {code: 11000});
|
|
1252
|
+
}
|
|
1253
|
+
static async findOneOrNone(
|
|
1254
|
+
query: Record<string, unknown>
|
|
1255
|
+
): Promise<Record<string, unknown> | null> {
|
|
1256
|
+
return query.betterAuthId ? insertedByOtherRequest : null;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
const {isDisabled, user} = await resolveBetterAuthAppUser({
|
|
1261
|
+
betterAuthUser: {
|
|
1262
|
+
createdAt: new Date(),
|
|
1263
|
+
email: "raced@example.com",
|
|
1264
|
+
emailVerified: false,
|
|
1265
|
+
id: "ba-raced",
|
|
1266
|
+
name: "Raced",
|
|
1267
|
+
updatedAt: new Date(),
|
|
1268
|
+
},
|
|
1269
|
+
userModel: RacingUser as unknown as UserModel,
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1272
|
+
expect(user.id).toBe("app-user-1");
|
|
1273
|
+
expect(isDisabled).toBe(false);
|
|
1274
|
+
});
|
|
1275
|
+
});
|
|
1276
|
+
|
|
1277
|
+
describe("createBetterAuthSessionMiddleware with disabled users", () => {
|
|
1278
|
+
const config: BetterAuthConfig = {
|
|
1279
|
+
baseURL: "http://localhost:3000",
|
|
1280
|
+
enabled: true,
|
|
1281
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
1282
|
+
};
|
|
1283
|
+
|
|
1284
|
+
// A real bearer session for a Better Auth user linked to an app user.
|
|
1285
|
+
const signUpLinkedUser = async (
|
|
1286
|
+
auth: BetterAuthInstance,
|
|
1287
|
+
email: string,
|
|
1288
|
+
disabled: boolean
|
|
1289
|
+
): Promise<{token: string; betterAuthId: string}> => {
|
|
1290
|
+
const created = await auth.api.signUpEmail({
|
|
1291
|
+
body: {email, name: "Linked User", password: "password-123456"},
|
|
1292
|
+
});
|
|
1293
|
+
await TestUser.create({betterAuthId: created.user.id, disabled, email});
|
|
1294
|
+
return {betterAuthId: created.user.id, token: created.token as string};
|
|
1295
|
+
};
|
|
1296
|
+
|
|
1297
|
+
// Mounted in TerrenoApp's order: session middleware first, then Better Auth's routes,
|
|
1298
|
+
// then a route that requires an authenticated user.
|
|
1299
|
+
const buildApp = (auth: BetterAuthInstance): express.Application => {
|
|
1300
|
+
const app = express();
|
|
1301
|
+
app.use(createBetterAuthSessionMiddleware(auth, TestUser));
|
|
1302
|
+
mountBetterAuthRoutes(app, auth);
|
|
1303
|
+
app.get("/protected", (req, res) => {
|
|
1304
|
+
if (!req.user) {
|
|
1305
|
+
return res.status(401).json({status: 401, title: "Unauthorized"});
|
|
1306
|
+
}
|
|
1307
|
+
return res.json({id: req.user.id});
|
|
1308
|
+
});
|
|
1309
|
+
return app;
|
|
1310
|
+
};
|
|
1311
|
+
|
|
1312
|
+
it("does not authenticate a session that belongs to a disabled user", async () => {
|
|
1313
|
+
await setup;
|
|
1314
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
1315
|
+
const {token} = await signUpLinkedUser(auth, "disabled-session@example.com", true);
|
|
1316
|
+
|
|
1317
|
+
const res = await supertest(buildApp(auth))
|
|
1318
|
+
.get("/protected")
|
|
1319
|
+
.set("authorization", `Bearer ${token}`);
|
|
1320
|
+
|
|
1321
|
+
expect(res.status).toBe(401);
|
|
1322
|
+
});
|
|
1323
|
+
|
|
1324
|
+
it("stops authenticating once a user is disabled while their session is live", async () => {
|
|
1325
|
+
await setup;
|
|
1326
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
1327
|
+
const {betterAuthId, token} = await signUpLinkedUser(auth, "disabled-later@example.com", false);
|
|
1328
|
+
const app = buildApp(auth);
|
|
1329
|
+
|
|
1330
|
+
const before = await supertest(app).get("/protected").set("authorization", `Bearer ${token}`);
|
|
1331
|
+
expect(before.status).toBe(200);
|
|
1332
|
+
|
|
1333
|
+
await TestUser.updateOne({betterAuthId}, {disabled: true});
|
|
1334
|
+
|
|
1335
|
+
const after = await supertest(app).get("/protected").set("authorization", `Bearer ${token}`);
|
|
1336
|
+
expect(after.status).toBe(401);
|
|
1337
|
+
});
|
|
1338
|
+
|
|
1339
|
+
it("still lets a disabled user sign out", async () => {
|
|
1340
|
+
await setup;
|
|
1341
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
1342
|
+
const {token} = await signUpLinkedUser(auth, "disabled-signout@example.com", true);
|
|
1343
|
+
|
|
1344
|
+
const res = await supertest(buildApp(auth))
|
|
1345
|
+
.post("/api/auth/sign-out")
|
|
1346
|
+
.set("authorization", `Bearer ${token}`)
|
|
1347
|
+
.set("origin", "http://localhost:3000")
|
|
1348
|
+
.send({});
|
|
1349
|
+
|
|
1350
|
+
expect(res.status).toBe(200);
|
|
1351
|
+
});
|
|
1352
|
+
});
|
|
1353
|
+
|
|
1354
|
+
describe("createBetterAuthSessionMiddleware with an existing app user's email", () => {
|
|
1355
|
+
const config: BetterAuthConfig = {
|
|
1356
|
+
baseURL: "http://localhost:3000",
|
|
1357
|
+
enabled: true,
|
|
1358
|
+
secret: "test-secret-at-least-32-characters-long",
|
|
1359
|
+
};
|
|
1360
|
+
|
|
1361
|
+
it("does not resolve an unverified sign-up to the existing app user", async () => {
|
|
1362
|
+
await setup;
|
|
1363
|
+
const auth = createBetterAuth({config, mongoClient: getClient()});
|
|
1364
|
+
const existing = await TestUser.create({admin: true, email: "existing-admin@example.com"});
|
|
1365
|
+
const created = await auth.api.signUpEmail({
|
|
1366
|
+
body: {email: "existing-admin@example.com", name: "Someone", password: "password-123456"},
|
|
1367
|
+
});
|
|
1368
|
+
assert.isFalse(created.user.emailVerified);
|
|
1369
|
+
|
|
1370
|
+
const app = express();
|
|
1371
|
+
app.use(createBetterAuthSessionMiddleware(auth, TestUser));
|
|
1372
|
+
app.get("/protected", (req, res) => {
|
|
1373
|
+
if (!req.user) {
|
|
1374
|
+
return res.status(401).json({status: 401, title: "Unauthorized"});
|
|
1375
|
+
}
|
|
1376
|
+
return res.json({id: req.user.id});
|
|
1377
|
+
});
|
|
1378
|
+
|
|
1379
|
+
const res = await supertest(app)
|
|
1380
|
+
.get("/protected")
|
|
1381
|
+
.set("authorization", `Bearer ${created.token as string}`);
|
|
1382
|
+
|
|
1383
|
+
expect(res.status).toBe(401);
|
|
1384
|
+
const reloaded = await TestUser.findById(existing._id).lean();
|
|
1385
|
+
assert.isUndefined(reloaded?.betterAuthId);
|
|
1386
|
+
});
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1013
1389
|
describe("mountBetterAuthRoutes", () => {
|
|
1014
1390
|
it("mounts routes at the default path", async () => {
|
|
1015
1391
|
await setup;
|
|
@@ -1088,6 +1464,19 @@ describe("getMongoClientFromMongoose", () => {
|
|
|
1088
1464
|
expect(client).toBeDefined();
|
|
1089
1465
|
});
|
|
1090
1466
|
|
|
1467
|
+
it("returns the connection's database, not the connection string's default", () => {
|
|
1468
|
+
// A dbName passed to mongoose.connect only sets the connection name; the client's
|
|
1469
|
+
// default database still comes from the URI.
|
|
1470
|
+
const connection = mongoose.connection as unknown as {name: string};
|
|
1471
|
+
const originalName = connection.name;
|
|
1472
|
+
connection.name = "terreno-isolated-dbname-test";
|
|
1473
|
+
try {
|
|
1474
|
+
expect(getMongoClientFromMongoose().db().databaseName).toBe("terreno-isolated-dbname-test");
|
|
1475
|
+
} finally {
|
|
1476
|
+
connection.name = originalName;
|
|
1477
|
+
}
|
|
1478
|
+
});
|
|
1479
|
+
|
|
1091
1480
|
it("throws when the mongoose connection has no client", () => {
|
|
1092
1481
|
const connection = mongoose.connection as unknown as {client?: unknown};
|
|
1093
1482
|
const originalClient = connection.client;
|