@terreno/api 57.2.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.
Files changed (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -0,0 +1,118 @@
1
+ import {createHash, randomBytes} from "node:crypto";
2
+ import {DateTime, Duration} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "./plugins";
6
+ import type {AuthTokenDocument, AuthTokenModel, AuthTokenType} from "./types/authToken";
7
+
8
+ export type {AuthTokenDocument, AuthTokenModel, AuthTokenType} from "./types/authToken";
9
+
10
+ export const AUTH_TOKEN_TTL = {
11
+ emailVerification: Duration.fromObject({hours: 24}),
12
+ passwordReset: Duration.fromObject({hours: 1}),
13
+ } as const;
14
+
15
+ const AUTH_TOKEN_TYPES: AuthTokenType[] = ["passwordReset", "emailVerification"];
16
+
17
+ const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
18
+
19
+ const authTokenSchema = new mongoose.Schema<AuthTokenDocument, AuthTokenModel>(
20
+ {
21
+ consumedAt: {
22
+ description: "When this token was consumed; unset until first successful consume",
23
+ type: Date,
24
+ },
25
+ expiresAt: {
26
+ description: "When this token expires and can no longer be consumed",
27
+ required: true,
28
+ type: Date,
29
+ },
30
+ tokenHash: {
31
+ description: "SHA-256 hash of the one-time token plaintext",
32
+ required: true,
33
+ type: String,
34
+ unique: true,
35
+ },
36
+ type: {
37
+ description: "Whether this token is for password reset or email verification",
38
+ enum: AUTH_TOKEN_TYPES,
39
+ required: true,
40
+ type: String,
41
+ },
42
+ userId: {
43
+ description: "The user this token was issued for",
44
+ index: true,
45
+ ref: "User",
46
+ required: true,
47
+ type: mongoose.Schema.Types.ObjectId,
48
+ },
49
+ },
50
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
51
+ );
52
+
53
+ authTokenSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
54
+
55
+ authTokenSchema.plugin(createdUpdatedPlugin);
56
+ authTokenSchema.plugin(findOneOrNone);
57
+ authTokenSchema.plugin(findExactlyOne);
58
+
59
+ authTokenSchema.statics = {
60
+ ...authTokenSchema.statics,
61
+ async consume(
62
+ this: AuthTokenModel,
63
+ token: string,
64
+ type: AuthTokenType
65
+ ): Promise<AuthTokenDocument | null> {
66
+ const now = DateTime.now().toJSDate();
67
+ const consumed = await this.findOneAndUpdate(
68
+ {
69
+ consumedAt: {$exists: false},
70
+ expiresAt: {$gt: now},
71
+ tokenHash: hashToken(token),
72
+ type,
73
+ },
74
+ {$set: {consumedAt: now}},
75
+ {returnDocument: "after"}
76
+ );
77
+ return consumed;
78
+ },
79
+
80
+ async invalidateUnusedFor(
81
+ this: AuthTokenModel,
82
+ user: {_id: {toString(): string}},
83
+ type: AuthTokenType
84
+ ): Promise<void> {
85
+ const userId = new mongoose.Types.ObjectId(String(user._id));
86
+ await this.updateMany(
87
+ {
88
+ consumedAt: {$exists: false},
89
+ type,
90
+ userId,
91
+ },
92
+ {$set: {consumedAt: DateTime.now().toJSDate()}}
93
+ );
94
+ },
95
+
96
+ async issueFor(
97
+ this: AuthTokenModel,
98
+ user: {_id: {toString(): string}},
99
+ type: AuthTokenType
100
+ ): Promise<{authToken: AuthTokenDocument; token: string}> {
101
+ const token = randomBytes(32).toString("hex");
102
+ const ttl = AUTH_TOKEN_TTL[type];
103
+ const now = DateTime.now();
104
+ const userId = new mongoose.Types.ObjectId(String(user._id));
105
+ await this.invalidateUnusedFor(user, type);
106
+ const authToken = await this.create({
107
+ expiresAt: now.plus(ttl).toJSDate(),
108
+ tokenHash: hashToken(token),
109
+ type,
110
+ userId,
111
+ });
112
+ return {authToken, token};
113
+ },
114
+ };
115
+
116
+ export const AuthToken =
117
+ (mongoose.models.AuthToken as AuthTokenModel | undefined) ??
118
+ mongoose.model<AuthTokenDocument, AuthTokenModel>("AuthToken", authTokenSchema);
@@ -0,0 +1,293 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type express from "express";
4
+ import mongoose, {Schema} from "mongoose";
5
+ import passportLocalMongoose from "passport-local-mongoose";
6
+ import supertest from "supertest";
7
+
8
+ import type {UserModel as AuthUserModel} from "./auth";
9
+ import {AuthToken} from "./authTokens";
10
+ import {TerrenoApp} from "./terrenoApp";
11
+ import {setupDb, UserModel} from "./tests";
12
+
13
+ interface CapturedMail {
14
+ html?: string;
15
+ subject: string;
16
+ text: string;
17
+ to: string;
18
+ }
19
+
20
+ const tokenFromVerifyUrl = (text: string): string => {
21
+ const match = text.match(/token=([0-9a-f]+)/i);
22
+ assert.isNotNull(match);
23
+ return match?.[1] ?? "";
24
+ };
25
+
26
+ describe("email verification gating", () => {
27
+ let gatedApp: express.Application;
28
+ let openApp: express.Application;
29
+ let gatedMail: CapturedMail[];
30
+ let openMail: CapturedMail[];
31
+
32
+ beforeEach(async () => {
33
+ await setupDb();
34
+ await AuthToken.deleteMany({});
35
+ gatedMail = [];
36
+ openMail = [];
37
+
38
+ gatedApp = new TerrenoApp({
39
+ authOptions: {
40
+ publicAppUrl: "https://app.example.com",
41
+ requireEmailVerification: true,
42
+ sendMail: async (message) => {
43
+ gatedMail.push(message);
44
+ },
45
+ },
46
+ skipListen: true,
47
+ userModel: UserModel,
48
+ }).build();
49
+
50
+ openApp = new TerrenoApp({
51
+ authOptions: {
52
+ publicAppUrl: "https://app.example.com",
53
+ sendMail: async (message) => {
54
+ openMail.push(message);
55
+ },
56
+ },
57
+ skipListen: true,
58
+ userModel: UserModel,
59
+ }).build();
60
+ });
61
+
62
+ it("returns 403 email-not-verified on login when the user is unverified", async () => {
63
+ const response = await supertest(gatedApp)
64
+ .post("/auth/login")
65
+ .send({email: "notAdmin@example.com", password: "password"})
66
+ .expect(403);
67
+ assert.equal(response.body.code, "email-not-verified");
68
+ });
69
+
70
+ it("allows login when requireEmailVerification is off", async () => {
71
+ await supertest(openApp)
72
+ .post("/auth/login")
73
+ .send({email: "notAdmin@example.com", password: "password"})
74
+ .expect(200);
75
+ });
76
+
77
+ it("lets an unverified user verify then login when gating is on", async () => {
78
+ const signup = await supertest(gatedApp)
79
+ .post("/auth/signup")
80
+ .send({email: "new-verify@example.com", password: "password"})
81
+ .expect(200);
82
+ assert.isString(signup.body.data.token);
83
+ assert.equal(gatedMail.length, 1);
84
+ const token = tokenFromVerifyUrl(gatedMail[0]?.text ?? "");
85
+
86
+ await supertest(gatedApp)
87
+ .post("/auth/login")
88
+ .send({
89
+ email: "new-verify@example.com",
90
+ password: "password",
91
+ })
92
+ .expect(403);
93
+
94
+ await supertest(gatedApp).post("/auth/verifyEmail").send({token}).expect(200);
95
+
96
+ await supertest(gatedApp)
97
+ .post("/auth/login")
98
+ .send({email: "new-verify@example.com", password: "password"})
99
+ .expect(200);
100
+ });
101
+
102
+ it("resends verification mail for an authenticated unverified user", async () => {
103
+ const login = await supertest(openApp)
104
+ .post("/auth/login")
105
+ .send({email: "notAdmin@example.com", password: "password"})
106
+ .expect(200);
107
+
108
+ await supertest(openApp)
109
+ .post("/auth/sendVerification")
110
+ .set("Authorization", `Bearer ${login.body.data.token}`)
111
+ .expect(202);
112
+ assert.equal(openMail.length, 1);
113
+ assert.include(openMail[0]?.text ?? "", "https://app.example.com/verifyEmail?token=");
114
+ });
115
+
116
+ it("returns a delivery error instead of reporting a false resend success", async () => {
117
+ const failingApp = new TerrenoApp({
118
+ authOptions: {
119
+ publicAppUrl: "https://app.example.com",
120
+ sendMail: async () => {
121
+ throw new Error("delivery failed");
122
+ },
123
+ },
124
+ skipListen: true,
125
+ userModel: UserModel,
126
+ }).build();
127
+ const login = await supertest(failingApp)
128
+ .post("/auth/login")
129
+ .send({email: "notAdmin@example.com", password: "password"})
130
+ .expect(200);
131
+
132
+ await supertest(failingApp)
133
+ .post("/auth/sendVerification")
134
+ .set("Authorization", `Bearer ${login.body.data.token}`)
135
+ .expect(500);
136
+ });
137
+
138
+ it("returns 501 when resend cannot send because publicAppUrl is missing", async () => {
139
+ const noUrlApp = new TerrenoApp({
140
+ authOptions: {
141
+ sendMail: async (message) => {
142
+ openMail.push(message);
143
+ },
144
+ },
145
+ skipListen: true,
146
+ userModel: UserModel,
147
+ }).build();
148
+ const login = await supertest(noUrlApp)
149
+ .post("/auth/login")
150
+ .send({email: "notAdmin@example.com", password: "password"})
151
+ .expect(200);
152
+ const before = await AuthToken.countDocuments({type: "emailVerification"});
153
+
154
+ await supertest(noUrlApp)
155
+ .post("/auth/sendVerification")
156
+ .set("Authorization", `Bearer ${login.body.data.token}`)
157
+ .expect(501);
158
+ assert.equal(openMail.length, 0);
159
+ assert.equal(await AuthToken.countDocuments({type: "emailVerification"}), before);
160
+ });
161
+
162
+ it("does not send verification mail when the user is already verified", async () => {
163
+ const login = await supertest(openApp)
164
+ .post("/auth/login")
165
+ .send({email: "notAdmin@example.com", password: "password"})
166
+ .expect(200);
167
+ const users = await UserModel.find({email: "notAdmin@example.com"});
168
+ const user = users[0];
169
+ assert.isNotNull(user);
170
+ (user as {emailVerified?: boolean}).emailVerified = true;
171
+ await user?.save();
172
+
173
+ await supertest(openApp)
174
+ .post("/auth/sendVerification")
175
+ .set("Authorization", `Bearer ${login.body.data.token}`)
176
+ .expect(202);
177
+ assert.equal(openMail.length, 0);
178
+ });
179
+
180
+ it("rejects verifyEmail without a token and with an invalid token", async () => {
181
+ await supertest(gatedApp).post("/auth/verifyEmail").send({}).expect(400);
182
+ await supertest(gatedApp)
183
+ .post("/auth/verifyEmail")
184
+ .send({token: "not-a-real-token"})
185
+ .expect(400);
186
+ });
187
+
188
+ it("requires authentication to resend verification", async () => {
189
+ await supertest(openApp).post("/auth/sendVerification").expect(401);
190
+ });
191
+
192
+ it("returns 400 when the consumed verification token has no user", async () => {
193
+ const orphanId = new mongoose.Types.ObjectId();
194
+ const issued = await AuthToken.issueFor({_id: orphanId}, "emailVerification");
195
+ await supertest(gatedApp).post("/auth/verifyEmail").send({token: issued.token}).expect(400);
196
+ });
197
+
198
+ it("rejects an old verification token after PATCH /auth/me changes the mailbox", async () => {
199
+ const login = await supertest(openApp)
200
+ .post("/auth/login")
201
+ .send({email: "notAdmin@example.com", password: "password"})
202
+ .expect(200);
203
+ const userId = login.body.data.userId as string;
204
+ const accessToken = login.body.data.token as string;
205
+ const issued = await AuthToken.issueFor({_id: userId}, "emailVerification");
206
+
207
+ await supertest(openApp)
208
+ .patch("/auth/me")
209
+ .set("authorization", `Bearer ${accessToken}`)
210
+ .send({email: "new-mailbox@example.com"})
211
+ .expect(200);
212
+
213
+ await supertest(openApp).post("/auth/verifyEmail").send({token: issued.token}).expect(400);
214
+
215
+ const reloaded = await UserModel.findById(userId);
216
+ assert.equal((reloaded as unknown as {emailVerified?: boolean})?.emailVerified, false);
217
+ });
218
+
219
+ it("rejects an old password-reset token after PATCH /auth/me changes the mailbox", async () => {
220
+ const login = await supertest(openApp)
221
+ .post("/auth/login")
222
+ .send({email: "notAdmin@example.com", password: "password"})
223
+ .expect(200);
224
+ const userId = login.body.data.userId as string;
225
+ const accessToken = login.body.data.token as string;
226
+ const issued = await AuthToken.issueFor({_id: userId}, "passwordReset");
227
+
228
+ await supertest(openApp)
229
+ .patch("/auth/me")
230
+ .set("authorization", `Bearer ${accessToken}`)
231
+ .send({email: "new-mailbox@example.com"})
232
+ .expect(200);
233
+
234
+ await supertest(openApp)
235
+ .post("/auth/resetPassword")
236
+ .send({password: "brand-new-password", token: issued.token})
237
+ .expect(400);
238
+ });
239
+
240
+ it("invalidates unused password-reset tokens on mailbox change without emailVerified", async () => {
241
+ const jwtResetOnlySchema = new Schema({
242
+ email: {type: String},
243
+ tokenEpoch: {default: 0, type: Number},
244
+ });
245
+ jwtResetOnlySchema.plugin(
246
+ passportLocalMongoose as unknown as (
247
+ schema: Schema,
248
+ options?: Record<string, unknown>
249
+ ) => void,
250
+ {
251
+ usernameCaseInsensitive: true,
252
+ usernameField: "email",
253
+ }
254
+ );
255
+ const JwtResetOnlyUser = (mongoose.models.JwtResetOnlyUser ??
256
+ mongoose.model("JwtResetOnlyUser", jwtResetOnlySchema)) as AuthUserModel;
257
+ await JwtResetOnlyUser.deleteMany({});
258
+ const registerable = JwtResetOnlyUser as unknown as {
259
+ register: (
260
+ user: {email: string},
261
+ password: string
262
+ ) => Promise<{_id: {toString: () => string}}>;
263
+ };
264
+ const user = await registerable.register({email: "reset-only@example.com"}, "password");
265
+ const userId = String(user._id);
266
+ const app = new TerrenoApp({
267
+ authOptions: {
268
+ publicAppUrl: "https://app.example.com",
269
+ sendMail: async () => undefined,
270
+ },
271
+ skipListen: true,
272
+ userModel: JwtResetOnlyUser,
273
+ }).build();
274
+ const login = await supertest(app)
275
+ .post("/auth/login")
276
+ .send({email: "reset-only@example.com", password: "password"})
277
+ .expect(200);
278
+ const accessToken = login.body.data.token as string;
279
+ const issued = await AuthToken.issueFor({_id: userId}, "passwordReset");
280
+
281
+ await supertest(app)
282
+ .patch("/auth/me")
283
+ .set("authorization", `Bearer ${accessToken}`)
284
+ .send({email: "new-reset-only@example.com"})
285
+ .expect(200);
286
+
287
+ await supertest(app)
288
+ .post("/auth/resetPassword")
289
+ .send({password: "brand-new-password", token: issued.token})
290
+ .expect(400);
291
+ assert.equal(JwtResetOnlyUser.schema.path("emailVerified"), undefined);
292
+ });
293
+ });
package/src/betterAuth.ts CHANGED
@@ -66,6 +66,30 @@ export interface BetterAuthConfig {
66
66
  * If not provided, falls back to BETTER_AUTH_URL environment variable.
67
67
  */
68
68
  baseURL?: string;
69
+
70
+ /** Public web/app origin used in password-reset and verification links. */
71
+ publicAppUrl?: string;
72
+
73
+ /** Deliver auth mail. Typically `getCommsService().sendMail`. */
74
+ sendMail?: (message: {html?: string; subject: string; text: string; to: string}) => Promise<void>;
75
+
76
+ /**
77
+ * Render reset/verify mail. Pass `@terreno/comms` `renderAuthMail` so JWT and
78
+ * Better Auth send identical templates.
79
+ */
80
+ renderAuthMail?: (options: {
81
+ publicAppUrl: string;
82
+ templateId: "resetPassword" | "verifyEmail";
83
+ token: string;
84
+ templates?: Partial<
85
+ Record<"resetPassword" | "verifyEmail", {html?: string; subject: string; text?: string}>
86
+ >;
87
+ }) => {html?: string; subject: string; text?: string};
88
+
89
+ /** Optional per-app subject/text/html overrides for auth mail. */
90
+ authMailTemplates?: Partial<
91
+ Record<"resetPassword" | "verifyEmail", {html?: string; subject: string; text?: string}>
92
+ >;
69
93
  }
70
94
 
71
95
  /**
@@ -95,6 +95,7 @@ describe("BetterAuthApp", () => {
95
95
  });
96
96
 
97
97
  expect(() => plugin.register(app)).not.toThrow();
98
+ expect(plugin.getBetterAuthBasePath()).toBe("/custom/auth");
98
99
  });
99
100
 
100
101
  it("registers with social providers", async () => {
@@ -27,33 +27,51 @@ export interface BetterAuthAppOptions {
27
27
  export class BetterAuthApp implements TerrenoPlugin {
28
28
  private auth: BetterAuthInstance | undefined;
29
29
  private options: BetterAuthAppOptions;
30
+ private sessionMiddlewareMounted = false;
30
31
 
31
32
  constructor(options: BetterAuthAppOptions) {
32
33
  this.options = options;
33
34
  }
34
35
 
35
- register(app: express.Application): void {
36
+ ensureAuth(): BetterAuthInstance {
37
+ if (this.auth) {
38
+ return this.auth;
39
+ }
36
40
  const {config, userModel} = this.options;
37
-
38
- const mongoClient = getMongoClientFromMongoose();
39
41
  this.auth = createBetterAuth({
40
42
  config,
41
- mongoClient,
43
+ mongoClient: getMongoClientFromMongoose(),
42
44
  userModel,
43
45
  });
46
+ if (userModel) {
47
+ setupBetterAuthUserSync(this.auth, userModel);
48
+ }
49
+ return this.auth;
50
+ }
44
51
 
45
- const basePath = config.basePath ?? "/api/auth";
46
- mountBetterAuthRoutes(app, this.auth, basePath);
52
+ markSessionMiddlewareMounted(): void {
53
+ this.sessionMiddlewareMounted = true;
54
+ }
47
55
 
48
- app.use(createBetterAuthSessionMiddleware(this.auth, userModel));
56
+ register(app: express.Application): void {
57
+ const {config, userModel} = this.options;
58
+ const auth = this.ensureAuth();
49
59
 
50
- if (userModel) {
51
- setupBetterAuthUserSync(this.auth, userModel);
60
+ const basePath = config.basePath ?? "/api/auth";
61
+ mountBetterAuthRoutes(app, auth, basePath);
62
+
63
+ if (!this.sessionMiddlewareMounted) {
64
+ app.use(createBetterAuthSessionMiddleware(auth, userModel));
65
+ this.sessionMiddlewareMounted = true;
52
66
  }
53
67
 
54
68
  logger.info("Better Auth initialized via BetterAuthApp plugin");
55
69
  }
56
70
 
71
+ getBetterAuthBasePath(): string {
72
+ return this.options.config.basePath ?? "/api/auth";
73
+ }
74
+
57
75
  getAuth(): BetterAuthInstance | undefined {
58
76
  return this.auth;
59
77
  }