@terreno/api 0.31.0 → 56.0.0-beta.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 (250) hide show
  1. package/CHANGELOG.md +122 -2
  2. package/LICENSE +202 -21
  3. package/dist/api.d.ts +12 -3
  4. package/dist/api.js +110 -361
  5. package/dist/auth.d.ts +26 -0
  6. package/dist/auth.js +100 -1
  7. package/dist/betterAuth.d.ts +5 -0
  8. package/dist/betterAuthSetup.d.ts +1 -15
  9. package/dist/betterAuthSetup.js +29 -8
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/docLoader.js +12 -9
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.js +29 -1
  14. package/dist/expressServer.js +5 -11
  15. package/dist/githubAuth.js +4 -1
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +29 -1
  18. package/dist/middleware.d.ts +7 -0
  19. package/dist/middleware.js +16 -1
  20. package/dist/openApiCompat.d.ts +10 -1
  21. package/dist/openApiCompat.js +115 -47
  22. package/dist/permissions.d.ts +27 -0
  23. package/dist/permissions.js +42 -1
  24. package/dist/plugins.d.ts +15 -3
  25. package/dist/plugins.js +36 -6
  26. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  27. package/dist/realtime/changeStreamWatcher.js +542 -137
  28. package/dist/realtime/realtimeApp.d.ts +3 -1
  29. package/dist/realtime/realtimeApp.js +75 -27
  30. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  31. package/dist/realtime/sessionRevalidation.js +438 -0
  32. package/dist/realtime/socketAuth.d.ts +97 -0
  33. package/dist/realtime/socketAuth.js +272 -0
  34. package/dist/realtime/socketUser.d.ts +54 -0
  35. package/dist/realtime/socketUser.js +75 -5
  36. package/dist/realtime/types.d.ts +40 -0
  37. package/dist/secretProviders.d.ts +23 -0
  38. package/dist/secretProviders.js +9 -3
  39. package/dist/sync/executors.d.ts +198 -0
  40. package/dist/sync/executors.js +670 -0
  41. package/dist/sync/loadHarness.js +807 -0
  42. package/dist/sync/models.d.ts +216 -0
  43. package/dist/sync/models.js +644 -0
  44. package/dist/sync/mutationHandler.d.ts +97 -0
  45. package/dist/sync/mutationHandler.js +886 -0
  46. package/dist/sync/registry.d.ts +73 -0
  47. package/dist/sync/registry.js +223 -0
  48. package/dist/sync/routes.d.ts +62 -0
  49. package/dist/sync/routes.js +936 -0
  50. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  51. package/dist/sync/scripts/compactTombstones.js +270 -0
  52. package/dist/sync/serialize.d.ts +20 -0
  53. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  54. package/dist/sync/socketHandlers.d.ts +54 -0
  55. package/dist/sync/socketHandlers.js +470 -0
  56. package/dist/sync/streams.d.ts +85 -0
  57. package/dist/sync/streams.js +221 -0
  58. package/dist/sync/syncApp.d.ts +29 -0
  59. package/dist/sync/syncApp.js +44 -0
  60. package/dist/sync/syncBatch.d.ts +71 -0
  61. package/dist/sync/syncBatch.js +252 -0
  62. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  63. package/dist/sync/syncSeqPlugin.js +903 -0
  64. package/dist/sync/types.d.ts +254 -0
  65. package/dist/sync/types.js +9 -0
  66. package/dist/terrenoApp.js +90 -27
  67. package/dist/tests/models.d.ts +11 -27
  68. package/dist/tests/models.js +3 -5
  69. package/dist/tests/testHelper.d.ts +3 -9
  70. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  71. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  72. package/package.json +10 -8
  73. package/src/__tests__/openApiCompat.test.ts +20 -0
  74. package/src/actions.test.ts +12 -19
  75. package/src/actions.ts +2 -2
  76. package/src/api.coverage.test.ts +9 -7
  77. package/src/api.errorPaths.test.ts +1 -47
  78. package/src/api.test.ts +12 -0
  79. package/src/api.ts +98 -317
  80. package/src/auth.test.ts +128 -176
  81. package/src/auth.ts +109 -0
  82. package/src/betterAuth.ts +6 -0
  83. package/src/betterAuthSetup.test.ts +34 -0
  84. package/src/betterAuthSetup.ts +27 -8
  85. package/src/configurationPlugin.ts +2 -2
  86. package/src/consentApp.test.ts +12 -12
  87. package/src/docLoader.ts +3 -1
  88. package/src/errors.ts +33 -0
  89. package/src/expressServer.test.ts +7 -1
  90. package/src/expressServer.ts +5 -11
  91. package/src/githubAuth.ts +3 -1
  92. package/src/index.ts +42 -0
  93. package/src/middleware.test.ts +40 -1
  94. package/src/middleware.ts +15 -0
  95. package/src/models/versionConfig.ts +1 -1
  96. package/src/openApiBuilder.test.ts +9 -24
  97. package/src/openApiCompat.ts +99 -45
  98. package/src/openApiValidator.test.ts +0 -41
  99. package/src/permissions.test.ts +75 -1
  100. package/src/permissions.ts +49 -0
  101. package/src/plugins.test.ts +54 -14
  102. package/src/plugins.ts +47 -9
  103. package/src/populate.test.ts +16 -25
  104. package/src/realtime/changeStreamWatcher.ts +552 -114
  105. package/src/realtime/realtime.test.ts +157 -239
  106. package/src/realtime/realtimeApp.ts +80 -19
  107. package/src/realtime/sessionRevalidation.test.ts +423 -0
  108. package/src/realtime/sessionRevalidation.ts +273 -0
  109. package/src/realtime/socketAuth.test.ts +355 -0
  110. package/src/realtime/socketAuth.ts +228 -0
  111. package/src/realtime/socketUser.ts +69 -0
  112. package/src/realtime/types.ts +40 -0
  113. package/src/secretProviders.test.ts +7 -1
  114. package/src/secretProviders.ts +15 -3
  115. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  116. package/src/sync/executors.test.ts +882 -0
  117. package/src/sync/executors.ts +703 -0
  118. package/src/sync/integration.test.ts +1160 -0
  119. package/src/sync/loadHarness.ts +618 -0
  120. package/src/sync/models.ts +640 -0
  121. package/src/sync/mutationHandler.test.ts +1252 -0
  122. package/src/sync/mutationHandler.ts +850 -0
  123. package/src/sync/registry.ts +232 -0
  124. package/src/sync/routes.ts +812 -0
  125. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  126. package/src/sync/scripts/compactTombstones.ts +145 -0
  127. package/src/sync/serialize.ts +48 -0
  128. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  129. package/src/sync/socketHandlers.ts +320 -0
  130. package/src/sync/streams.ts +188 -0
  131. package/src/sync/sync.test.ts +582 -0
  132. package/src/sync/syncApp.ts +44 -0
  133. package/src/sync/syncBatch.ts +219 -0
  134. package/src/sync/syncFrontier.test.ts +494 -0
  135. package/src/sync/syncPhaseC.test.ts +718 -0
  136. package/src/sync/syncRoutes.test.ts +865 -0
  137. package/src/sync/syncSeqPlugin.ts +738 -0
  138. package/src/sync/syncSocket.test.ts +1440 -0
  139. package/src/sync/types.ts +270 -0
  140. package/src/terrenoApp.ts +37 -17
  141. package/src/tests/bunSetup.ts +8 -0
  142. package/src/tests/models.ts +6 -8
  143. package/tsconfig.json +4 -4
  144. package/tsconfig.typedoc.json +7 -1
  145. package/dist/__tests__/openApiCompat.test.js +0 -317
  146. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  147. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  148. package/dist/actions.openApi.test.d.ts +0 -1
  149. package/dist/actions.openApi.test.js +0 -253
  150. package/dist/actions.test.d.ts +0 -1
  151. package/dist/actions.test.js +0 -1087
  152. package/dist/api.arrayOperations.test.d.ts +0 -1
  153. package/dist/api.arrayOperations.test.js +0 -878
  154. package/dist/api.asyncHandler.test.d.ts +0 -1
  155. package/dist/api.asyncHandler.test.js +0 -236
  156. package/dist/api.coverage.test.d.ts +0 -1
  157. package/dist/api.coverage.test.js +0 -192
  158. package/dist/api.errorPaths.test.d.ts +0 -1
  159. package/dist/api.errorPaths.test.js +0 -887
  160. package/dist/api.errors.test.d.ts +0 -1
  161. package/dist/api.errors.test.js +0 -185
  162. package/dist/api.hooks.test.d.ts +0 -1
  163. package/dist/api.hooks.test.js +0 -950
  164. package/dist/api.query.test.d.ts +0 -1
  165. package/dist/api.query.test.js +0 -948
  166. package/dist/api.test.d.ts +0 -1
  167. package/dist/api.test.js +0 -2820
  168. package/dist/auth.compile.test.d.ts +0 -1
  169. package/dist/auth.compile.test.js +0 -201
  170. package/dist/auth.coverage.test.d.ts +0 -1
  171. package/dist/auth.coverage.test.js +0 -202
  172. package/dist/auth.test.d.ts +0 -1
  173. package/dist/auth.test.js +0 -2286
  174. package/dist/betterAuth.test.d.ts +0 -1
  175. package/dist/betterAuth.test.js +0 -181
  176. package/dist/betterAuthApp.test.d.ts +0 -1
  177. package/dist/betterAuthApp.test.js +0 -242
  178. package/dist/betterAuthSetup.test.d.ts +0 -1
  179. package/dist/betterAuthSetup.test.js +0 -762
  180. package/dist/config.test.d.ts +0 -1
  181. package/dist/config.test.js +0 -353
  182. package/dist/configuration.test.d.ts +0 -1
  183. package/dist/configuration.test.js +0 -980
  184. package/dist/configurationPlugin.test.d.ts +0 -1
  185. package/dist/configurationPlugin.test.js +0 -827
  186. package/dist/consentApp.test.d.ts +0 -1
  187. package/dist/consentApp.test.js +0 -1411
  188. package/dist/docLoader.test.d.ts +0 -1
  189. package/dist/docLoader.test.js +0 -137
  190. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  191. package/dist/envConfigurationPlugin.test.js +0 -369
  192. package/dist/errors.test.d.ts +0 -1
  193. package/dist/errors.test.js +0 -607
  194. package/dist/expressServer.test.d.ts +0 -1
  195. package/dist/expressServer.test.js +0 -1249
  196. package/dist/githubAuth.test.d.ts +0 -1
  197. package/dist/githubAuth.test.js +0 -1142
  198. package/dist/httpClient.test.d.ts +0 -1
  199. package/dist/httpClient.test.js +0 -1471
  200. package/dist/logger.test.d.ts +0 -1
  201. package/dist/logger.test.js +0 -685
  202. package/dist/middleware.test.d.ts +0 -1
  203. package/dist/middleware.test.js +0 -241
  204. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  205. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  206. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  207. package/dist/notifiers/slackNotifier.test.js +0 -297
  208. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  209. package/dist/notifiers/zoomNotifier.test.js +0 -373
  210. package/dist/openApi.test.d.ts +0 -1
  211. package/dist/openApi.test.js +0 -620
  212. package/dist/openApiBuilder.test.d.ts +0 -1
  213. package/dist/openApiBuilder.test.js +0 -599
  214. package/dist/openApiEtag.test.d.ts +0 -1
  215. package/dist/openApiEtag.test.js +0 -86
  216. package/dist/openApiValidator.test.d.ts +0 -1
  217. package/dist/openApiValidator.test.js +0 -795
  218. package/dist/permissions.middleware.test.d.ts +0 -1
  219. package/dist/permissions.middleware.test.js +0 -308
  220. package/dist/permissions.test.d.ts +0 -1
  221. package/dist/permissions.test.js +0 -439
  222. package/dist/plugins.test.d.ts +0 -1
  223. package/dist/plugins.test.js +0 -902
  224. package/dist/populate.test.d.ts +0 -1
  225. package/dist/populate.test.js +0 -370
  226. package/dist/realtime/realtime.test.d.ts +0 -10
  227. package/dist/realtime/realtime.test.js +0 -4213
  228. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  229. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  230. package/dist/requestContext.test.d.ts +0 -1
  231. package/dist/requestContext.test.js +0 -412
  232. package/dist/scriptRunner.test.d.ts +0 -1
  233. package/dist/scriptRunner.test.js +0 -386
  234. package/dist/secretProviders.test.d.ts +0 -1
  235. package/dist/secretProviders.test.js +0 -726
  236. package/dist/syncConsents.test.d.ts +0 -1
  237. package/dist/syncConsents.test.js +0 -522
  238. package/dist/terrenoApp.test.d.ts +0 -1
  239. package/dist/terrenoApp.test.js +0 -489
  240. package/dist/tests/bunSetup.d.ts +0 -1
  241. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  242. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  243. package/dist/tests/testEnv.d.ts +0 -0
  244. package/dist/tests/testEnv.js +0 -6
  245. package/dist/transformers.test.d.ts +0 -1
  246. package/dist/transformers.test.js +0 -423
  247. package/dist/utils.test.d.ts +0 -1
  248. package/dist/utils.test.js +0 -242
  249. package/src/realtime/realtimeAppSetup.test.ts +0 -161
  250. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/auth.test.ts CHANGED
