@terreno/api 57.1.0 → 57.3.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/README.md +17 -7
- package/dist/actions.js +19 -7
- package/dist/adminTypes.d.ts +26 -0
- package/dist/api.d.ts +4 -0
- package/dist/api.js +12 -24
- package/dist/auth.d.ts +23 -10
- package/dist/auth.js +97 -32
- package/dist/authRecovery.d.ts +5 -0
- package/dist/authRecovery.js +350 -0
- package/dist/authTokens.d.ts +8 -0
- package/dist/authTokens.js +162 -0
- package/dist/betterAuth.d.ts +33 -0
- package/dist/betterAuthApp.d.ts +4 -0
- package/dist/betterAuthApp.js +26 -8
- package/dist/betterAuthSetup.d.ts +44 -2
- package/dist/betterAuthSetup.js +288 -18
- package/dist/collectionRegistry.d.ts +38 -0
- package/dist/collectionRegistry.js +72 -0
- package/dist/configurationApp.d.ts +11 -2
- package/dist/configurationApp.js +2 -4
- package/dist/docLoader.js +35 -6
- package/dist/expressServer.d.ts +26 -3
- package/dist/expressServer.js +79 -11
- package/dist/index.d.ts +16 -0
- package/dist/index.js +38 -2
- package/dist/mcp/auth.d.ts +1 -0
- package/dist/mcp/auth.js +47 -25
- package/dist/mcp/handlers.d.ts +1 -1
- package/dist/mcp/handlers.js +67 -233
- package/dist/mcp/query.d.ts +2 -2
- package/dist/mcp/registry.d.ts +1 -5
- package/dist/mcp/registry.js +31 -20
- package/dist/mcp/schemaGenerator.d.ts +2 -7
- package/dist/mcp/schemaGenerator.js +41 -116
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +1 -0
- package/dist/mcp/serviceTokens.d.ts +16 -0
- package/dist/mcp/serviceTokens.js +345 -0
- package/dist/mcp/types.d.ts +2 -2
- package/dist/models/mcpServiceToken.d.ts +3 -0
- package/dist/models/mcpServiceToken.js +208 -0
- package/dist/openApiBuilder.d.ts +5 -4
- package/dist/openApiBuilder.js +61 -8
- package/dist/openApiCompat.js +1 -1
- package/dist/openApiValidator.js +0 -2
- package/dist/plugins.d.ts +14 -1
- package/dist/plugins.js +17 -6
- package/dist/populate.d.ts +2 -2
- package/dist/populate.js +47 -42
- package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
- package/dist/rateLimit/applyTrustProxy.js +17 -0
- package/dist/rateLimit/createStore.d.ts +2 -0
- package/dist/rateLimit/createStore.js +28 -0
- package/dist/rateLimit/memoryStore.d.ts +2 -0
- package/dist/rateLimit/memoryStore.js +108 -0
- package/dist/rateLimit/middleware.d.ts +11 -0
- package/dist/rateLimit/middleware.js +110 -0
- package/dist/rateLimit/mongoStore.d.ts +3 -0
- package/dist/rateLimit/mongoStore.js +122 -0
- package/dist/rateLimit/policies.d.ts +14 -0
- package/dist/rateLimit/policies.js +151 -0
- package/dist/rateLimit/redisStore.d.ts +3 -0
- package/dist/rateLimit/redisStore.js +155 -0
- package/dist/rateLimit/types.d.ts +54 -0
- package/dist/rateLimit/types.js +9 -0
- package/dist/rbac/access.js +5 -1
- package/dist/rbac/assertAllowed.d.ts +9 -0
- package/dist/rbac/assertAllowed.js +182 -0
- package/dist/rbac/modelRouterAccess.d.ts +1 -0
- package/dist/rbac/modelRouterAccess.js +8 -4
- package/dist/rbac/permissionUtils.js +3 -2
- package/dist/rbac/resolve.js +5 -4
- package/dist/rbac/routes.js +15 -6
- package/dist/rbac/statements.d.ts +10 -0
- package/dist/rbac/statements.js +13 -2
- package/dist/realtime/deprecation.d.ts +12 -0
- package/dist/realtime/deprecation.js +32 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +10 -11
- package/dist/realtime/registry.d.ts +0 -31
- package/dist/realtime/registry.js +44 -31
- package/dist/realtime/socketAuth.d.ts +5 -5
- package/dist/realtime/socketAuth.js +11 -1
- package/dist/realtime/socketUser.d.ts +5 -1
- package/dist/realtime/types.d.ts +14 -4
- package/dist/schemaMetadata.d.ts +56 -0
- package/dist/schemaMetadata.js +513 -0
- package/dist/seedRunner.d.ts +88 -0
- package/dist/seedRunner.js +627 -0
- package/dist/sync/executors.d.ts +12 -2
- package/dist/sync/executors.js +8 -10
- package/dist/sync/loadHarness.js +28 -19
- package/dist/sync/models.js +26 -24
- package/dist/sync/mutationHandler.d.ts +9 -0
- package/dist/sync/mutationHandler.js +11 -6
- package/dist/sync/registrationSideEffects.d.ts +35 -0
- package/dist/sync/registrationSideEffects.js +151 -0
- package/dist/sync/registry.d.ts +2 -52
- package/dist/sync/registry.js +38 -187
- package/dist/sync/routes.js +3 -2
- package/dist/sync/scripts/compactTombstones.js +0 -2
- package/dist/sync/syncApp.d.ts +3 -3
- package/dist/sync/syncApp.js +4 -4
- package/dist/sync/syncBatch.js +3 -2
- package/dist/sync/syncSeqPlugin.d.ts +1 -1
- package/dist/sync/syncSeqPlugin.js +20 -16
- package/dist/terrenoApp.d.ts +19 -5
- package/dist/terrenoApp.js +66 -18
- package/dist/tests/models.d.ts +2 -0
- package/dist/tests/models.js +6 -0
- package/dist/types/authToken.d.ts +33 -0
- package/dist/types/authToken.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +41 -0
- package/dist/types/mcpServiceToken.js +2 -0
- package/dist/webhooks/headerValue.d.ts +2 -0
- package/dist/webhooks/headerValue.js +14 -0
- package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
- package/dist/webhooks/idempotency/memoryStore.js +65 -0
- package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
- package/dist/webhooks/idempotency/mongoStore.js +150 -0
- package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
- package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
- package/dist/webhooks/rawBody.d.ts +14 -0
- package/dist/webhooks/rawBody.js +22 -0
- package/dist/webhooks/timingSafeEqual.d.ts +4 -0
- package/dist/webhooks/timingSafeEqual.js +17 -0
- package/dist/webhooks/verifiers/hmac.d.ts +15 -0
- package/dist/webhooks/verifiers/hmac.js +49 -0
- package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
- package/dist/webhooks/verifiers/sendgrid.js +56 -0
- package/dist/webhooks/verifiers/stripe.d.ts +9 -0
- package/dist/webhooks/verifiers/stripe.js +99 -0
- package/dist/webhooks/verifiers/twilio.d.ts +9 -0
- package/dist/webhooks/verifiers/twilio.js +112 -0
- package/dist/webhooks/webhooksApp.d.ts +33 -0
- package/dist/webhooks/webhooksApp.js +195 -0
- package/package.json +5 -6
- package/src/__snapshots__/openApi.test.ts.snap +270 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
- package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
- package/src/actions.ts +20 -13
- package/src/adminModelRouter.test.ts +133 -0
- package/src/adminTypes.ts +23 -0
- package/src/api.arrayOperations.test.ts +43 -31
- package/src/api.hooks.test.ts +38 -29
- package/src/api.query.test.ts +31 -31
- package/src/api.test.ts +95 -96
- package/src/api.ts +16 -27
- package/src/auth.test.ts +107 -51
- package/src/auth.ts +98 -29
- package/src/authRecovery.test.ts +281 -0
- package/src/authRecovery.ts +279 -0
- package/src/authTokens.test.ts +94 -0
- package/src/authTokens.ts +118 -0
- package/src/authVerification.test.ts +293 -0
- package/src/betterAuth.ts +24 -0
- package/src/betterAuthApp.test.ts +1 -0
- package/src/betterAuthApp.ts +27 -9
- package/src/betterAuthSetup.test.ts +568 -38
- package/src/betterAuthSetup.ts +260 -5
- package/src/collectionRegistry.test.ts +165 -0
- package/src/collectionRegistry.ts +115 -0
- package/src/configurationApp.ts +13 -7
- package/src/docLoader.test.ts +45 -1
- package/src/docLoader.ts +37 -6
- package/src/express.d.ts +1 -0
- package/src/expressServer.test.ts +130 -66
- package/src/expressServer.ts +75 -19
- package/src/githubAuth.test.ts +60 -55
- package/src/index.ts +58 -0
- package/src/mcp/auth.test.ts +47 -0
- package/src/mcp/auth.ts +32 -11
- package/src/mcp/handlers.ts +45 -172
- package/src/mcp/integration.test.ts +59 -9
- package/src/mcp/query.ts +2 -4
- package/src/mcp/registry.ts +29 -20
- package/src/mcp/schemaGenerator.test.ts +8 -0
- package/src/mcp/schemaGenerator.ts +49 -131
- package/src/mcp/server.ts +2 -0
- package/src/mcp/serviceTokens.test.ts +330 -0
- package/src/mcp/serviceTokens.ts +307 -0
- package/src/mcp/toolGenerator.test.ts +1 -1
- package/src/mcp/types.ts +2 -6
- package/src/models/mcpServiceToken.test.ts +129 -0
- package/src/models/mcpServiceToken.ts +158 -0
- package/src/openApi.test.ts +80 -64
- package/src/openApiBuilder.test.ts +95 -7
- package/src/openApiBuilder.ts +46 -9
- package/src/openApiCompat.ts +1 -1
- package/src/openApiValidator.test.ts +49 -54
- package/src/openApiValidator.ts +1 -3
- package/src/plugins.test.ts +14 -0
- package/src/plugins.ts +34 -9
- package/src/populate.test.ts +34 -0
- package/src/populate.ts +40 -29
- package/src/rateLimit/applyTrustProxy.ts +17 -0
- package/src/rateLimit/createStore.ts +25 -0
- package/src/rateLimit/memoryStore.ts +40 -0
- package/src/rateLimit/middleware.ts +79 -0
- package/src/rateLimit/mongoStore.test.ts +80 -0
- package/src/rateLimit/mongoStore.ts +76 -0
- package/src/rateLimit/policies.ts +130 -0
- package/src/rateLimit/rateLimit.test.ts +328 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
- package/src/rateLimit/redisStore.test.ts +114 -0
- package/src/rateLimit/redisStore.ts +85 -0
- package/src/rateLimit/types.ts +64 -0
- package/src/rbac/access.ts +5 -1
- package/src/rbac/assertAllowed.test.ts +325 -0
- package/src/rbac/assertAllowed.ts +157 -0
- package/src/rbac/backfillAdmins.test.ts +124 -0
- package/src/rbac/fieldViews.test.ts +89 -0
- package/src/rbac/modelRouterAccess.test.ts +126 -0
- package/src/rbac/modelRouterAccess.ts +5 -2
- package/src/rbac/permissionUtils.ts +3 -2
- package/src/rbac/realtimeAccess.test.ts +109 -1
- package/src/rbac/resolve.ts +5 -4
- package/src/rbac/roleManager.test.ts +169 -0
- package/src/rbac/routes.test.ts +233 -0
- package/src/rbac/routes.ts +16 -6
- package/src/rbac/statements.test.ts +2 -0
- package/src/rbac/statements.ts +12 -1
- package/src/realtime/deprecation.test.ts +60 -0
- package/src/realtime/deprecation.ts +32 -0
- package/src/realtime/realtime.test.ts +8 -4
- package/src/realtime/realtimeApp.ts +10 -11
- package/src/realtime/realtimeAppSetup.test.ts +32 -5
- package/src/realtime/registry.ts +48 -42
- package/src/realtime/sessionRevalidation.test.ts +57 -44
- package/src/realtime/socketAuth.test.ts +75 -23
- package/src/realtime/socketAuth.ts +17 -6
- package/src/realtime/socketUser.ts +5 -3
- package/src/realtime/types.ts +14 -4
- package/src/schemaMetadata.test.ts +405 -0
- package/src/schemaMetadata.ts +593 -0
- package/src/scrubAdminFields.test.ts +105 -0
- package/src/seedRunner.test.ts +591 -0
- package/src/seedRunner.ts +464 -0
- package/src/sync/docMatchesMutationData.test.ts +16 -0
- package/src/sync/ensureSyncIndexes.test.ts +54 -15
- package/src/sync/executors.test.ts +40 -0
- package/src/sync/executors.ts +24 -12
- package/src/sync/integration.test.ts +15 -7
- package/src/sync/loadHarness.ts +28 -19
- package/src/sync/models.ts +32 -18
- package/src/sync/mutationHandler.test.ts +16 -16
- package/src/sync/mutationHandler.ts +9 -7
- package/src/sync/registrationSideEffects.test.ts +126 -0
- package/src/sync/registrationSideEffects.ts +131 -0
- package/src/sync/registry.ts +45 -171
- package/src/sync/routes.ts +3 -2
- package/src/sync/scripts/compactTombstones.ts +0 -2
- package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
- package/src/sync/sync.test.ts +25 -23
- package/src/sync/syncApp.ts +4 -4
- package/src/sync/syncBatch.ts +3 -2
- package/src/sync/syncFrontier.test.ts +17 -15
- package/src/sync/syncPhaseC.test.ts +54 -43
- package/src/sync/syncRoutes.test.ts +51 -36
- package/src/sync/syncSeqPlugin.ts +66 -44
- package/src/sync/syncSocket.test.ts +112 -81
- package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
- package/src/terrenoApp.ts +87 -15
- package/src/tests/models.ts +14 -1
- package/src/types/authToken.ts +43 -0
- package/src/types/mcpServiceToken.ts +54 -0
- package/src/webhooks/headerValue.test.ts +22 -0
- package/src/webhooks/headerValue.ts +12 -0
- package/src/webhooks/idempotency/memoryStore.ts +34 -0
- package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
- package/src/webhooks/idempotency/mongoStore.ts +83 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
- package/src/webhooks/rawBody.test.ts +74 -0
- package/src/webhooks/rawBody.ts +23 -0
- package/src/webhooks/timingSafeEqual.ts +16 -0
- package/src/webhooks/verifiers/hmac.test.ts +110 -0
- package/src/webhooks/verifiers/hmac.ts +54 -0
- package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
- package/src/webhooks/verifiers/sendgrid.ts +59 -0
- package/src/webhooks/verifiers/stripe.ts +67 -0
- package/src/webhooks/verifiers/twilio.ts +69 -0
- package/src/webhooks/webhooksApp.test.ts +221 -0
- package/src/webhooks/webhooksApp.ts +144 -0
package/src/auth.test.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
|
|
4
2
|
import {assert} from "chai";
|
|
5
3
|
import express from "express";
|
|
@@ -37,7 +35,7 @@ const decodeTokenPayload = <T extends Record<string, unknown>>(token: string): T
|
|
|
37
35
|
|
|
38
36
|
describe("auth tests", () => {
|
|
39
37
|
let app: express.Application;
|
|
40
|
-
let admin:
|
|
38
|
+
let admin: Awaited<ReturnType<typeof setupDb>>[number];
|
|
41
39
|
let contextEvents: Array<{
|
|
42
40
|
currentSessionId?: string;
|
|
43
41
|
requestId?: string;
|
|
@@ -148,7 +146,7 @@ describe("auth tests", () => {
|
|
|
148
146
|
app = new TerrenoApp({
|
|
149
147
|
configureApp: addRoutes,
|
|
150
148
|
skipListen: true,
|
|
151
|
-
userModel: UserModel as
|
|
149
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
152
150
|
}).build();
|
|
153
151
|
agent = supertest.agent(app);
|
|
154
152
|
});
|
|
@@ -212,7 +210,7 @@ describe("auth tests", () => {
|
|
|
212
210
|
const getRes = await agent.get("/food").expect(200);
|
|
213
211
|
|
|
214
212
|
expect(getRes.body.data).toHaveLength(4);
|
|
215
|
-
expect(getRes.body.data.find((f:
|
|
213
|
+
expect(getRes.body.data.find((f: Food) => f.name === "Peas")).toBeDefined();
|
|
216
214
|
|
|
217
215
|
const updateRes = await agent
|
|
218
216
|
.patch(`/food/${food._id}`)
|
|
@@ -391,7 +389,7 @@ describe("auth tests", () => {
|
|
|
391
389
|
const getRes = await agent.get("/food").expect(200);
|
|
392
390
|
|
|
393
391
|
expect(getRes.body.data).toHaveLength(4);
|
|
394
|
-
const food = getRes.body.data.find((f:
|
|
392
|
+
const food = getRes.body.data.find((f: Food) => f.name === "Apple");
|
|
395
393
|
expect(food).toBeDefined();
|
|
396
394
|
|
|
397
395
|
const updateRes = await agent
|
|
@@ -431,7 +429,7 @@ describe("auth tests", () => {
|
|
|
431
429
|
message: "Password or username is incorrect",
|
|
432
430
|
});
|
|
433
431
|
let user = await UserModel.findById(admin._id);
|
|
434
|
-
expect((user as
|
|
432
|
+
expect((user as unknown as {attempts: number} | null)?.attempts).toBe(1);
|
|
435
433
|
res = await agent
|
|
436
434
|
.post("/auth/login")
|
|
437
435
|
.send({email: "admin@example.com", password: "wrong"})
|
|
@@ -441,7 +439,7 @@ describe("auth tests", () => {
|
|
|
441
439
|
message: "Password or username is incorrect",
|
|
442
440
|
});
|
|
443
441
|
user = await UserModel.findById(admin._id);
|
|
444
|
-
expect((user as
|
|
442
|
+
expect((user as unknown as {attempts: number} | null)?.attempts).toBe(2);
|
|
445
443
|
res = await agent
|
|
446
444
|
.post("/auth/login")
|
|
447
445
|
.send({email: "admin@example.com", password: "wrong"})
|
|
@@ -451,7 +449,7 @@ describe("auth tests", () => {
|
|
|
451
449
|
message: "Account locked due to too many failed login attempts",
|
|
452
450
|
});
|
|
453
451
|
user = await UserModel.findById(admin._id);
|
|
454
|
-
expect((user as
|
|
452
|
+
expect((user as unknown as {attempts: number} | null)?.attempts).toBe(3);
|
|
455
453
|
|
|
456
454
|
// Logging in with correct password fails because account is locked
|
|
457
455
|
res = await agent
|
|
@@ -464,7 +462,7 @@ describe("auth tests", () => {
|
|
|
464
462
|
});
|
|
465
463
|
user = await UserModel.findById(admin._id);
|
|
466
464
|
// Not incremented
|
|
467
|
-
expect((user as
|
|
465
|
+
expect((user as unknown as {attempts: number} | null)?.attempts).toBe(3);
|
|
468
466
|
});
|
|
469
467
|
|
|
470
468
|
it("refresh token allows refresh of auth token", async () => {
|
|
@@ -538,8 +536,8 @@ describe("auth tests", () => {
|
|
|
538
536
|
|
|
539
537
|
describe("custom auth options", () => {
|
|
540
538
|
let app: express.Application;
|
|
541
|
-
let admin:
|
|
542
|
-
let notAdmin:
|
|
539
|
+
let admin: Awaited<ReturnType<typeof setupDb>>[number];
|
|
540
|
+
let notAdmin: Awaited<ReturnType<typeof setupDb>>[number];
|
|
543
541
|
|
|
544
542
|
beforeEach(async () => {
|
|
545
543
|
// Reset to real time - don't freeze time here as passport-local-mongoose
|
|
@@ -569,7 +567,7 @@ describe("custom auth options", () => {
|
|
|
569
567
|
}),
|
|
570
568
|
]);
|
|
571
569
|
app = getBaseServer();
|
|
572
|
-
addAuthRoutes(app, UserModel as
|
|
570
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel, {
|
|
573
571
|
// custom refresh token logic based on admin or non admin
|
|
574
572
|
generateTokenExpiration: (user?: {admin: boolean}) => {
|
|
575
573
|
if (user?.admin) {
|
|
@@ -578,8 +576,8 @@ describe("custom auth options", () => {
|
|
|
578
576
|
return "365d";
|
|
579
577
|
},
|
|
580
578
|
});
|
|
581
|
-
setupAuth(app, UserModel as
|
|
582
|
-
addMeRoutes(app, UserModel as
|
|
579
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
580
|
+
addMeRoutes(app, UserModel as unknown as AuthUserModel);
|
|
583
581
|
app.use(
|
|
584
582
|
"/food",
|
|
585
583
|
modelRouter(FoodModel, {
|
|
@@ -734,29 +732,29 @@ describe("generateTokens edge cases", () => {
|
|
|
734
732
|
});
|
|
735
733
|
|
|
736
734
|
it("includes custom payload from generateJWTPayload option", async () => {
|
|
737
|
-
const jwtLib = await import("jsonwebtoken");
|
|
738
|
-
|
|
739
735
|
const user = {_id: "user-123"};
|
|
740
736
|
const result = await generateTokens(user, {
|
|
741
737
|
generateJWTPayload: (u) => ({customField: "customValue", userId: u._id}),
|
|
742
738
|
});
|
|
743
739
|
|
|
744
740
|
expect(result.token).toBeDefined();
|
|
745
|
-
const decoded =
|
|
741
|
+
const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
|
|
742
|
+
result.token as string
|
|
743
|
+
);
|
|
746
744
|
expect(decoded.customField).toBe("customValue");
|
|
747
745
|
expect(decoded.id).toBe("user-123");
|
|
748
746
|
});
|
|
749
747
|
|
|
750
748
|
it("uses custom token expiration from generateTokenExpiration option", async () => {
|
|
751
|
-
const jwtLib = await import("jsonwebtoken");
|
|
752
|
-
|
|
753
749
|
const user = {_id: "user-123"};
|
|
754
750
|
const result = await generateTokens(user, {
|
|
755
751
|
generateTokenExpiration: () => "1h",
|
|
756
752
|
});
|
|
757
753
|
|
|
758
754
|
expect(result.token).toBeDefined();
|
|
759
|
-
const decoded =
|
|
755
|
+
const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
|
|
756
|
+
result.token as string
|
|
757
|
+
);
|
|
760
758
|
// Check that exp is roughly 1 hour from now (within 5 seconds tolerance)
|
|
761
759
|
const expectedExp = Math.floor(Date.now() / 1000) + 3600;
|
|
762
760
|
expect(decoded.exp).toBeGreaterThan(expectedExp - 5);
|
|
@@ -764,15 +762,15 @@ describe("generateTokens edge cases", () => {
|
|
|
764
762
|
});
|
|
765
763
|
|
|
766
764
|
it("uses custom refresh token expiration from generateRefreshTokenExpiration option", async () => {
|
|
767
|
-
const jwtLib = await import("jsonwebtoken");
|
|
768
|
-
|
|
769
765
|
const user = {_id: "user-123"};
|
|
770
766
|
const result = await generateTokens(user, {
|
|
771
767
|
generateRefreshTokenExpiration: () => "7d",
|
|
772
768
|
});
|
|
773
769
|
|
|
774
770
|
expect(result.refreshToken).toBeDefined();
|
|
775
|
-
const decoded =
|
|
771
|
+
const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
|
|
772
|
+
result.refreshToken as string
|
|
773
|
+
);
|
|
776
774
|
// Check that exp is roughly 7 days from now
|
|
777
775
|
const expectedExp = Math.floor(Date.now() / 1000) + 7 * 24 * 3600;
|
|
778
776
|
expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
|
|
@@ -792,20 +790,22 @@ describe("generateTokens edge cases", () => {
|
|
|
792
790
|
});
|
|
793
791
|
|
|
794
792
|
it("uses TOKEN_EXPIRES_IN from env when valid", async () => {
|
|
795
|
-
const jwtLib = await import("jsonwebtoken");
|
|
796
793
|
process.env.TOKEN_EXPIRES_IN = "2h";
|
|
797
794
|
const result = await generateTokens({_id: "user-123"});
|
|
798
|
-
const decoded =
|
|
795
|
+
const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
|
|
796
|
+
result.token as string
|
|
797
|
+
);
|
|
799
798
|
const expectedExp = Math.floor(Date.now() / 1000) + 2 * 3600;
|
|
800
799
|
expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
|
|
801
800
|
expect(decoded.exp).toBeLessThan(expectedExp + 10);
|
|
802
801
|
});
|
|
803
802
|
|
|
804
803
|
it("uses REFRESH_TOKEN_EXPIRES_IN from env when valid", async () => {
|
|
805
|
-
const jwtLib = await import("jsonwebtoken");
|
|
806
804
|
process.env.REFRESH_TOKEN_EXPIRES_IN = "1h";
|
|
807
805
|
const result = await generateTokens({_id: "user-123"});
|
|
808
|
-
const decoded =
|
|
806
|
+
const decoded = decodeTokenPayload<{customField?: string; exp: number; id?: string}>(
|
|
807
|
+
result.refreshToken as string
|
|
808
|
+
);
|
|
809
809
|
const expectedExp = Math.floor(Date.now() / 1000) + 3600;
|
|
810
810
|
expect(decoded.exp).toBeGreaterThan(expectedExp - 10);
|
|
811
811
|
expect(decoded.exp).toBeLessThan(expectedExp + 10);
|
|
@@ -904,7 +904,7 @@ describe("addAuthRoutes /refresh_token error paths", () => {
|
|
|
904
904
|
const [adminUser] = await setupDb();
|
|
905
905
|
const jwtLib = (await import("jsonwebtoken")).default;
|
|
906
906
|
const validToken = jwtLib.sign(
|
|
907
|
-
{id:
|
|
907
|
+
{id: adminUser._id.toString()},
|
|
908
908
|
process.env.REFRESH_TOKEN_SECRET as string
|
|
909
909
|
);
|
|
910
910
|
const res = await agent
|
|
@@ -926,7 +926,7 @@ describe("addMeRoutes edge cases", () => {
|
|
|
926
926
|
app = new TerrenoApp({
|
|
927
927
|
configureApp: () => {},
|
|
928
928
|
skipListen: true,
|
|
929
|
-
userModel: UserModel as
|
|
929
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
930
930
|
}).build();
|
|
931
931
|
agent = supertest.agent(app);
|
|
932
932
|
});
|
|
@@ -946,13 +946,11 @@ describe("addMeRoutes edge cases", () => {
|
|
|
946
946
|
it("GET /auth/me returns 404 when user is deleted after auth", async () => {
|
|
947
947
|
const [_admin, notAdmin] = await setupDb();
|
|
948
948
|
const jwtLib = (await import("jsonwebtoken")).default;
|
|
949
|
-
const token = jwtLib.sign(
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
{issuer: process.env.TOKEN_ISSUER}
|
|
953
|
-
);
|
|
949
|
+
const token = jwtLib.sign({id: notAdmin._id.toString()}, process.env.TOKEN_SECRET as string, {
|
|
950
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
951
|
+
});
|
|
954
952
|
// Delete the user so findById returns null
|
|
955
|
-
await UserModel.deleteOne({_id:
|
|
953
|
+
await UserModel.deleteOne({_id: notAdmin._id});
|
|
956
954
|
const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
|
|
957
955
|
// Either 404 (user not found in /me handler) or 401 (auth middleware rejects)
|
|
958
956
|
expect([401, 404]).toContain(res.status);
|
|
@@ -998,7 +996,7 @@ describe("privileged user fields", () => {
|
|
|
998
996
|
app = new TerrenoApp({
|
|
999
997
|
configureApp: () => {},
|
|
1000
998
|
skipListen: true,
|
|
1001
|
-
userModel: UserModel as
|
|
999
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1002
1000
|
}).build();
|
|
1003
1001
|
agent = supertest.agent(app);
|
|
1004
1002
|
});
|
|
@@ -1007,14 +1005,16 @@ describe("privileged user fields", () => {
|
|
|
1007
1005
|
setSystemTime();
|
|
1008
1006
|
});
|
|
1009
1007
|
|
|
1010
|
-
it("drops admin, roles, and
|
|
1008
|
+
it("drops admin, roles, organizationIds, emailVerified, and tokenEpoch, keeping other fields", () => {
|
|
1011
1009
|
const sanitized = stripPrivilegedUserFields(
|
|
1012
1010
|
{
|
|
1013
1011
|
admin: true,
|
|
1014
1012
|
age: 42,
|
|
1013
|
+
emailVerified: true,
|
|
1015
1014
|
name: "Someone",
|
|
1016
1015
|
organizationIds: ["other-tenant"],
|
|
1017
1016
|
roles: ["superadmin"],
|
|
1017
|
+
tokenEpoch: 99,
|
|
1018
1018
|
},
|
|
1019
1019
|
"test"
|
|
1020
1020
|
);
|
|
@@ -1026,8 +1026,14 @@ describe("privileged user fields", () => {
|
|
|
1026
1026
|
expect(stripPrivilegedUserFields({name: "Someone"}, "test")).toEqual({name: "Someone"});
|
|
1027
1027
|
});
|
|
1028
1028
|
|
|
1029
|
-
it("lists admin, roles, and
|
|
1030
|
-
expect([...PRIVILEGED_USER_FIELDS]).toEqual([
|
|
1029
|
+
it("lists admin, roles, organizationIds, emailVerified, and tokenEpoch as privileged", () => {
|
|
1030
|
+
expect([...PRIVILEGED_USER_FIELDS]).toEqual([
|
|
1031
|
+
"admin",
|
|
1032
|
+
"roles",
|
|
1033
|
+
"organizationIds",
|
|
1034
|
+
"emailVerified",
|
|
1035
|
+
"tokenEpoch",
|
|
1036
|
+
]);
|
|
1031
1037
|
});
|
|
1032
1038
|
|
|
1033
1039
|
it("omits privileged User fields from ordinary RBAC modelRouter writes", () => {
|
|
@@ -1071,14 +1077,18 @@ describe("privileged user fields", () => {
|
|
|
1071
1077
|
.send({
|
|
1072
1078
|
admin: true,
|
|
1073
1079
|
email: "escalate@example.com",
|
|
1080
|
+
emailVerified: true,
|
|
1074
1081
|
organizationIds: ["other-tenant"],
|
|
1075
1082
|
password: "Password123!",
|
|
1083
|
+
tokenEpoch: 99,
|
|
1076
1084
|
})
|
|
1077
1085
|
.expect(200);
|
|
1078
1086
|
|
|
1079
1087
|
const created = await UserModel.findOne({email: "escalate@example.com"});
|
|
1080
1088
|
expect(created).toBeTruthy();
|
|
1081
1089
|
expect((created as unknown as {admin?: boolean})?.admin).toBe(false);
|
|
1090
|
+
expect((created as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
|
|
1091
|
+
expect((created as unknown as {tokenEpoch?: number})?.tokenEpoch ?? 0).toBe(0);
|
|
1082
1092
|
expect(
|
|
1083
1093
|
(created as unknown as {organizationIds?: string[]})?.organizationIds ?? []
|
|
1084
1094
|
).not.toContain("other-tenant");
|
|
@@ -1107,16 +1117,62 @@ describe("privileged user fields", () => {
|
|
|
1107
1117
|
await agent
|
|
1108
1118
|
.patch("/auth/me")
|
|
1109
1119
|
.set("authorization", `Bearer ${token}`)
|
|
1110
|
-
.send({
|
|
1120
|
+
.send({
|
|
1121
|
+
admin: true,
|
|
1122
|
+
emailVerified: true,
|
|
1123
|
+
name: "Renamed",
|
|
1124
|
+
organizationIds: ["other-tenant"],
|
|
1125
|
+
tokenEpoch: 99,
|
|
1126
|
+
})
|
|
1111
1127
|
.expect(200);
|
|
1112
1128
|
|
|
1113
1129
|
const reloaded = await UserModel.findById(notAdminId);
|
|
1114
1130
|
expect((reloaded as unknown as {admin?: boolean})?.admin).toBe(false);
|
|
1131
|
+
expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
|
|
1132
|
+
expect((reloaded as unknown as {tokenEpoch?: number})?.tokenEpoch ?? 0).toBe(0);
|
|
1115
1133
|
expect((reloaded as unknown as {name?: string})?.name).toBe("Renamed");
|
|
1116
1134
|
expect(
|
|
1117
1135
|
(reloaded as unknown as {organizationIds?: string[]})?.organizationIds ?? []
|
|
1118
1136
|
).not.toContain("other-tenant");
|
|
1119
1137
|
});
|
|
1138
|
+
|
|
1139
|
+
it("clears email verification when PATCH /auth/me changes the mailbox", async () => {
|
|
1140
|
+
const [_admin, notAdmin] = await setupDb();
|
|
1141
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1142
|
+
const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
|
|
1143
|
+
const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
|
|
1144
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1145
|
+
});
|
|
1146
|
+
await UserModel.findByIdAndUpdate(notAdminId, {$set: {emailVerified: true}});
|
|
1147
|
+
|
|
1148
|
+
await agent
|
|
1149
|
+
.patch("/auth/me")
|
|
1150
|
+
.set("authorization", `Bearer ${token}`)
|
|
1151
|
+
.send({email: "unproven@example.com"})
|
|
1152
|
+
.expect(200);
|
|
1153
|
+
|
|
1154
|
+
const reloaded = await UserModel.findById(notAdminId);
|
|
1155
|
+
expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(false);
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
it("keeps email verification for a casing-only email update", async () => {
|
|
1159
|
+
const [_admin, notAdmin] = await setupDb();
|
|
1160
|
+
const jwtLib = (await import("jsonwebtoken")).default;
|
|
1161
|
+
const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
|
|
1162
|
+
const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
|
|
1163
|
+
issuer: process.env.TOKEN_ISSUER,
|
|
1164
|
+
});
|
|
1165
|
+
await UserModel.findByIdAndUpdate(notAdminId, {$set: {emailVerified: true}});
|
|
1166
|
+
|
|
1167
|
+
await agent
|
|
1168
|
+
.patch("/auth/me")
|
|
1169
|
+
.set("authorization", `Bearer ${token}`)
|
|
1170
|
+
.send({email: "NOTADMIN@EXAMPLE.COM"})
|
|
1171
|
+
.expect(200);
|
|
1172
|
+
|
|
1173
|
+
const reloaded = await UserModel.findById(notAdminId);
|
|
1174
|
+
expect((reloaded as unknown as {emailVerified?: boolean})?.emailVerified).toBe(true);
|
|
1175
|
+
});
|
|
1120
1176
|
});
|
|
1121
1177
|
|
|
1122
1178
|
describe("Secret prefix authorization bypass", () => {
|
|
@@ -1143,7 +1199,7 @@ describe("Secret prefix authorization bypass", () => {
|
|
|
1143
1199
|
);
|
|
1144
1200
|
},
|
|
1145
1201
|
skipListen: true,
|
|
1146
|
-
userModel: UserModel as
|
|
1202
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1147
1203
|
}).build();
|
|
1148
1204
|
agent = supertest.agent(app);
|
|
1149
1205
|
});
|
|
@@ -1208,7 +1264,7 @@ describe("refresh_token without REFRESH_TOKEN_SECRET", () => {
|
|
|
1208
1264
|
app = new TerrenoApp({
|
|
1209
1265
|
configureApp: () => {},
|
|
1210
1266
|
skipListen: true,
|
|
1211
|
-
userModel: UserModel as
|
|
1267
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1212
1268
|
}).build();
|
|
1213
1269
|
agent = supertest.agent(app);
|
|
1214
1270
|
});
|
|
@@ -1274,7 +1330,7 @@ describe("JWT cookie extraction and /me routes edge cases", () => {
|
|
|
1274
1330
|
app = new TerrenoApp({
|
|
1275
1331
|
configureApp: () => {},
|
|
1276
1332
|
skipListen: true,
|
|
1277
|
-
userModel: UserModel as
|
|
1333
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1278
1334
|
}).build();
|
|
1279
1335
|
agent = supertest.agent(app);
|
|
1280
1336
|
});
|
|
@@ -1322,7 +1378,7 @@ describe("login error and disabled user paths", () => {
|
|
|
1322
1378
|
app = new TerrenoApp({
|
|
1323
1379
|
configureApp: () => {},
|
|
1324
1380
|
skipListen: true,
|
|
1325
|
-
userModel: UserModel as
|
|
1381
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1326
1382
|
}).build();
|
|
1327
1383
|
agent = supertest.agent(app);
|
|
1328
1384
|
});
|
|
@@ -1370,7 +1426,7 @@ describe("PATCH /me route edge cases", () => {
|
|
|
1370
1426
|
app = new TerrenoApp({
|
|
1371
1427
|
configureApp: () => {},
|
|
1372
1428
|
skipListen: true,
|
|
1373
|
-
userModel: UserModel as
|
|
1429
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1374
1430
|
}).build();
|
|
1375
1431
|
agent = supertest.agent(app);
|
|
1376
1432
|
});
|
|
@@ -1430,7 +1486,7 @@ describe("JWT strategy createAnonymousUser path", () => {
|
|
|
1430
1486
|
);
|
|
1431
1487
|
},
|
|
1432
1488
|
skipListen: true,
|
|
1433
|
-
userModel: UserModel as
|
|
1489
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1434
1490
|
}).build();
|
|
1435
1491
|
agent = supertest.agent(app);
|
|
1436
1492
|
});
|
|
@@ -1501,7 +1557,7 @@ describe("decodeJWTMiddleware error paths", () => {
|
|
|
1501
1557
|
);
|
|
1502
1558
|
},
|
|
1503
1559
|
skipListen: true,
|
|
1504
|
-
userModel: UserModel as
|
|
1560
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1505
1561
|
}).build();
|
|
1506
1562
|
agent = supertest.agent(app);
|
|
1507
1563
|
});
|
|
@@ -1588,7 +1644,7 @@ describe("signup disabled", () => {
|
|
|
1588
1644
|
app = new TerrenoApp({
|
|
1589
1645
|
configureApp: () => {},
|
|
1590
1646
|
skipListen: true,
|
|
1591
|
-
userModel: UserModel as
|
|
1647
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1592
1648
|
}).build();
|
|
1593
1649
|
agent = supertest.agent(app);
|
|
1594
1650
|
});
|
|
@@ -1758,7 +1814,7 @@ describe("auth error paths when the user lookup fails", () => {
|
|
|
1758
1814
|
app = new TerrenoApp({
|
|
1759
1815
|
configureApp: () => {},
|
|
1760
1816
|
skipListen: true,
|
|
1761
|
-
userModel: UserModel as
|
|
1817
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1762
1818
|
}).build();
|
|
1763
1819
|
agent = supertest.agent(app);
|
|
1764
1820
|
});
|
|
@@ -1799,7 +1855,7 @@ describe("auth error paths when the user lookup fails", () => {
|
|
|
1799
1855
|
const errApp = new TerrenoApp({
|
|
1800
1856
|
configureApp: () => {},
|
|
1801
1857
|
skipListen: true,
|
|
1802
|
-
userModel: UserModel as
|
|
1858
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
1803
1859
|
}).build();
|
|
1804
1860
|
const errAgent = supertest.agent(errApp);
|
|
1805
1861
|
const res = await errAgent
|
package/src/auth.ts
CHANGED
|
@@ -2,7 +2,7 @@ import {randomUUID} from "node:crypto";
|
|
|
2
2
|
import express from "express";
|
|
3
3
|
import jwt, {type JwtPayload} from "jsonwebtoken";
|
|
4
4
|
import {DateTime} from "luxon";
|
|
5
|
-
import type {Model, ObjectId} from "mongoose";
|
|
5
|
+
import type {Model, ObjectId, Query} from "mongoose";
|
|
6
6
|
import ms, {type StringValue} from "ms";
|
|
7
7
|
import passport from "passport";
|
|
8
8
|
import {Strategy as AnonymousStrategy} from "passport-anonymous";
|
|
@@ -12,10 +12,12 @@ import {
|
|
|
12
12
|
type StrategyOptions,
|
|
13
13
|
} from "passport-jwt";
|
|
14
14
|
import {Strategy as LocalStrategy} from "passport-local";
|
|
15
|
-
|
|
15
|
+
import {addAuthRecoveryRoutes, sendVerificationEmail} from "./authRecovery";
|
|
16
|
+
import {AuthToken} from "./authTokens";
|
|
16
17
|
import {APIError, apiErrorMiddleware, errorMessage} from "./errors";
|
|
17
18
|
import type {AuthOptions} from "./expressServer";
|
|
18
19
|
import {logger} from "./logger";
|
|
20
|
+
import {isJwtCredentialExchangePath} from "./rateLimit/policies";
|
|
19
21
|
import {
|
|
20
22
|
getSessionIdFromJwtPayload,
|
|
21
23
|
type JwtSessionPayload,
|
|
@@ -34,6 +36,12 @@ export interface User {
|
|
|
34
36
|
* This can be helpful for pre-signup users.
|
|
35
37
|
*/
|
|
36
38
|
isAnonymous?: boolean;
|
|
39
|
+
/** Login identifier; present on passport-local and Better Auth app users. */
|
|
40
|
+
email?: string;
|
|
41
|
+
/** Incremented on password reset so outstanding refresh tokens fail. */
|
|
42
|
+
tokenEpoch?: number;
|
|
43
|
+
/** Set by emailVerificationPlugin; login may require this when requireEmailVerification is on. */
|
|
44
|
+
emailVerified?: boolean;
|
|
37
45
|
}
|
|
38
46
|
|
|
39
47
|
export interface UserModel extends Model<User> {
|
|
@@ -41,18 +49,14 @@ export interface UserModel extends Model<User> {
|
|
|
41
49
|
// Allows additional setup during signup. This will be passed the rest of req.body from the signup
|
|
42
50
|
postCreate?: (body: Record<string, unknown>) => Promise<void>;
|
|
43
51
|
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
deserializeUser(): any;
|
|
53
|
-
// noExplicitAny: passport-local-mongoose return types are untyped
|
|
54
|
-
// biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
|
|
55
|
-
findByUsername(username: string, findOpts: any): any;
|
|
52
|
+
// Provided by passport-local-mongoose:
|
|
53
|
+
createStrategy(): passport.Strategy;
|
|
54
|
+
serializeUser(): (user: User, cb: (err: unknown, id?: unknown) => void) => void;
|
|
55
|
+
deserializeUser(): (username: string, cb: (err: unknown, user?: User | null) => void) => void;
|
|
56
|
+
findByUsername(
|
|
57
|
+
username: string,
|
|
58
|
+
findOpts: boolean | {selectHashSaltFields?: boolean}
|
|
59
|
+
): Query<User | null, User>;
|
|
56
60
|
}
|
|
57
61
|
|
|
58
62
|
export interface GenerateTokensOptions {
|
|
@@ -101,11 +105,18 @@ export const authenticateMiddleware = (anonymous = false) => {
|
|
|
101
105
|
};
|
|
102
106
|
|
|
103
107
|
/**
|
|
104
|
-
* User fields that confer authority. Self-service requests
|
|
105
|
-
* must never set them, or any caller could grant
|
|
106
|
-
*
|
|
108
|
+
* User fields that confer authority or skip security gates. Self-service requests
|
|
109
|
+
* (anonymous signup, `PATCH /me`) must never set them, or any caller could grant
|
|
110
|
+
* themselves admin, an RBAC role, a verified email, or a reset epoch. Elevate users
|
|
111
|
+
* through the admin API or `access.roles.assign` instead.
|
|
107
112
|
*/
|
|
108
|
-
export const PRIVILEGED_USER_FIELDS = [
|
|
113
|
+
export const PRIVILEGED_USER_FIELDS = [
|
|
114
|
+
"admin",
|
|
115
|
+
"roles",
|
|
116
|
+
"organizationIds",
|
|
117
|
+
"emailVerified",
|
|
118
|
+
"tokenEpoch",
|
|
119
|
+
] as const;
|
|
109
120
|
|
|
110
121
|
/**
|
|
111
122
|
* Removes {@link PRIVILEGED_USER_FIELDS} from a self-service body. Fields are dropped rather
|
|
@@ -130,6 +141,13 @@ export const stripPrivilegedUserFields = (
|
|
|
130
141
|
return sanitized;
|
|
131
142
|
};
|
|
132
143
|
|
|
144
|
+
const isEmailUpdateChangingMailbox = (currentEmail: unknown, nextEmail: unknown): boolean => {
|
|
145
|
+
if (typeof currentEmail !== "string" || typeof nextEmail !== "string") {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
return currentEmail.trim().toLowerCase() !== nextEmail.trim().toLowerCase();
|
|
149
|
+
};
|
|
150
|
+
|
|
133
151
|
const omitPrivilegedFieldsFromObject = (item: unknown, allowAdminWrite: boolean): unknown => {
|
|
134
152
|
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
135
153
|
return item;
|
|
@@ -181,9 +199,18 @@ export const signupUser = async (
|
|
|
181
199
|
const bodyRest = stripPrivilegedUserFields(rawBody, "signup");
|
|
182
200
|
|
|
183
201
|
try {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
202
|
+
const registrableModel = userModel as UserModel & {
|
|
203
|
+
register(
|
|
204
|
+
user: Record<string, unknown>,
|
|
205
|
+
password: string
|
|
206
|
+
): Promise<
|
|
207
|
+
User & {
|
|
208
|
+
postCreate?: (body: Record<string, unknown>) => Promise<void>;
|
|
209
|
+
save: () => Promise<unknown>;
|
|
210
|
+
}
|
|
211
|
+
>;
|
|
212
|
+
};
|
|
213
|
+
const user = await registrableModel.register({email, ...bodyRest}, password);
|
|
187
214
|
|
|
188
215
|
if (user.postCreate) {
|
|
189
216
|
try {
|
|
@@ -341,15 +368,20 @@ export const generateTokens = async (
|
|
|
341
368
|
return {refreshToken: null, token: null};
|
|
342
369
|
}
|
|
343
370
|
const sessionId = options.sessionId ?? randomUUID();
|
|
344
|
-
|
|
371
|
+
const authUser = user as User;
|
|
372
|
+
let payload: Record<string, unknown> = {
|
|
373
|
+
id: String(tokenUser._id),
|
|
374
|
+
sid: sessionId,
|
|
375
|
+
te: authUser.tokenEpoch ?? 0,
|
|
376
|
+
};
|
|
345
377
|
if (authOptions?.generateJWTPayload) {
|
|
346
|
-
payload = {...authOptions.generateJWTPayload(
|
|
378
|
+
payload = {...authOptions.generateJWTPayload(authUser), ...payload};
|
|
347
379
|
}
|
|
348
380
|
const tokenOptions: jwt.SignOptions = {
|
|
349
381
|
expiresIn: "15m",
|
|
350
382
|
};
|
|
351
383
|
if (authOptions?.generateTokenExpiration) {
|
|
352
|
-
tokenOptions.expiresIn = authOptions.generateTokenExpiration(
|
|
384
|
+
tokenOptions.expiresIn = authOptions.generateTokenExpiration(authUser);
|
|
353
385
|
} else if (process.env.TOKEN_EXPIRES_IN) {
|
|
354
386
|
const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
|
|
355
387
|
if (expiresIn) {
|
|
@@ -368,7 +400,7 @@ export const generateTokens = async (
|
|
|
368
400
|
expiresIn: "30d",
|
|
369
401
|
};
|
|
370
402
|
if (authOptions?.generateRefreshTokenExpiration) {
|
|
371
|
-
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(
|
|
403
|
+
refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(authUser);
|
|
372
404
|
} else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
|
|
373
405
|
const expiresIn = validateDuration(
|
|
374
406
|
"REFRESH_TOKEN_EXPIRES_IN",
|
|
@@ -469,6 +501,12 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
469
501
|
return next();
|
|
470
502
|
}
|
|
471
503
|
|
|
504
|
+
// Login, signup, and refresh exchange credentials. A stale access JWT in
|
|
505
|
+
// Authorization / the jwt cookie must not 401 before those handlers run.
|
|
506
|
+
if (isJwtCredentialExchangePath(req)) {
|
|
507
|
+
return next();
|
|
508
|
+
}
|
|
509
|
+
|
|
472
510
|
// Allow requests with a "Secret" prefix to pass through since this is a string value,
|
|
473
511
|
// not a jwt that needs to be decoded
|
|
474
512
|
if (req?.headers?.authorization?.split(" ")[0] === "Secret") {
|
|
@@ -535,9 +573,8 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
|
|
|
535
573
|
return next();
|
|
536
574
|
};
|
|
537
575
|
app.use(decodeJWTMiddleware);
|
|
538
|
-
//
|
|
539
|
-
|
|
540
|
-
app.use(express.urlencoded({extended: false}) as any);
|
|
576
|
+
// express 5's urlencoded() handler type doesn't match RequestHandler directly
|
|
577
|
+
app.use(express.urlencoded({extended: false}) as unknown as express.RequestHandler);
|
|
541
578
|
};
|
|
542
579
|
|
|
543
580
|
export const addAuthRoutes = (
|
|
@@ -563,6 +600,15 @@ export const addAuthRoutes = (
|
|
|
563
600
|
logger.warn(`Invalid login: ${info}`);
|
|
564
601
|
return res.status(401).json({message: info?.message});
|
|
565
602
|
}
|
|
603
|
+
if (authOptions?.requireEmailVerification && user.emailVerified !== true) {
|
|
604
|
+
return next(
|
|
605
|
+
new APIError({
|
|
606
|
+
code: "email-not-verified",
|
|
607
|
+
status: 403,
|
|
608
|
+
title: "Email is not verified",
|
|
609
|
+
})
|
|
610
|
+
);
|
|
611
|
+
}
|
|
566
612
|
if (process.env.NODE_ENV !== "test") {
|
|
567
613
|
logger.info(`User logged in: ${user._id}, type: ${user.type || "N/A"}`);
|
|
568
614
|
}
|
|
@@ -602,6 +648,12 @@ export const addAuthRoutes = (
|
|
|
602
648
|
}
|
|
603
649
|
if (decoded?.id) {
|
|
604
650
|
const user = await userModel.findById(decoded.id);
|
|
651
|
+
const tokenEpoch = typeof decoded.te === "number" ? decoded.te : 0;
|
|
652
|
+
const userEpoch = (user as User | null)?.tokenEpoch ?? 0;
|
|
653
|
+
if (!user || tokenEpoch !== userEpoch) {
|
|
654
|
+
logger.error(`Invalid refresh token, user id: ${req.user?.id}`);
|
|
655
|
+
return res.status(401).json({message: "Invalid refresh token"});
|
|
656
|
+
}
|
|
605
657
|
const sessionId = getSessionIdFromJwtPayload(decoded as JwtSessionPayload);
|
|
606
658
|
const tokens = await generateTokens(user, authOptions, {sessionId});
|
|
607
659
|
if (tokens.sessionId) {
|
|
@@ -643,6 +695,13 @@ export const addAuthRoutes = (
|
|
|
643
695
|
)(req, res, next);
|
|
644
696
|
},
|
|
645
697
|
async (req: express.Request, res: express.Response) => {
|
|
698
|
+
if (req.user) {
|
|
699
|
+
try {
|
|
700
|
+
await sendVerificationEmail(req.user, authOptions);
|
|
701
|
+
} catch (error: unknown) {
|
|
702
|
+
logger.error("[auth] Failed to send verification mail after signup", {error});
|
|
703
|
+
}
|
|
704
|
+
}
|
|
646
705
|
const tokens = await generateTokens(req.user, authOptions);
|
|
647
706
|
if (tokens.sessionId) {
|
|
648
707
|
setRequestContext({
|
|
@@ -659,6 +718,7 @@ export const addAuthRoutes = (
|
|
|
659
718
|
}
|
|
660
719
|
app.set("etag", false);
|
|
661
720
|
app.use("/auth", router);
|
|
721
|
+
addAuthRecoveryRoutes(app, userModel, authOptions);
|
|
662
722
|
};
|
|
663
723
|
|
|
664
724
|
export const addMeRoutes = (
|
|
@@ -705,7 +765,16 @@ export const addMeRoutes = (
|
|
|
705
765
|
// return res.status(403).send({message: (e as Error).message});
|
|
706
766
|
// }
|
|
707
767
|
try {
|
|
708
|
-
|
|
768
|
+
const update = stripPrivilegedUserFields(req.body ?? {}, "PATCH /auth/me");
|
|
769
|
+
const isMailboxChange = isEmailUpdateChangingMailbox(doc.email, update.email);
|
|
770
|
+
Object.assign(doc, update);
|
|
771
|
+
if (isMailboxChange) {
|
|
772
|
+
await AuthToken.invalidateUnusedFor({_id: String(doc._id)}, "passwordReset");
|
|
773
|
+
if (userModel.schema.path("emailVerified") !== undefined) {
|
|
774
|
+
doc.emailVerified = false;
|
|
775
|
+
await AuthToken.invalidateUnusedFor({_id: String(doc._id)}, "emailVerification");
|
|
776
|
+
}
|
|
777
|
+
}
|
|
709
778
|
await doc.save();
|
|
710
779
|
|
|
711
780
|
const dataObject = doc.toObject() as unknown as Record<string, unknown>;
|