@terreno/api 57.16.2 → 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.
Files changed (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
package/src/auth.test.ts CHANGED
@@ -2,6 +2,8 @@ import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from
2
2
  import {assert} from "chai";
3
3
  import express from "express";
4
4
  import type jwt from "jsonwebtoken";
5
+ import mongoose, {Schema} from "mongoose";
6
+ import passportLocalMongoose from "passport-local-mongoose";
5
7
  import supertest from "supertest";
6
8
  import type TestAgent from "supertest/lib/agent";
7
9
 
@@ -15,13 +17,18 @@ import {
15
17
  MAX_PASSWORD_LENGTH,
16
18
  omitUserRolesFromWriteBody,
17
19
  PRIVILEGED_USER_FIELDS,
20
+ SELF_SERVICE_BLOCKED_USER_FIELDS,
18
21
  setPasswordForUser,
19
22
  setupAuth,
20
23
  signupUser,
21
24
  stripPrivilegedUserFields,
22
25
  } from "./auth";
26
+ import {apiUnauthorizedMiddleware} from "./errors";
27
+ import type {AuthOptions, AuthRecoveryMail} from "./expressServer";
28
+ import {githubUserPlugin} from "./githubAuth";
23
29
  import {logger} from "./logger";
24
30
  import {Permissions} from "./permissions";
31
+ import {isRbacUserModelName} from "./rbac/userWriteGuards";
25
32
  import {getCurrentRequestContext} from "./requestContext";
26
33
  import {TerrenoApp} from "./terrenoApp";
27
34
  import {type Food, FoodModel, getBaseServer, setupDb, setupTestData, UserModel} from "./tests";
@@ -195,7 +202,7 @@ describe("auth tests", () => {
195
202
 
196
203
  const mePatchRes = await agent
197
204
  .patch("/auth/me")
198
- .send({email: "new2@example.com"})
205
+ .send({currentPassword: "123", email: "new2@example.com"})
199
206
  .set("authorization", `Bearer ${token}`)
200
207
  .expect(200);
201
208
  expect(mePatchRes.body.data._id).toBeDefined();
@@ -375,7 +382,7 @@ describe("auth tests", () => {
375
382
 
376
383
  const mePatchRes = await agent
377
384
  .patch("/auth/me")
378
- .send({email: "admin2@example.com"})
385
+ .send({currentPassword: "securePassword", email: "admin2@example.com"})
379
386
  .expect(200);
380
387
  expect(mePatchRes.body.data._id).toBeDefined();
381
388
  expect(mePatchRes.body.data.id).toBeDefined();
@@ -1106,6 +1113,62 @@ describe("privileged user fields", () => {
1106
1113
  expect((user as unknown as {roles?: string[]}).roles ?? []).toEqual([]);
1107
1114
  });
1108
1115
 
1116
+ it("drops dotted-path forms of privileged fields from self-service and RBAC write bodies", () => {
1117
+ const body = {
1118
+ "emailVerified.flag": true,
1119
+ name: "Someone",
1120
+ "organizationIds.0": "other-tenant",
1121
+ "profile.nickname": "kept",
1122
+ "roles.0": "superadmin",
1123
+ "roles.1": "superadmin",
1124
+ rolesNote: "kept",
1125
+ };
1126
+ expect(stripPrivilegedUserFields(body, "test")).toEqual({
1127
+ name: "Someone",
1128
+ "profile.nickname": "kept",
1129
+ rolesNote: "kept",
1130
+ });
1131
+ expect(omitUserRolesFromWriteBody("User", {}, body)).toEqual({
1132
+ name: "Someone",
1133
+ "profile.nickname": "kept",
1134
+ rolesNote: "kept",
1135
+ });
1136
+ expect(omitUserRolesFromWriteBody("User", {}, {admin: true, "admin.flag": true}, true)).toEqual(
1137
+ {admin: true}
1138
+ );
1139
+ });
1140
+
1141
+ it("recognizes the createAccess user model by its compiled name", () => {
1142
+ const access = {userModel: {modelName: "Account"}};
1143
+ expect(isRbacUserModelName("Account", access)).toBe(true);
1144
+ expect(isRbacUserModelName("User", access)).toBe(true);
1145
+ expect(isRbacUserModelName("Todo", access)).toBe(false);
1146
+ expect(isRbacUserModelName("Account", undefined)).toBe(false);
1147
+ expect(omitUserRolesFromWriteBody("Account", access, {name: "a", roles: ["x"]})).toEqual({
1148
+ name: "a",
1149
+ });
1150
+ expect(omitUserRolesFromWriteBody("Account", {}, {roles: ["x"]})).toEqual({roles: ["x"]});
1151
+ });
1152
+
1153
+ it("does not let anonymous signup self-assign roles through dotted paths", async () => {
1154
+ await agent
1155
+ .post("/auth/signup")
1156
+ .send({
1157
+ email: "dotted-escalate@example.com",
1158
+ "organizationIds.0": "other-tenant",
1159
+ password: "Password123!",
1160
+ "roles.0": "superadmin",
1161
+ })
1162
+ .expect(200);
1163
+
1164
+ const created = await UserModel.findOne({email: "dotted-escalate@example.com"});
1165
+ expect(created).toBeTruthy();
1166
+ expect((created as unknown as {roles?: string[]})?.roles ?? []).toEqual([]);
1167
+ expect(
1168
+ (created as unknown as {organizationIds?: string[]})?.organizationIds ?? []
1169
+ ).not.toContain("other-tenant");
1170
+ });
1171
+
1109
1172
  it("does not let PATCH /auth/me escalate to admin or join organizations", async () => {
1110
1173
  const [_admin, notAdmin] = await setupDb();
1111
1174
  const jwtLib = (await import("jsonwebtoken")).default;
@@ -1148,7 +1211,7 @@ describe("privileged user fields", () => {
1148
1211
  await agent
1149
1212
  .patch("/auth/me")
1150
1213
  .set("authorization", `Bearer ${token}`)
1151
- .send({email: "unproven@example.com"})
1214
+ .send({currentPassword: "password", email: "unproven@example.com"})
1152
1215
  .expect(200);
1153
1216
 
1154
1217
  const reloaded = await UserModel.findById(notAdminId);
@@ -1175,6 +1238,372 @@ describe("privileged user fields", () => {
1175
1238
  });
1176
1239
  });
1177
1240
 
1241
+ describe("PATCH /auth/me email change step-up", () => {
1242
+ let agent: TestAgent;
1243
+ let sentMail: AuthRecoveryMail[];
1244
+ let token: string;
1245
+ let notAdminId: string;
1246
+
1247
+ const buildAgent = (authOptions: AuthOptions): TestAgent => {
1248
+ const app = new TerrenoApp({
1249
+ authOptions,
1250
+ configureApp: () => {},
1251
+ skipListen: true,
1252
+ userModel: UserModel as unknown as AuthUserModel,
1253
+ }).build();
1254
+ return supertest.agent(app);
1255
+ };
1256
+
1257
+ const signToken = async (id: string): Promise<string> => {
1258
+ const jwtLib = (await import("jsonwebtoken")).default;
1259
+ return jwtLib.sign({id}, process.env.TOKEN_SECRET as string, {
1260
+ issuer: process.env.TOKEN_ISSUER,
1261
+ });
1262
+ };
1263
+
1264
+ const reloadNotAdmin = async (): Promise<Record<string, unknown> | null> => {
1265
+ return (await UserModel.findById(notAdminId).lean()) as Record<string, unknown> | null;
1266
+ };
1267
+
1268
+ beforeEach(async () => {
1269
+ setSystemTime();
1270
+ const [_admin, notAdmin] = await setupDb();
1271
+ notAdminId = String((notAdmin as unknown as {_id: {toString(): string}})._id);
1272
+ token = await signToken(notAdminId);
1273
+ sentMail = [];
1274
+ agent = buildAgent({
1275
+ sendMail: async (message) => {
1276
+ sentMail.push(message);
1277
+ },
1278
+ });
1279
+ });
1280
+
1281
+ afterEach(() => {
1282
+ setSystemTime();
1283
+ });
1284
+
1285
+ it("rejects an email change without the current password and writes nothing", async () => {
1286
+ const res = await agent
1287
+ .patch("/auth/me")
1288
+ .set("authorization", `Bearer ${token}`)
1289
+ .send({email: "taken-over@example.com", name: "Should Not Save"})
1290
+ .expect(403);
1291
+ expect(res.body.message).toContain("current password");
1292
+
1293
+ const reloaded = await reloadNotAdmin();
1294
+ expect(reloaded?.email).toBe("notAdmin@example.com");
1295
+ expect(reloaded?.name).toBe("Not Admin");
1296
+ expect(sentMail).toHaveLength(0);
1297
+ });
1298
+
1299
+ it("rejects an email change with a wrong current password and counts the attempt", async () => {
1300
+ await agent
1301
+ .patch("/auth/me")
1302
+ .set("authorization", `Bearer ${token}`)
1303
+ .send({currentPassword: "wrong-password", email: "taken-over@example.com"})
1304
+ .expect(403);
1305
+
1306
+ const reloaded = await reloadNotAdmin();
1307
+ expect(reloaded?.email).toBe("notAdmin@example.com");
1308
+ expect(reloaded?.attempts).toBe(1);
1309
+ expect(sentMail).toHaveLength(0);
1310
+ });
1311
+
1312
+ it("reports the passport lockout once wrong current passwords reach maxAttempts", async () => {
1313
+ const messages: string[] = [];
1314
+ // The test user model locks after three wrong attempts.
1315
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1316
+ const res = await agent
1317
+ .patch("/auth/me")
1318
+ .set("authorization", `Bearer ${token}`)
1319
+ .send({currentPassword: "wrong-password", email: "taken-over@example.com"})
1320
+ .expect(403);
1321
+ messages.push(res.body.message);
1322
+ }
1323
+ expect(messages.slice(0, 2)).toEqual([
1324
+ "The current password is incorrect.",
1325
+ "The current password is incorrect.",
1326
+ ]);
1327
+ expect(messages[2]).not.toBe("The current password is incorrect.");
1328
+ const locked = await agent
1329
+ .patch("/auth/me")
1330
+ .set("authorization", `Bearer ${token}`)
1331
+ .send({currentPassword: "password", email: "taken-over@example.com"})
1332
+ .expect(403);
1333
+ expect(locked.body.message).not.toBe("The current password is incorrect.");
1334
+
1335
+ const reloaded = await reloadNotAdmin();
1336
+ expect(reloaded?.email).toBe("notAdmin@example.com");
1337
+ });
1338
+
1339
+ it("changes the email with the right current password and notifies the old address", async () => {
1340
+ const res = await agent
1341
+ .patch("/auth/me")
1342
+ .set("authorization", `Bearer ${token}`)
1343
+ .send({currentPassword: "password", email: "renamed@example.com"})
1344
+ .expect(200);
1345
+ expect(res.body.data.email).toBe("renamed@example.com");
1346
+ expect(res.body.data.currentPassword).toBeUndefined();
1347
+
1348
+ const reloaded = await reloadNotAdmin();
1349
+ expect(reloaded?.email).toBe("renamed@example.com");
1350
+ expect(reloaded?.currentPassword).toBeUndefined();
1351
+ expect(reloaded?.tokenEpoch ?? 0).toBe(0);
1352
+
1353
+ expect(sentMail).toHaveLength(1);
1354
+ const [notice] = sentMail;
1355
+ expect(notice.to).toBe("notAdmin@example.com");
1356
+ expect(notice.sensitive).toBe(true);
1357
+ expect(notice.text).not.toContain("renamed@example.com");
1358
+ expect(notice.text).toContain("r***@e***.com");
1359
+ expect(notice.text).toContain("support");
1360
+ expect(`${notice.text} ${notice.html ?? ""}`).not.toMatch(/https?:|token=/i);
1361
+
1362
+ // The new address now signs in with the same password.
1363
+ await agent
1364
+ .post("/auth/login")
1365
+ .send({email: "renamed@example.com", password: "password"})
1366
+ .expect(200);
1367
+ });
1368
+
1369
+ it("accepts an unchanged email echoed back without a password", async () => {
1370
+ await agent
1371
+ .patch("/auth/me")
1372
+ .set("authorization", `Bearer ${token}`)
1373
+ .send({email: " NOTADMIN@example.com ", name: "Renamed"})
1374
+ .expect(200);
1375
+
1376
+ const reloaded = await reloadNotAdmin();
1377
+ expect(reloaded?.name).toBe("Renamed");
1378
+ expect(sentMail).toHaveLength(0);
1379
+ });
1380
+
1381
+ it("returns 400 for a user with no password to confirm", async () => {
1382
+ const passwordless = await UserModel.create({
1383
+ email: "github-only@example.com",
1384
+ name: "GitHub Only",
1385
+ });
1386
+ const passwordlessToken = await signToken(String(passwordless._id));
1387
+
1388
+ const res = await agent
1389
+ .patch("/auth/me")
1390
+ .set("authorization", `Bearer ${passwordlessToken}`)
1391
+ .send({currentPassword: "anything", email: "moved@example.com"})
1392
+ .expect(400);
1393
+ expect(res.body.message).toContain("Set a password");
1394
+
1395
+ const reloaded = await UserModel.findById(passwordless._id).lean();
1396
+ expect((reloaded as unknown as {email?: string})?.email).toBe("github-only@example.com");
1397
+ });
1398
+
1399
+ it("verifies a passwordless app user against the Better Auth credential", async () => {
1400
+ const checked: Array<{password: string; userId: string}> = [];
1401
+ const betterAuthAgent = buildAgent({
1402
+ sendMail: async (message) => {
1403
+ sentMail.push(message);
1404
+ },
1405
+ verifyBetterAuthPassword: async (user, password) => {
1406
+ checked.push({password, userId: String(user._id)});
1407
+ return password === "better-auth-password" ? "verified" : "wrong";
1408
+ },
1409
+ });
1410
+ const betterAuthUser = await UserModel.create({
1411
+ email: "better-auth@example.com",
1412
+ name: "Better Auth",
1413
+ });
1414
+ const betterAuthToken = await signToken(String(betterAuthUser._id));
1415
+
1416
+ await betterAuthAgent
1417
+ .patch("/auth/me")
1418
+ .set("authorization", `Bearer ${betterAuthToken}`)
1419
+ .send({currentPassword: "wrong-password", email: "moved@example.com"})
1420
+ .expect(403);
1421
+ await betterAuthAgent
1422
+ .patch("/auth/me")
1423
+ .set("authorization", `Bearer ${betterAuthToken}`)
1424
+ .send({currentPassword: "better-auth-password", email: "moved@example.com"})
1425
+ .expect(200);
1426
+
1427
+ expect(checked).toEqual([
1428
+ {password: "wrong-password", userId: String(betterAuthUser._id)},
1429
+ {password: "better-auth-password", userId: String(betterAuthUser._id)},
1430
+ ]);
1431
+ const reloaded = await UserModel.findById(betterAuthUser._id).lean();
1432
+ expect((reloaded as unknown as {email?: string})?.email).toBe("moved@example.com");
1433
+ expect(sentMail.map((message) => message.to)).toEqual(["better-auth@example.com"]);
1434
+ });
1435
+
1436
+ it("completes the change and logs a warning when no mail sender is configured", async () => {
1437
+ const warnSpy = spyOn(logger, "warn");
1438
+ const noMailAgent = buildAgent({});
1439
+
1440
+ await noMailAgent
1441
+ .patch("/auth/me")
1442
+ .set("authorization", `Bearer ${token}`)
1443
+ .send({currentPassword: "password", email: "renamed@example.com"})
1444
+ .expect(200);
1445
+
1446
+ const reloaded = await reloadNotAdmin();
1447
+ expect(reloaded?.email).toBe("renamed@example.com");
1448
+ expect(warnSpy.mock.calls.some((call) => String(call[0]).includes("email change notice"))).toBe(
1449
+ true
1450
+ );
1451
+ warnSpy.mockRestore();
1452
+ });
1453
+ });
1454
+
1455
+ // A user schema that declares the identity-binding fields Better Auth and GitHub linking add.
1456
+ const identityUserSchema = new Schema({
1457
+ admin: {default: false, description: "Admin flag", type: Boolean},
1458
+ betterAuthId: {description: "Better Auth user id", type: String},
1459
+ email: {description: "Email", type: String},
1460
+ name: {description: "Name", type: String},
1461
+ oauthProvider: {description: "Social provider", type: String},
1462
+ tokenEpoch: {default: 0, description: "Refresh token epoch", type: Number},
1463
+ });
1464
+ identityUserSchema.plugin(
1465
+ passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
1466
+ {usernameCaseInsensitive: true, usernameField: "email"}
1467
+ );
1468
+ identityUserSchema.plugin(githubUserPlugin);
1469
+ const IdentityUserModel =
1470
+ (mongoose.models.AuthIdentityUser as mongoose.Model<Record<string, unknown>> | undefined) ??
1471
+ mongoose.model("AuthIdentityUser", identityUserSchema);
1472
+
1473
+ describe("self-service identity and credential fields", () => {
1474
+ const identityFields = {
1475
+ attempts: 0,
1476
+ betterAuthId: "victim-better-auth-id",
1477
+ disabled: false,
1478
+ githubAvatarUrl: "https://example.com/avatar.png",
1479
+ githubId: "gh-victim-1",
1480
+ githubProfileUrl: "https://example.com/victim",
1481
+ githubUsername: "victim",
1482
+ hash: "attacker-hash",
1483
+ last: new Date(0).toISOString(),
1484
+ oauthProvider: "github",
1485
+ salt: "attacker-salt",
1486
+ };
1487
+ let agent: TestAgent;
1488
+
1489
+ beforeEach(async () => {
1490
+ await IdentityUserModel.deleteMany({});
1491
+ const app = new TerrenoApp({
1492
+ configureApp: () => {},
1493
+ skipListen: true,
1494
+ userModel: IdentityUserModel as unknown as AuthUserModel,
1495
+ }).build();
1496
+ agent = supertest.agent(app);
1497
+ });
1498
+
1499
+ it("drops identity-binding and credential fields from self-service bodies", () => {
1500
+ expect(stripPrivilegedUserFields({...identityFields, name: "Someone"}, "test")).toEqual({
1501
+ name: "Someone",
1502
+ });
1503
+ });
1504
+
1505
+ it("blocks the privileged fields plus identity and credential fields", () => {
1506
+ expect([...SELF_SERVICE_BLOCKED_USER_FIELDS]).toEqual([
1507
+ ...PRIVILEGED_USER_FIELDS,
1508
+ "betterAuthId",
1509
+ "githubId",
1510
+ "githubUsername",
1511
+ "githubProfileUrl",
1512
+ "githubAvatarUrl",
1513
+ "oauthProvider",
1514
+ "hash",
1515
+ "salt",
1516
+ "attempts",
1517
+ "last",
1518
+ "disabled",
1519
+ ]);
1520
+ });
1521
+
1522
+ it("does not let anonymous signup bind another person's credentials", async () => {
1523
+ await agent
1524
+ .post("/auth/signup")
1525
+ .send({...identityFields, email: "signup-binder@example.com", password: "Password123!"})
1526
+ .expect(200);
1527
+
1528
+ const created = await IdentityUserModel.findOne({email: "signup-binder@example.com"}).lean();
1529
+ assert.isUndefined(created?.betterAuthId);
1530
+ assert.isUndefined(created?.githubId);
1531
+ assert.isUndefined(created?.githubUsername);
1532
+ assert.isUndefined(created?.oauthProvider);
1533
+ });
1534
+
1535
+ it("does not let PATCH /auth/me bind credentials or overwrite the password hash", async () => {
1536
+ const signup = await agent
1537
+ .post("/auth/signup")
1538
+ .send({email: "patch-binder@example.com", password: "Password123!"})
1539
+ .expect(200);
1540
+ const token = signup.body.data.token as string;
1541
+ const before = await IdentityUserModel.findOne({email: "patch-binder@example.com"})
1542
+ .select("+hash +salt")
1543
+ .lean();
1544
+
1545
+ await agent
1546
+ .patch("/auth/me")
1547
+ .set("authorization", `Bearer ${token}`)
1548
+ .send({...identityFields, name: "Renamed"})
1549
+ .expect(200);
1550
+
1551
+ const after = await IdentityUserModel.findOne({email: "patch-binder@example.com"})
1552
+ .select("+hash +salt")
1553
+ .lean();
1554
+ assert.equal(after?.name, "Renamed");
1555
+ assert.isUndefined(after?.betterAuthId);
1556
+ assert.isUndefined(after?.githubId);
1557
+ assert.isUndefined(after?.oauthProvider);
1558
+ assert.equal(after?.hash, before?.hash);
1559
+ assert.equal(after?.salt, before?.salt);
1560
+ await agent
1561
+ .post("/auth/login")
1562
+ .send({email: "patch-binder@example.com", password: "Password123!"})
1563
+ .expect(200);
1564
+ });
1565
+ });
1566
+
1567
+ describe("PATCH /auth/me password changes", () => {
1568
+ let agent: TestAgent;
1569
+
1570
+ beforeEach(async () => {
1571
+ await setupTestData();
1572
+ const app = new TerrenoApp({
1573
+ configureApp: () => {},
1574
+ skipListen: true,
1575
+ userModel: UserModel as unknown as AuthUserModel,
1576
+ }).build();
1577
+ agent = supertest.agent(app);
1578
+ });
1579
+
1580
+ it("rejects a password in the profile body instead of reporting success", async () => {
1581
+ const login = await agent
1582
+ .post("/auth/login")
1583
+ .send({email: "notAdmin@example.com", password: "password"})
1584
+ .expect(200);
1585
+ const token = login.body.data.token as string;
1586
+
1587
+ for (const body of [
1588
+ {password: "brand-new-password-1"},
1589
+ {newPassword: "brand-new-password-1"},
1590
+ ]) {
1591
+ const res = await agent
1592
+ .patch("/auth/me")
1593
+ .set("authorization", `Bearer ${token}`)
1594
+ .send({...body, name: "Should Not Save"});
1595
+ expect(res.status).toBe(400);
1596
+ }
1597
+
1598
+ const reloaded = await UserModel.findOne({email: "notAdmin@example.com"}).lean();
1599
+ expect((reloaded as unknown as {name?: string})?.name).toBe("Not Admin");
1600
+ await agent
1601
+ .post("/auth/login")
1602
+ .send({email: "notAdmin@example.com", password: "password"})
1603
+ .expect(200);
1604
+ });
1605
+ });
1606
+
1178
1607
  describe("Secret prefix authorization bypass", () => {
1179
1608
  let app: express.Application;
1180
1609
  let agent: TestAgent;
@@ -1416,6 +1845,95 @@ describe("login error and disabled user paths", () => {
1416
1845
  });
1417
1846
  });
1418
1847
 
1848
+ describe("disabled users on the legacy JWT stack", () => {
1849
+ let app: express.Application;
1850
+ let token: string;
1851
+ let refreshToken: string;
1852
+ let userId: string;
1853
+
1854
+ beforeEach(async () => {
1855
+ setSystemTime();
1856
+ await setupTestData();
1857
+ app = new TerrenoApp({
1858
+ configureApp: (router: express.Router) => {
1859
+ router.use(
1860
+ "/food",
1861
+ modelRouter(FoodModel, {
1862
+ permissions: {
1863
+ create: [Permissions.IsAuthenticated],
1864
+ delete: [],
1865
+ list: [Permissions.IsAuthenticated],
1866
+ read: [Permissions.IsAuthenticated],
1867
+ update: [],
1868
+ },
1869
+ })
1870
+ );
1871
+ },
1872
+ skipListen: true,
1873
+ userModel: UserModel as unknown as AuthUserModel,
1874
+ }).build();
1875
+ const loginRes = await supertest(app)
1876
+ .post("/auth/login")
1877
+ .send({email: "notAdmin@example.com", password: "password"})
1878
+ .expect(200);
1879
+ ({refreshToken, token, userId} = loginRes.body.data);
1880
+ assert.isString(refreshToken);
1881
+ await UserModel.findByIdAndUpdate(userId, {disabled: true});
1882
+ });
1883
+
1884
+ afterEach(() => {
1885
+ setSystemTime();
1886
+ });
1887
+
1888
+ it("rejects the access JWT under a non-Bearer authorization scheme", async () => {
1889
+ await supertest(app).get("/auth/me").set("authorization", `Secret ${token}`).expect(401);
1890
+ });
1891
+
1892
+ it("rejects a modelRouter create sent with a non-Bearer authorization scheme", async () => {
1893
+ await supertest(app)
1894
+ .post("/food")
1895
+ .set("authorization", `Secret ${token}`)
1896
+ .send({calories: 1, name: "disabled-user-food"})
1897
+ .expect(401);
1898
+ const count = await FoodModel.countDocuments({name: "disabled-user-food"});
1899
+ expect(count).toBe(0);
1900
+ });
1901
+
1902
+ it("rejects the jwt cookie when the decode middleware is skipped", async () => {
1903
+ const cookieApp = getBaseServer();
1904
+ cookieApp.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
1905
+ req.cookies = {jwt: token};
1906
+ next();
1907
+ });
1908
+ setupAuth(cookieApp, UserModel as unknown as AuthUserModel);
1909
+ addMeRoutes(cookieApp, UserModel as unknown as AuthUserModel);
1910
+ cookieApp.use(apiUnauthorizedMiddleware);
1911
+ await supertest(cookieApp).get("/auth/me").set("authorization", "Secret not-a-jwt").expect(401);
1912
+ });
1913
+
1914
+ it("refuses to log in a disabled user", async () => {
1915
+ const res = await supertest(app)
1916
+ .post("/auth/login")
1917
+ .send({email: "notAdmin@example.com", password: "password"})
1918
+ .expect(401);
1919
+ expect(res.body.data?.token).toBeUndefined();
1920
+ });
1921
+
1922
+ it("refuses to refresh tokens for a disabled user", async () => {
1923
+ const res = await supertest(app).post("/auth/refresh_token").send({refreshToken}).expect(401);
1924
+ expect(res.body.data?.token).toBeUndefined();
1925
+ });
1926
+
1927
+ it("still authenticates an enabled user's Bearer token", async () => {
1928
+ await UserModel.findByIdAndUpdate(userId, {disabled: false});
1929
+ const res = await supertest(app)
1930
+ .get("/auth/me")
1931
+ .set("authorization", `Bearer ${token}`)
1932
+ .expect(200);
1933
+ expect(res.body.data.email).toBe("notAdmin@example.com");
1934
+ });
1935
+ });
1936
+
1419
1937
  describe("PATCH /me route edge cases", () => {
1420
1938
  let app: express.Application;
1421
1939
  let agent: TestAgent;