@@ -1,19 +1,20 @@
1
1
  // noExplicitAny: test mock typing
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
4
- import express from "express";
4
+ import type express from "express";
5
5
  import type jwt from "jsonwebtoken";
6
6
  import supertest from "supertest";
7
7
  import type TestAgent from "supertest/lib/agent";
8
8
 
9
9
  import {modelRouter} from "./api";
10
10
  import {
11
- type UserModel as AuthUserModel,
12
11
  addAuthRoutes,
13
12
  addMeRoutes,
14
13
  generateTokens,
14
+ type HasSetPassword,
15
+ MAX_PASSWORD_LENGTH,
16
+ setPasswordForUser,
15
17
  setupAuth,
16
- signupUser,
17
18
  } from "./auth";
18
19
  import {logger} from "./logger";
19
20
  import {Permissions} from "./permissions";
@@ -1369,6 +1370,40 @@ describe("decodeJWTMiddleware error paths", () => {
1369
1370
  const res = await agent.get("/food").set("authorization", "Bearer undefined").expect(200);
1370
1371
  expect(res.body.data).toBeDefined();
1371
1372
  });
1373
+
1374
+ // D1: the JWT-vs-non-JWT fallthrough now decodes the token's header/payload
1375
+ // structure (jwt.decode with complete: true) instead of counting dots, so it is
1376
+ // robust to opaque tokens that coincidentally contain two dots and to malformed
1377
+ // strings that happen to have three dot-delimited segments without real JWT
1378
+ // structure.
1379
+ it("falls through (200, no 401) for an opaque non-JWT bearer token with two dots", async () => {
1380
+ // An opaque token shaped like a Better Auth session id — has exactly two dots
1381
+ // but is not base64url-encoded JSON in any segment.
1382
+ const res = await agent
1383
+ .get("/food")
1384
+ .set("authorization", "Bearer not.a.jwt-at-all")
1385
+ .expect(200);
1386
+ expect(res.body.data).toBeDefined();
1387
+ });
1388
+
1389
+ it("falls through (200, no 401) for a three-dot string with no real JWT header/payload structure", async () => {
1390
+ // Exactly three dot-delimited segments (would have been treated as "a JWT" by
1391
+ // the old dot-counting check) but none are valid base64url JSON.
1392
+ const res = await agent.get("/food").set("authorization", "Bearer abc.def.ghi").expect(200);
1393
+ expect(res.body.data).toBeDefined();
1394
+ });
1395
+
1396
+ it("returns 401 for a genuinely malformed JWT-shaped token (decodable header, bad signature)", async () => {
1397
+ const jwtLib = await import("jsonwebtoken");
1398
+ // A well-formed JWT (decodable header/payload) but signed with the wrong
1399
+ // secret — jwt.verify throws, and jwt.decode succeeds (it is a real JWT), so
1400
+ // this must still 401 rather than fall through.
1401
+ const badToken = jwtLib.sign({id: "someone"}, "wrong-secret", {
1402
+ issuer: process.env.TOKEN_ISSUER,
1403
+ });
1404
+ const res = await agent.get("/food").set("authorization", `Bearer ${badToken}`);
1405
+ expect(res.status).toBe(401);
1406
+ });
1372
1407
  });
1373
1408
 
1374
1409
  describe("signup disabled", () => {
@@ -1400,205 +1435,122 @@ describe("signup disabled", () => {
1400
1435
  });
1401
1436
  });
1402
1437
 
1403
- describe("signupUser postCreate failures", () => {
1404
- it("wraps and rethrows errors thrown by user.postCreate", async () => {
1405
- let saveCalled = false;
1406
- const failingUser = {
1407
- postCreate: async () => {
1408
- throw new Error("postCreate failed");
1409
- },
1410
- save: async () => {
1411
- saveCalled = true;
1438
+ describe("setPasswordForUser", () => {
1439
+ it("resolves when a callback-based setPassword invokes the callback with no error", async () => {
1440
+ let receivedPassword: string | undefined;
1441
+ const user: HasSetPassword = {
1442
+ setPassword: (password, callback) => {
1443
+ receivedPassword = password;
1444
+ callback?.();
1412
1445
  },
1413
1446
  };
1414
- const fakeModel = {
1415
- register: async () => failingUser,
1416
- } as unknown as Parameters<typeof signupUser>[0];
1417
1447
 
1418
- await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
1419
- "postCreate failed"
1420
- );
1421
- expect(saveCalled).toBe(false);
1448
+ await setPasswordForUser(user, "new-password");
1449
+ expect(receivedPassword).toBe("new-password");
1422
1450
  });
1423
- });
1424
1451
 
1425
- describe("auth error paths when the user lookup fails", () => {
1426
- let app: express.Application;
1427
- let agent: TestAgent;
1428
- let admin: {_id: {toString: () => string}};
1452
+ it("resolves when setPassword returns a promise", async () => {
1453
+ let receivedPassword: string | undefined;
1454
+ const user: HasSetPassword = {
1455
+ setPassword: async (password) => {
1456
+ receivedPassword = password;
1457
+ },
1458
+ };
1429
1459
 
1430
- beforeEach(async () => {
1431
- setSystemTime();
1432
- const testData = await setupTestData();
1433
- admin = testData.users.admin;
1434
- app = new TerrenoApp({
1435
- configureApp: () => {},
1436
- skipListen: true,
1437
- userModel: UserModel as any,
1438
- }).build();
1439
- agent = supertest.agent(app);
1460
+ await setPasswordForUser(user, "promise-password");
1461
+ expect(receivedPassword).toBe("promise-password");
1440
1462
  });
1441
1463
 
1442
- afterEach(() => {
1443
- setSystemTime();
1444
- });
1464
+ it("rejects when the callback is invoked with an error", async () => {
1465
+ const user: HasSetPassword = {
1466
+ setPassword: (_password, callback) => {
1467
+ callback?.(new Error("boom"));
1468
+ },
1469
+ };
1445
1470
 
1446
- it("responds with an error when userModel.findById throws during authentication", async () => {
1447
- const jwtLib = (await import("jsonwebtoken")).default;
1448
- const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
1449
- issuer: process.env.TOKEN_ISSUER,
1450
- });
1451
- const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
1452
- throw new Error("database unavailable");
1453
- });
1454
- try {
1455
- const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
1456
- expect(res.status).toBeGreaterThanOrEqual(400);
1457
- } finally {
1458
- findSpy.mockRestore();
1459
- }
1471
+ await expect(setPasswordForUser(user, "pw")).rejects.toThrow("boom");
1460
1472
  });
1461
1473
 
1462
- it("calls next(err) when the local login strategy errors", async () => {
1463
- type Authenticator = (
1464
- username: string,
1465
- password: string,
1466
- done: (err: Error | null) => void
1467
- ) => void;
1468
- const authSpy = spyOn(
1469
- UserModel as unknown as {authenticate: () => Authenticator},
1470
- "authenticate"
1471
- ).mockReturnValue((_username, _password, done) => {
1472
- done(new Error("strategy failure"));
1473
- });
1474
- try {
1475
- const errApp = new TerrenoApp({
1476
- configureApp: () => {},
1477
- skipListen: true,
1478
- userModel: UserModel as any,
1479
- }).build();
1480
- const errAgent = supertest.agent(errApp);
1481
- const res = await errAgent
1482
- .post("/auth/login")
1483
- .send({email: "notAdmin@example.com", password: "password"});
1484
- expect(res.status).toBeGreaterThanOrEqual(400);
1485
- } finally {
1486
- authSpy.mockRestore();
1487
- }
1474
+ it("rejects when setPassword throws synchronously", async () => {
1475
+ const user: HasSetPassword = {
1476
+ setPassword: () => {
1477
+ throw new Error("sync failure");
1478
+ },
1479
+ };
1480
+
1481
+ await expect(setPasswordForUser(user, "pw")).rejects.toThrow("sync failure");
1488
1482
  });
1489
- });
1490
1483
 
1491
- describe("cookie based JWT extraction", () => {
1492
- afterEach(() => {
1493
- setSystemTime();
1484
+ it("rejects with a timeout when setPassword never settles", async () => {
1485
+ const user: HasSetPassword = {
1486
+ setPassword: () => {
1487
+ // Never invokes the callback and returns nothing (no promise).
1488
+ },
1489
+ };
1490
+
1491
+ await expect(setPasswordForUser(user, "pw", 10)).rejects.toThrow(
1492
+ "Timed out while setting password"
1493
+ );
1494
1494
  });
1495
1495
 
1496
- it("authenticates /auth/me from a jwt cookie", async () => {
1497
- setSystemTime();
1498
- const {users} = await setupTestData();
1499
- const jwtLib = (await import("jsonwebtoken")).default;
1500
- const token = jwtLib.sign({id: String(users.admin._id)}, process.env.TOKEN_SECRET as string, {
1501
- issuer: process.env.TOKEN_ISSUER,
1502
- });
1503
- const app = getBaseServer();
1504
- // Stand in for cookie-parser: the extractor prefers req.cookies.jwt over the auth header.
1505
- app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
1506
- req.cookies = {jwt: token};
1507
- next();
1508
- });
1509
- setupAuth(app, UserModel as unknown as AuthUserModel);
1510
- addMeRoutes(app, UserModel as unknown as AuthUserModel);
1496
+ it("rejects passwords longer than MAX_PASSWORD_LENGTH without calling setPassword", async () => {
1497
+ let called = false;
1498
+ const user: HasSetPassword = {
1499
+ setPassword: (_password, callback) => {
1500
+ called = true;
1501
+ callback?.();
1502
+ },
1503
+ };
1504
+ const tooLong = "x".repeat(MAX_PASSWORD_LENGTH + 1);
1511
1505
 
1512
- const res = await supertest.agent(app).get("/auth/me").expect(200);
1513
- expect(res.body.data.email).toBe("admin@example.com");
1506
+ await expect(setPasswordForUser(user, tooLong)).rejects.toThrow(
1507
+ `Password must be at most ${MAX_PASSWORD_LENGTH} characters`
1508
+ );
1509
+ expect(called).toBe(false);
1514
1510
  });
1515
- });
1516
1511
 
1517
- describe("auth logging outside of the test environment", () => {
1518
- const originalNodeEnv = process.env.NODE_ENV;
1512
+ it("accepts a password exactly at MAX_PASSWORD_LENGTH", async () => {
1513
+ let receivedPassword: string | undefined;
1514
+ const user: HasSetPassword = {
1515
+ setPassword: (password, callback) => {
1516
+ receivedPassword = password;
1517
+ callback?.();
1518
+ },
1519
+ };
1520
+ const atLimit = "x".repeat(MAX_PASSWORD_LENGTH);
1519
1521
 
1520
- afterEach(() => {
1521
- setSystemTime();
1522
- process.env.NODE_ENV = originalNodeEnv;
1522
+ await setPasswordForUser(user, atLimit);
1523
+ expect(receivedPassword).toBe(atLimit);
1523
1524
  });
1524
1525
 
1525
- it("logs JWT setup and successful logins when NODE_ENV is not test", async () => {
1526
- setSystemTime();
1527
- await setupTestData();
1528
- process.env.NODE_ENV = "development";
1529
- const debugSpy = spyOn(logger, "debug");
1526
+ it("logs an audit line with the admin id and target user id when audit context is provided", async () => {
1530
1527
  const infoSpy = spyOn(logger, "info");
1531
- try {
1532
- const app = getBaseServer();
1533
- setupAuth(app, UserModel as unknown as AuthUserModel);
1534
- addAuthRoutes(app, UserModel as unknown as AuthUserModel);
1535
-
1536
- const res = await supertest
1537
- .agent(app)
1538
- .post("/auth/login")
1539
- .send({email: "notAdmin@example.com", password: "password"})
1540
- .expect(200);
1541
- expect(res.body.data.token).toBeDefined();
1542
- expect(
1543
- debugSpy.mock.calls.some(([message]) =>
1544
- String(message).includes("Setting up JWT Authentication")
1545
- )
1546
- ).toBe(true);
1547
- expect(
1548
- infoSpy.mock.calls.some(([message]) => String(message).includes("User logged in"))
1549
- ).toBe(true);
1550
- } finally {
1551
- debugSpy.mockRestore();
1552
- infoSpy.mockRestore();
1553
- }
1554
- });
1555
- });
1528
+ infoSpy.mockClear();
1529
+ const user: HasSetPassword = {
1530
+ _id: "target-user-id",
1531
+ setPassword: (_password, callback) => callback?.(),
1532
+ };
1556
1533
 
1557
- describe("/me routes with an already populated req.user", () => {
1558
- const buildApp = (
1559
- user: {_id?: string; id?: string} | undefined,
1560
- foundUser: unknown
1561
- ): express.Application => {
1562
- const app = express();
1563
- app.use(express.json());
1564
- app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
1565
- req.user = user as unknown as express.Request["user"];
1566
- next();
1567
- });
1568
- const stubUserModel = {
1569
- findById: async () => foundUser,
1570
- } as unknown as AuthUserModel;
1571
- addMeRoutes(app, stubUserModel);
1572
- return app;
1573
- };
1574
-
1575
- it("returns 401 from GET /auth/me when the request user has no id", async () => {
1576
- await supertest
1577
- .agent(buildApp({_id: "abc"}, null))
1578
- .get("/auth/me")
1579
- .expect(401);
1580
- });
1534
+ await setPasswordForUser(user, "new-password", undefined, {adminId: "admin-id-123"});
1581
1535
 
1582
- it("returns 401 from PATCH /auth/me when the request user has no id", async () => {
1583
- await supertest
1584
- .agent(buildApp({_id: "abc"}, null))
1585
- .patch("/auth/me")
1586
- .send({name: "Updated"})
1587
- .expect(401);
1536
+ expect(infoSpy).toHaveBeenCalledTimes(1);
1537
+ const [message] = infoSpy.mock.calls[0] as [string];
1538
+ expect(message).toContain("admin-id-123");
1539
+ expect(message).toContain("target-user-id");
1540
+ expect(message).not.toContain("new-password");
1541
+ infoSpy.mockRestore();
1588
1542
  });
1589
1543
 
1590
- it("returns 404 from GET /auth/me when the user record no longer exists", async () => {
1591
- await supertest
1592
- .agent(buildApp({id: "abc"}, null))
1593
- .get("/auth/me")
1594
- .expect(404);
1595
- });
1544
+ it("does not log an audit line when no audit context is provided", async () => {
1545
+ const infoSpy = spyOn(logger, "info");
1546
+ infoSpy.mockClear();
1547
+ const user: HasSetPassword = {
1548
+ setPassword: (_password, callback) => callback?.(),
1549
+ };
1596
1550
 
1597
- it("returns 404 from PATCH /auth/me when the user record no longer exists", async () => {
1598
- await supertest
1599
- .agent(buildApp({id: "abc"}, null))
1600
- .patch("/auth/me")
1601
- .send({name: "Updated"})
1602
- .expect(404);
1551
+ await setPasswordForUser(user, "new-password");
1552
+
1553
+ expect(infoSpy).not.toHaveBeenCalled();
1554
+ infoSpy.mockRestore();
1603
1555
  });
1604
1556
  });
package/src/auth.ts CHANGED
@@ -131,6 +131,102 @@ export const signupUser = async (
131
131
  }
132
132
  };
133
133
 
134
+ /** A user document exposing passport-local-mongoose's `setPassword`. */
135
+ export interface HasSetPassword {
136
+ _id?: unknown;
137
+ id?: string;
138
+ setPassword: (
139
+ password: string,
140
+ callback?: (error?: unknown) => void
141
+ ) => Promise<unknown> | unknown;
142
+ }
143
+
144
+ /** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
145
+ export const MAX_PASSWORD_LENGTH = 256;
146
+
147
+ /** Optional audit context for {@link setPasswordForUser} — never includes the password itself. */
148
+ export interface SetPasswordAuditContext {
149
+ /** The admin performing the change, when set via an admin-only route. */
150
+ adminId?: unknown;
151
+ }
152
+
153
+ /**
154
+ * Sets a password on a passport-local-mongoose user document, returning a Promise regardless of
155
+ * whether the installed version of `setPassword` is callback- or promise-based. Newer versions
156
+ * return a promise while older ones only invoke the callback; this helper normalizes both and
157
+ * rejects after `timeoutMs` (default 15s) if neither settles. Call `user.save()` afterwards to
158
+ * persist the new hash/salt.
159
+ *
160
+ * Rejects synchronously (before touching `setPassword`) when `password` exceeds
161
+ * {@link MAX_PASSWORD_LENGTH} characters. When `audit.adminId` is provided (an admin-initiated
162
+ * password change), logs a `logger.info` audit line with the admin id, target user id, and
163
+ * timestamp — NEVER the password itself.
164
+ */
165
+ export const setPasswordForUser = async (
166
+ user: HasSetPassword,
167
+ password: string,
168
+ timeoutMs = 15_000,
169
+ audit?: SetPasswordAuditContext
170
+ ): Promise<void> => {
171
+ if (password.length > MAX_PASSWORD_LENGTH) {
172
+ throw new APIError({
173
+ status: 400,
174
+ title: `Password must be at most ${MAX_PASSWORD_LENGTH} characters`,
175
+ });
176
+ }
177
+ if (audit?.adminId !== undefined) {
178
+ const targetUserId = user._id ?? user.id ?? "unknown";
179
+ logger.info(
180
+ `[auth] Admin ${String(audit.adminId)} set password for user ${String(targetUserId)} ` +
181
+ `at ${DateTime.now().toISO()}`
182
+ );
183
+ }
184
+ await new Promise<void>((resolve, reject) => {
185
+ let isSettled = false;
186
+ const timeout = setTimeout(() => {
187
+ if (isSettled) {
188
+ return;
189
+ }
190
+ isSettled = true;
191
+ reject(new Error("Timed out while setting password"));
192
+ }, timeoutMs);
193
+
194
+ const resolveOnce = (): void => {
195
+ if (isSettled) {
196
+ return;
197
+ }
198
+ isSettled = true;
199
+ clearTimeout(timeout);
200
+ resolve();
201
+ };
202
+
203
+ const rejectOnce = (error: unknown): void => {
204
+ if (isSettled) {
205
+ return;
206
+ }
207
+ isSettled = true;
208
+ clearTimeout(timeout);
209
+ reject(error);
210
+ };
211
+
212
+ try {
213
+ const maybePromise = user.setPassword(password, (error?: unknown) => {
214
+ if (error) {
215
+ rejectOnce(error);
216
+ return;
217
+ }
218
+ resolveOnce();
219
+ });
220
+
221
+ if (maybePromise && typeof (maybePromise as Promise<unknown>).then === "function") {
222
+ (maybePromise as Promise<unknown>).then(resolveOnce).catch(rejectOnce);
223
+ }
224
+ } catch (error) {
225
+ rejectOnce(error);
226
+ }
227
+ });
228
+ };
229
+
134
230
  /**
135
231
  * Generates both an access token (JWT) and a refresh token for a given user.
136
232
  *
@@ -322,6 +418,19 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
322
418
  issuer: process.env.TOKEN_ISSUER,
323
419
  }) as jwt.JwtPayload;
324
420
  } catch (error: unknown) {
421
+ // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
422
+ // token) is not ours to reject — fall through so a later auth layer (Better
423
+ // Auth session middleware) or the route's own permissions can handle it.
424
+ // Detect this by decoding the token's header/payload structure (D1) rather
425
+ // than counting dot-delimited segments: an opaque token can coincidentally
426
+ // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
427
+ // this same check for the wrong reason — `jwt.decode` parses the actual
428
+ // base64url JSON structure of each segment, which dot-counting cannot.
429
+ // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
430
+ // client's token-refresh flow is preserved.
431
+ if (jwt.decode(token, {complete: true}) === null) {
432
+ return next();
433
+ }
325
434
  const userText = req.user?._id ? ` for user ${req.user._id} ` : "";
326
435
  const expiredAt =
327
436
  error && typeof error === "object" && "expiredAt" in error
package/src/betterAuth.ts CHANGED
@@ -43,6 +43,12 @@ export interface BetterAuthConfig {
43
43
  */
44
44
  trustedOrigins?: string[];
45
45
 
46
+ /**
47
+ * Allow credential cookies when the frontend and API are hosted on different sites.
48
+ * Enables `SameSite=None; Secure` cookie attributes. Keep disabled for local HTTP.
49
+ */
50
+ crossDomainCookies?: boolean;
51
+
46
52
  /**
47
53
  * Base path for Better Auth routes.
48
54
  * @default "/api/auth"
@@ -1,6 +1,7 @@
1
1
  // noExplicitAny: test mock typing
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
4
+ import {assert} from "chai";
4
5
  import express from "express";
5
6
  import {MongoMemoryServer} from "mongodb-memory-server";
6
7
  import mongoose, {Schema} from "mongoose";
@@ -101,6 +102,39 @@ describe("createBetterAuth", () => {
101
102
  expect(auth.api).toBeDefined();
102
103
  });
103
104
 
105
+ it("sets cross-site session cookies when crossDomainCookies is enabled", async () => {
106
+ await setup;
107
+ const origin = "https://frontend.example.com";
108
+ const config: BetterAuthConfig = {
109
+ baseURL: "https://api.example.com",
110
+ crossDomainCookies: true,
111
+ enabled: true,
112
+ secret: "test-secret-at-least-32-characters-long",
113
+ trustedOrigins: [origin],
114
+ };
115
+ const auth = createBetterAuth({config, mongoClient: getClient()});
116
+
117
+ const response = await auth.handler(
118
+ new Request("https://api.example.com/api/auth/sign-up/email", {
119
+ body: JSON.stringify({
120
+ email: "cross-domain-cookie@example.com",
121
+ name: "Cross Domain",
122
+ password: "testpassword123",
123
+ }),
124
+ headers: {
125
+ "Content-Type": "application/json",
126
+ Origin: origin,
127
+ },
128
+ method: "POST",
129
+ })
130
+ );
131
+ const setCookie = response.headers.get("set-cookie") ?? "";
132
+
133
+ assert.isTrue(response.ok);
134
+ assert.include(setCookie.toLowerCase(), "samesite=none");
135
+ assert.include(setCookie.toLowerCase(), "secure");
136
+ });
137
+
104
138
  it("creates instance with social providers", async () => {
105
139
  await setup;
106
140
  const config: BetterAuthConfig = {
@@ -8,6 +8,7 @@
8
8
  import {betterAuth} from "better-auth";
9
9
  import {mongodbAdapter} from "better-auth/adapters/mongodb";
10
10
  import {toNodeHandler} from "better-auth/node";
11
+ import {bearer} from "better-auth/plugins";
11
12
  import type {Application, NextFunction, Request, Response} from "express";
12
13
  import mongoose from "mongoose";
13
14
  import type {UserModel} from "./auth";
@@ -86,12 +87,27 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
86
87
  }
87
88
 
88
89
  const auth = betterAuth({
90
+ advanced: config.crossDomainCookies
91
+ ? {
92
+ defaultCookieAttributes: {
93
+ httpOnly: true,
94
+ sameSite: "none",
95
+ secure: true,
96
+ },
97
+ }
98
+ : undefined,
89
99
  basePath,
90
100
  baseURL,
91
101
  database: mongodbAdapter(mongoClient.db()),
92
102
  emailAndPassword: {
93
103
  enabled: true,
94
104
  },
105
+ // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
106
+ // instead of the signed session cookie. Required for cross-origin/native clients and for
107
+ // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
108
+ // token as a bearer header) — without it, a raw session token cannot be validated and
109
+ // socket auth silently fails (the sync client shows perpetually "offline").
110
+ plugins: [bearer()],
95
111
  secret,
96
112
  session: {
97
113
  cookieCache: {
@@ -103,7 +119,10 @@ export const createBetterAuth = (options: CreateBetterAuthOptions): BetterAuthIn
103
119
  trustedOrigins: config.trustedOrigins ?? [],
104
120
  });
105
121
 
106
- return auth as BetterAuthInstance;
122
+ // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
123
+ // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
124
+ // BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
125
+ return auth as unknown as BetterAuthInstance;
107
126
  };
108
127
 
109
128
  /**
@@ -173,7 +192,6 @@ export const createBetterAuthSessionMiddleware = (
173
192
  // Loose shape used when mutating Mongoose user documents during Better Auth sync.
174
193
  // The fields are added by the consumer's user schema (via baseUserPlugin or similar).
175
194
  interface MutableUserDoc {
176
- admin?: boolean;
177
195
  email?: string;
178
196
  name?: string;
179
197
  betterAuthId?: string;
@@ -186,7 +204,9 @@ export const syncBetterAuthUser = async (
186
204
  userModel: UserModel,
187
205
  betterAuthUser: BetterAuthUser,
188
206
  oauthProvider?: string
189
- ): Promise<MutableUserDoc> => {
207
+ // noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
208
+ // biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
209
+ ): Promise<any> => {
190
210
  try {
191
211
  const existingUser = (await findOneOrNoneFor(userModel, {
192
212
  betterAuthId: betterAuthUser.id,
@@ -218,17 +238,16 @@ export const syncBetterAuthUser = async (
218
238
 
219
239
  // Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
220
240
  const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
221
- const UserDocumentConstructor = userModel as unknown as new (
222
- doc: Record<string, unknown>
223
- ) => MutableUserDoc;
224
- const newUser = new UserDocumentConstructor({
241
+ // noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
242
+ // biome-ignore lint/suspicious/noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
243
+ const newUser = new (userModel as any)({
225
244
  ...useAsId,
226
245
  admin: false,
227
246
  betterAuthId: betterAuthUser.id,
228
247
  email: betterAuthUser.email,
229
248
  name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
230
249
  oauthProvider: oauthProvider || null,
231
- });
250
+ }) as MutableUserDoc;
232
251
  await newUser.save();
233
252
  logger.info(`Created new user from Better Auth: ${newUser.id}`);
234
253
  return newUser;
@@ -344,7 +344,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
344
344
  const updated = await this.findOneAndUpdate(
345
345
  singletonFilter,
346
346
  {$set: setFields},
347
- {returnDocument: "after", runValidators: true}
347
+ {new: true, runValidators: true}
348
348
  );
349
349
  if (updated) {
350
350
  return updated;
@@ -356,7 +356,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
356
356
  return this.findOneAndUpdate(
357
357
  singletonFilter,
358
358
  {$set: setFields},
359
- {returnDocument: "after", runValidators: true}
359
+ {new: true, runValidators: true}
360
360
  ).orFail();
361
361
  };
362
362