@terreno/api 0.25.0 → 0.27.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 (114) hide show
  1. package/.ai/guidelines/core.md +1 -0
  2. package/README.md +4 -3
  3. package/dist/__tests__/openApiCompat.test.js +8 -2
  4. package/dist/__tests__/versionCheckPlugin.test.js +15 -0
  5. package/dist/actions.openApi.test.js +1 -0
  6. package/dist/actions.test.js +1 -0
  7. package/dist/api.arrayOperations.test.js +1 -0
  8. package/dist/api.coverage.test.d.ts +1 -0
  9. package/dist/api.coverage.test.js +191 -0
  10. package/dist/api.errorPaths.test.d.ts +1 -0
  11. package/dist/api.errorPaths.test.js +278 -0
  12. package/dist/api.errors.test.js +1 -0
  13. package/dist/api.hooks.test.js +1 -0
  14. package/dist/api.js +160 -167
  15. package/dist/api.query.test.js +1 -0
  16. package/dist/api.test.js +1 -0
  17. package/dist/auth.js +1 -0
  18. package/dist/auth.test.js +122 -0
  19. package/dist/betterAuthApp.test.js +1 -2
  20. package/dist/betterAuthSetup.js +1 -0
  21. package/dist/betterAuthSetup.test.js +1 -0
  22. package/dist/configuration.test.js +1 -0
  23. package/dist/configurationApp.js +1 -0
  24. package/dist/configurationPlugin.test.js +80 -0
  25. package/dist/consentApp.test.js +1 -0
  26. package/dist/docLoader.js +1 -3
  27. package/dist/envConfigurationPlugin.js +1 -0
  28. package/dist/example.js +3 -2
  29. package/dist/expressServer.js +6 -6
  30. package/dist/expressServer.test.js +23 -0
  31. package/dist/githubAuth.js +2 -0
  32. package/dist/githubAuth.test.js +1 -0
  33. package/dist/index.d.ts +9 -2
  34. package/dist/index.js +28 -3
  35. package/dist/logger.test.js +107 -0
  36. package/dist/openApi.test.js +52 -0
  37. package/dist/openApiBuilder.js +2 -1
  38. package/dist/openApiBuilder.test.js +3 -2
  39. package/dist/openApiValidator.js +1 -0
  40. package/dist/openApiValidator.test.js +41 -0
  41. package/dist/permissions.middleware.test.js +1 -0
  42. package/dist/permissions.test.js +1 -0
  43. package/dist/plugins.js +8 -0
  44. package/dist/plugins.test.js +1 -0
  45. package/dist/populate.js +4 -2
  46. package/dist/populate.test.js +1 -0
  47. package/dist/realtime/realtime.test.js +13 -3
  48. package/dist/realtime/types.d.ts +1 -1
  49. package/dist/requestContext.test.js +28 -0
  50. package/dist/terrenoApp.js +1 -0
  51. package/dist/tests/createTestData.js +11 -6
  52. package/dist/tests/fixtures/compileAuthEntry.js +1 -1
  53. package/dist/tests/models.js +1 -0
  54. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
  55. package/package.json +7 -7
  56. package/src/__tests__/openApiCompat.test.ts +8 -2
  57. package/src/__tests__/versionCheckPlugin.test.ts +9 -0
  58. package/src/actions.openApi.test.ts +1 -0
  59. package/src/actions.test.ts +1 -0
  60. package/src/api.arrayOperations.test.ts +1 -0
  61. package/src/api.coverage.test.ts +121 -0
  62. package/src/api.errorPaths.test.ts +171 -0
  63. package/src/api.errors.test.ts +1 -0
  64. package/src/api.hooks.test.ts +1 -0
  65. package/src/api.query.test.ts +1 -0
  66. package/src/api.test.ts +1 -0
  67. package/src/api.ts +13 -9
  68. package/src/auth.test.ts +91 -2
  69. package/src/auth.ts +6 -0
  70. package/src/betterAuthApp.test.ts +3 -3
  71. package/src/betterAuthSetup.test.ts +1 -0
  72. package/src/betterAuthSetup.ts +3 -0
  73. package/src/configuration.test.ts +1 -0
  74. package/src/configurationApp.ts +2 -0
  75. package/src/configurationPlugin.test.ts +46 -1
  76. package/src/consentApp.test.ts +1 -0
  77. package/src/docLoader.ts +1 -2
  78. package/src/envConfigurationPlugin.ts +2 -0
  79. package/src/example.ts +3 -2
  80. package/src/expressServer.test.ts +13 -0
  81. package/src/expressServer.ts +5 -3
  82. package/src/githubAuth.test.ts +1 -0
  83. package/src/githubAuth.ts +2 -0
  84. package/src/index.ts +40 -2
  85. package/src/logger.test.ts +78 -0
  86. package/src/openApi.test.ts +54 -0
  87. package/src/openApiBuilder.test.ts +7 -6
  88. package/src/openApiBuilder.ts +2 -1
  89. package/src/openApiValidator.test.ts +64 -0
  90. package/src/openApiValidator.ts +1 -0
  91. package/src/permissions.middleware.test.ts +1 -0
  92. package/src/permissions.test.ts +1 -0
  93. package/src/plugins.test.ts +1 -0
  94. package/src/plugins.ts +9 -0
  95. package/src/populate.test.ts +1 -0
  96. package/src/populate.ts +4 -2
  97. package/src/realtime/realtime.test.ts +13 -3
  98. package/src/realtime/realtimeApp.ts +1 -0
  99. package/src/realtime/registry.ts +1 -0
  100. package/src/realtime/types.ts +1 -2
  101. package/src/requestContext.test.ts +32 -0
  102. package/src/terrenoApp.ts +1 -0
  103. package/src/tests/createTestData.ts +11 -6
  104. package/src/tests/fixtures/compileAuthEntry.ts +1 -1
  105. package/src/tests/models.ts +1 -0
  106. package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
  107. package/tsconfig.json +3 -3
  108. package/dist/notifiers/index.d.ts +0 -3
  109. package/dist/notifiers/index.js +0 -19
  110. package/dist/realtime/index.d.ts +0 -6
  111. package/dist/realtime/index.js +0 -27
  112. package/src/notifiers/index.ts +0 -3
  113. package/src/realtime/index.ts +0 -34
  114. /package/{types.d.ts → src/types.d.ts} +0 -0
@@ -0,0 +1,171 @@
1
+ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
2
+ import * as Sentry from "@sentry/bun";
3
+ import {assert} from "chai";
4
+ import type express from "express";
5
+ import mongoose from "mongoose";
6
+ import supertest from "supertest";
7
+ import type TestAgent from "supertest/lib/agent";
8
+
9
+ import {type ModelRouterOptions, modelRouter} from "./api";
10
+ import {addAuthRoutes, setupAuth} from "./auth";
11
+ import {Permissions} from "./permissions";
12
+ import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
13
+
14
+ type SetupAuthUserModel = Parameters<typeof setupAuth>[1];
15
+ const authUserModel = UserModel as unknown as SetupAuthUserModel;
16
+
17
+ interface RestorableSpy {
18
+ mockRestore?: () => void;
19
+ }
20
+
21
+ const anyPermissions = {
22
+ create: [Permissions.IsAny],
23
+ delete: [Permissions.IsAny],
24
+ list: [Permissions.IsAny],
25
+ read: [Permissions.IsAny],
26
+ update: [Permissions.IsAny],
27
+ };
28
+
29
+ describe("modelRouter error paths", () => {
30
+ let app: express.Application;
31
+ let server: TestAgent;
32
+
33
+ beforeEach(async () => {
34
+ await setupDb();
35
+ app = getBaseServer();
36
+ setupAuth(app, authUserModel);
37
+ addAuthRoutes(app, authUserModel);
38
+ });
39
+
40
+ afterEach(() => {
41
+ // Restore any spies installed on the shared FoodModel / Sentry.
42
+ (FoodModel.find as unknown as RestorableSpy).mockRestore?.();
43
+ (FoodModel.findById as unknown as RestorableSpy).mockRestore?.();
44
+ (Sentry.captureMessage as unknown as RestorableSpy).mockRestore?.();
45
+ });
46
+
47
+ const mountFood = (options: Partial<ModelRouterOptions<Food>> = {}): void => {
48
+ app.use(
49
+ "/food",
50
+ modelRouter(FoodModel, {
51
+ allowAnonymous: true,
52
+ permissions: anyPermissions,
53
+ ...options,
54
+ })
55
+ );
56
+ server = supertest(app);
57
+ };
58
+
59
+ it("wraps populate failures on create in a Populate error", async () => {
60
+ mountFood({populatePaths: [{fields: ["email"], path: "ownerId"}]});
61
+
62
+ // Creation succeeds, but the follow-up populate query rejects.
63
+ const rejectingQuery = {
64
+ exec: () => Promise.reject(new Error("populate exploded")),
65
+ populate() {
66
+ return this;
67
+ },
68
+ };
69
+ spyOn(FoodModel, "findById").mockReturnValue(
70
+ rejectingQuery as unknown as ReturnType<typeof FoodModel.findById>
71
+ );
72
+
73
+ const res = await server
74
+ .post("/food")
75
+ .send({calories: 5, name: "Broccoli", ownerId: new mongoose.Types.ObjectId()})
76
+ .expect(400);
77
+ assert.include(res.body.title, "Populate error");
78
+ assert.include(res.body.title, "populate exploded");
79
+ });
80
+
81
+ it("wraps list query failures in a List error", async () => {
82
+ mountFood();
83
+
84
+ const rejectingQuery = {
85
+ exec: () => Promise.reject(new Error("list exploded")),
86
+ limit() {
87
+ return this;
88
+ },
89
+ };
90
+ spyOn(FoodModel, "find").mockReturnValue(
91
+ rejectingQuery as unknown as ReturnType<typeof FoodModel.find>
92
+ );
93
+
94
+ const res = await server.get("/food").expect(500);
95
+ assert.include(res.body.title, "List error");
96
+ });
97
+
98
+ it("swallows Sentry failures when warning about truncated unpaginated lists", async () => {
99
+ mountFood({defaultLimit: 1});
100
+ const ownerId = new mongoose.Types.ObjectId();
101
+ await FoodModel.create([
102
+ {calories: 1, name: "A", ownerId} as Partial<Food>,
103
+ {calories: 2, name: "B", ownerId} as Partial<Food>,
104
+ ]);
105
+
106
+ const captureSpy = spyOn(Sentry, "captureMessage").mockImplementation(() => {
107
+ throw new Error("sentry down");
108
+ });
109
+
110
+ const res = await server.get("/food").expect(200);
111
+ // The extra document is sliced off so only `limit` rows are returned.
112
+ assert.lengthOf(res.body.data, 1);
113
+ assert.isTrue(res.body.more);
114
+ assert.isAbove(captureSpy.mock.calls.length, 0);
115
+ });
116
+
117
+ it("wraps deleteOne failures for models without soft delete", async () => {
118
+ const brittleSchema = new mongoose.Schema(
119
+ {name: {description: "The name", type: String}},
120
+ {strict: "throw"}
121
+ );
122
+ brittleSchema.pre("deleteOne", {document: true, query: false}, () => {
123
+ throw new Error("deleteOne exploded");
124
+ });
125
+ const BrittleModel = mongoose.model(`BrittleDelete_${Date.now()}`, brittleSchema);
126
+
127
+ app.use(
128
+ "/brittle",
129
+ modelRouter(BrittleModel, {allowAnonymous: true, permissions: anyPermissions})
130
+ );
131
+ server = supertest(app);
132
+
133
+ const created = await BrittleModel.create({name: "doomed"});
134
+ const res = await server.delete(`/brittle/${created._id}`).expect(400);
135
+ assert.include(res.body.title, "deleteOne exploded");
136
+ });
137
+
138
+ it("wraps non-APIError transformer failures during array operations", async () => {
139
+ mountFood({
140
+ transformer: {
141
+ transform: () => {
142
+ throw new Error("transform exploded");
143
+ },
144
+ },
145
+ });
146
+ const food = await FoodModel.create({
147
+ calories: 1,
148
+ name: "Tagged",
149
+ ownerId: new mongoose.Types.ObjectId(),
150
+ } as Partial<Food>);
151
+
152
+ const res = await server.post(`/food/${food._id}/tags`).send({tags: "vegetable"}).expect(403);
153
+ assert.include(res.body.title, "transform exploded");
154
+ });
155
+
156
+ it("wraps save failures during array operations", async () => {
157
+ mountFood();
158
+ const food = await FoodModel.create({
159
+ calories: 1,
160
+ name: "Eaten",
161
+ ownerId: new mongoose.Types.ObjectId(),
162
+ } as Partial<Food>);
163
+
164
+ // eatenBy is an ObjectId array, so pushing an unparseable id fails on save.
165
+ const res = await server
166
+ .post(`/food/${food._id}/eatenBy`)
167
+ .send({eatenBy: "not-an-object-id"})
168
+ .expect(400);
169
+ assert.include(res.body.title, "PATCH Pre Update error");
170
+ });
171
+ });
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {describe, expect, it} from "bun:test";
3
4
  import mongoose from "mongoose";
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import * as Sentry from "@sentry/bun";
package/src/api.test.ts CHANGED
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  // biome-ignore-all lint/suspicious/noImplicitAnyLet: test mock typing
3
4
  import {beforeEach, describe, expect, it} from "bun:test";
package/src/api.ts CHANGED
@@ -58,6 +58,7 @@ export interface JSONObject {
58
58
  export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
59
59
 
60
60
  export const addPopulateToQuery = (
61
+ // noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
61
62
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
62
63
  builtQuery: mongoose.Query<any[], any, Record<string, never>, any>,
63
64
  populatePaths?: PopulatePath[]
@@ -710,6 +711,7 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
710
711
 
711
712
  if (options.populatePaths) {
712
713
  try {
714
+ // noExplicitAny: mongoose Query type varies based on populatePaths
713
715
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
714
716
  let populateQuery: any = model.findById(data._id);
715
717
  populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
@@ -1079,6 +1081,7 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1079
1081
  }
1080
1082
 
1081
1083
  if (options.populatePaths) {
1084
+ // noExplicitAny: mongoose Query type varies based on populatePaths
1082
1085
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
1083
1086
  let populateQuery: any = model.findById(doc._id);
1084
1087
  populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
@@ -1192,11 +1195,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1192
1195
  })
1193
1196
  );
1194
1197
 
1195
- async function arrayOperation(
1198
+ const arrayOperation = async (
1196
1199
  req: Request,
1197
1200
  res: Response,
1198
1201
  operation: "POST" | "PATCH" | "DELETE"
1199
- ) {
1202
+ ) => {
1200
1203
  // TODO Combine array operations and .patch(), as they are very similar.
1201
1204
 
1202
1205
  if (!(await checkPermissions("update", options.permissions.update, req.user))) {
@@ -1347,19 +1350,19 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
1347
1350
  return res.json({
1348
1351
  data: serialize<T>(req, options, doc as unknown as Document<unknown, unknown, unknown> & T),
1349
1352
  });
1350
- }
1353
+ };
1351
1354
 
1352
- async function arrayPost(req: Request, res: Response) {
1355
+ const arrayPost = async (req: Request, res: Response) => {
1353
1356
  return arrayOperation(req, res, "POST");
1354
- }
1357
+ };
1355
1358
 
1356
- async function arrayPatch(req: Request, res: Response) {
1359
+ const arrayPatch = async (req: Request, res: Response) => {
1357
1360
  return arrayOperation(req, res, "PATCH");
1358
- }
1361
+ };
1359
1362
 
1360
- async function arrayDelete(req: Request, res: Response) {
1363
+ const arrayDelete = async (req: Request, res: Response) => {
1361
1364
  return arrayOperation(req, res, "DELETE");
1362
- }
1365
+ };
1363
1366
  // Set up routes for managing array fields. Check if there any array fields to add this for.
1364
1367
  if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
1365
1368
  router.post(
@@ -1439,6 +1442,7 @@ export interface AsyncHandlerOptions {
1439
1442
  * }));
1440
1443
  * ```
1441
1444
  */
1445
+ // noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
1442
1446
  // biome-ignore lint/suspicious/noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
1443
1447
  type AsyncHandlerFn = (req: any, res: Response, next: NextFunction) => Promise<unknown> | unknown;
1444
1448
 
package/src/auth.test.ts CHANGED
@@ -1,12 +1,13 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
- import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
3
+ import {afterEach, beforeEach, describe, expect, it, setSystemTime, spyOn} from "bun:test";
3
4
  import type express from "express";
4
5
  import type jwt from "jsonwebtoken";
5
6
  import supertest from "supertest";
6
7
  import type TestAgent from "supertest/lib/agent";
7
8
 
8
9
  import {modelRouter} from "./api";
9
- import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth} from "./auth";
10
+ import {addAuthRoutes, addMeRoutes, generateTokens, setupAuth, signupUser} from "./auth";
10
11
  import {Permissions} from "./permissions";
11
12
  import {getCurrentRequestContext} from "./requestContext";
12
13
  import {TerrenoApp} from "./terrenoApp";
@@ -1390,3 +1391,91 @@ describe("signup disabled", () => {
1390
1391
  expect(res.status).toBe(404);
1391
1392
  });
1392
1393
  });
1394
+
1395
+ describe("signupUser postCreate failures", () => {
1396
+ it("wraps and rethrows errors thrown by user.postCreate", async () => {
1397
+ let saveCalled = false;
1398
+ const failingUser = {
1399
+ postCreate: async () => {
1400
+ throw new Error("postCreate failed");
1401
+ },
1402
+ save: async () => {
1403
+ saveCalled = true;
1404
+ },
1405
+ };
1406
+ const fakeModel = {
1407
+ register: async () => failingUser,
1408
+ } as unknown as Parameters<typeof signupUser>[0];
1409
+
1410
+ await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
1411
+ "postCreate failed"
1412
+ );
1413
+ expect(saveCalled).toBe(false);
1414
+ });
1415
+ });
1416
+
1417
+ describe("auth error paths when the user lookup fails", () => {
1418
+ let app: express.Application;
1419
+ let agent: TestAgent;
1420
+ let admin: {_id: {toString: () => string}};
1421
+
1422
+ beforeEach(async () => {
1423
+ setSystemTime();
1424
+ const testData = await setupTestData();
1425
+ admin = testData.users.admin;
1426
+ app = new TerrenoApp({
1427
+ configureApp: () => {},
1428
+ skipListen: true,
1429
+ userModel: UserModel as any,
1430
+ }).build();
1431
+ agent = supertest.agent(app);
1432
+ });
1433
+
1434
+ afterEach(() => {
1435
+ setSystemTime();
1436
+ });
1437
+
1438
+ it("responds with an error when userModel.findById throws during authentication", async () => {
1439
+ const jwtLib = (await import("jsonwebtoken")).default;
1440
+ const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
1441
+ issuer: process.env.TOKEN_ISSUER,
1442
+ });
1443
+ const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
1444
+ throw new Error("database unavailable");
1445
+ });
1446
+ try {
1447
+ const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
1448
+ expect(res.status).toBeGreaterThanOrEqual(400);
1449
+ } finally {
1450
+ findSpy.mockRestore();
1451
+ }
1452
+ });
1453
+
1454
+ it("calls next(err) when the local login strategy errors", async () => {
1455
+ type Authenticator = (
1456
+ username: string,
1457
+ password: string,
1458
+ done: (err: Error | null) => void
1459
+ ) => void;
1460
+ const authSpy = spyOn(
1461
+ UserModel as unknown as {authenticate: () => Authenticator},
1462
+ "authenticate"
1463
+ ).mockReturnValue((_username, _password, done) => {
1464
+ done(new Error("strategy failure"));
1465
+ });
1466
+ try {
1467
+ const errApp = new TerrenoApp({
1468
+ configureApp: () => {},
1469
+ skipListen: true,
1470
+ userModel: UserModel as any,
1471
+ }).build();
1472
+ const errAgent = supertest.agent(errApp);
1473
+ const res = await errAgent
1474
+ .post("/auth/login")
1475
+ .send({email: "notAdmin@example.com", password: "password"});
1476
+ expect(res.status).toBeGreaterThanOrEqual(400);
1477
+ } finally {
1478
+ authSpy.mockRestore();
1479
+ }
1480
+ });
1481
+ });
package/src/auth.ts CHANGED
@@ -41,12 +41,16 @@ export interface UserModel extends Model<User> {
41
41
  // Allows additional setup during signup. This will be passed the rest of req.body from the signup
42
42
  postCreate?: (body: Record<string, unknown>) => Promise<void>;
43
43
 
44
+ // noExplicitAny: passport-local-mongoose return types are untyped
44
45
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
45
46
  createStrategy(): any;
47
+ // noExplicitAny: passport-local-mongoose return types are untyped
46
48
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
47
49
  serializeUser(): any;
50
+ // noExplicitAny: passport-local-mongoose return types are untyped
48
51
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
49
52
  deserializeUser(): any;
53
+ // noExplicitAny: passport-local-mongoose return types are untyped
50
54
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose return types are untyped
51
55
  findByUsername(username: string, findOpts: any): any;
52
56
  }
@@ -107,6 +111,7 @@ export const signupUser = async (
107
111
  const {email: _email, password: _password, ...bodyRest} = body ?? {};
108
112
 
109
113
  try {
114
+ // noExplicitAny: passport-local-mongoose's register() is untyped
110
115
  // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's register() is untyped
111
116
  const user = await (userModel as any).register({email, ...bodyRest}, password);
112
117
 
@@ -349,6 +354,7 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
349
354
  return next();
350
355
  };
351
356
  app.use(decodeJWTMiddleware);
357
+ // noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
352
358
  // biome-ignore lint/suspicious/noExplicitAny: express 5 type for urlencoded doesn't match RequestHandler
353
359
  app.use(express.urlencoded({extended: false}) as any);
354
360
  };
@@ -1,4 +1,3 @@
1
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
1
  import {afterAll, afterEach, describe, expect, it} from "bun:test";
3
2
  import express from "express";
4
3
  import {MongoMemoryServer} from "mongodb-memory-server";
@@ -9,7 +8,6 @@ import {BetterAuthApp} from "./betterAuthApp";
9
8
 
10
9
  let conn: mongoose.Connection;
11
10
  let mongod: MongoMemoryServer;
12
- let TestUser: any;
13
11
 
14
12
  const testUserSchema = new Schema({
15
13
  admin: {default: false, type: Boolean},
@@ -19,6 +17,8 @@ const testUserSchema = new Schema({
19
17
  oauthProvider: {type: String},
20
18
  });
21
19
 
20
+ let TestUser: mongoose.Model<mongoose.InferSchemaType<typeof testUserSchema>>;
21
+
22
22
  const setup = (async () => {
23
23
  mongod = await MongoMemoryServer.create();
24
24
  conn = mongoose.createConnection(mongod.getUri());
@@ -78,7 +78,7 @@ describe("BetterAuthApp", () => {
78
78
 
79
79
  const plugin = new BetterAuthApp({
80
80
  config: makeConfig(),
81
- userModel: TestUser as UserModel,
81
+ userModel: TestUser as unknown as UserModel,
82
82
  });
83
83
 
84
84
  expect(() => plugin.register(app)).not.toThrow();
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterAll, afterEach, describe, expect, it, mock} from "bun:test";
3
4
  import express from "express";
@@ -27,6 +27,7 @@ export type BetterAuthInstance = ReturnType<typeof betterAuth>;
27
27
  */
28
28
  // Minimal shape we use from the MongoDB native client returned by mongoose connection
29
29
  export interface MongoClientLike {
30
+ // noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
30
31
  // biome-ignore lint/suspicious/noExplicitAny: the MongoDB driver Db type is opaque to this layer; it is passed straight to better-auth's adapter
31
32
  db: () => any;
32
33
  }
@@ -184,6 +185,7 @@ export const syncBetterAuthUser = async (
184
185
  userModel: UserModel,
185
186
  betterAuthUser: BetterAuthUser,
186
187
  oauthProvider?: string
188
+ // noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
187
189
  // biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
188
190
  ): Promise<any> => {
189
191
  try {
@@ -217,6 +219,7 @@ export const syncBetterAuthUser = async (
217
219
 
218
220
  // Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
219
221
  const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
222
+ // noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
220
223
  // biome-ignore lint/suspicious/noExplicitAny: userModel is generic across consumers — constructor args are runtime-validated
221
224
  const newUser = new (userModel as any)({
222
225
  ...useAsId,
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
@@ -132,6 +132,7 @@ export type ConfigurationPostUpdateHook = (
132
132
  */
133
133
  export interface ConfigurationAppOptions {
134
134
  /** The Mongoose model with configurationPlugin applied. */
135
+ // noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
135
136
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
136
137
  model: Model<any>;
137
138
  /** Base path for configuration routes. Defaults to "/configuration". */
@@ -478,6 +479,7 @@ export class ConfigurationApp implements TerrenoPlugin {
478
479
  * Top-level fields with subschemas become sections.
479
480
  * Top-level scalar fields go into a "General" section.
480
481
  */
482
+ // noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
481
483
  // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance with consumer-supplied configuration models
482
484
  private buildMetadata(_model: Model<any>, schema: Schema): ConfigurationMetaResponse {
483
485
  const sections: ConfigSectionMeta[] = [];
@@ -1,5 +1,6 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
- import {afterAll, beforeAll, beforeEach, describe, expect, it} from "bun:test";
3
+ import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
3
4
  import mongoose, {model, Schema} from "mongoose";
4
5
  import type {SecretProvider} from "./configurationPlugin";
5
6
  import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
@@ -322,6 +323,50 @@ describe("configurationPlugin", () => {
322
323
  await expect(duplicate.save()).rejects.toThrow();
323
324
  });
324
325
 
326
+ it("re-fetches the existing singleton when a concurrent create hits a 409", async () => {
327
+ if (!dbConnected) {
328
+ return;
329
+ }
330
+ const existing = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
331
+ // Simulate a race: the initial lookup misses, so getConfig attempts a create
332
+ // that the pre-save singleton guard rejects with a 409. getConfig should then
333
+ // re-fetch and return the document created by the "other process".
334
+ const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
335
+ try {
336
+ const config = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
337
+ expect(config._id.toString()).toBe(existing._id.toString());
338
+ } finally {
339
+ spy.mockRestore();
340
+ }
341
+ });
342
+
343
+ it("rethrows non-409 errors raised while creating the singleton", async () => {
344
+ if (!dbConnected) {
345
+ return;
346
+ }
347
+ const findSpy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
348
+ const saveSpy = spyOn(SimpleConfigModel.prototype, "save").mockRejectedValueOnce(
349
+ new Error("unexpected save failure")
350
+ );
351
+ try {
352
+ await expect(SimpleConfigModel.getConfig()).rejects.toThrow("unexpected save failure");
353
+ } finally {
354
+ findSpy.mockRestore();
355
+ saveSpy.mockRestore();
356
+ }
357
+ });
358
+
359
+ it("returns undefined for a dotted key that traverses a non-object value", async () => {
360
+ if (!dbConnected) {
361
+ return;
362
+ }
363
+ await SimpleConfigModel.getConfig();
364
+ // `value` is a string, so descending into `value.missing` bails out.
365
+ expect(await SimpleConfigModel.getConfig("value.missing")).toBeUndefined();
366
+ // A missing top-level segment also resolves to undefined.
367
+ expect(await SimpleConfigModel.getConfig("nope.deeper")).toBeUndefined();
368
+ });
369
+
325
370
  it("updates an existing document via updateConfig", async () => {
326
371
  if (!dbConnected) {
327
372
  return;
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
3
4
  import type express from "express";
package/src/docLoader.ts CHANGED
@@ -16,8 +16,7 @@ export const loadDocOr404 = async <T>(
16
16
  ): Promise<T> => {
17
17
  const builtQuery = model.findById(id);
18
18
  const populatedQuery = addPopulateToQuery(
19
- // biome-ignore lint/suspicious/noExplicitAny: Query types vary based on populate paths
20
- builtQuery as any,
19
+ builtQuery as unknown as Parameters<typeof addPopulateToQuery>[0],
21
20
  populatePaths
22
21
  );
23
22
  let data: T | null;
@@ -60,6 +60,7 @@ const mapToObject = (
60
60
 
61
61
  const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
62
62
  try {
63
+ // noExplicitAny: doc shape determined by consumer schema
63
64
  // biome-ignore lint/suspicious/noExplicitAny: doc shape determined by consumer schema
64
65
  const doc = (await findOneOrNoneFor(Model as Model<any>, {})) as
65
66
  | (Document & {env?: Map<string, string> | Record<string, string>})
@@ -72,6 +73,7 @@ const refreshFromDoc = async (Model: Model<unknown>): Promise<void> => {
72
73
  }
73
74
  };
74
75
 
76
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
75
77
  // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
76
78
  export const envConfigurationPlugin = (schema: Schema<any, any, any, any>): void => {
77
79
  schema.add({
package/src/example.ts CHANGED
@@ -45,8 +45,9 @@ const userSchema = new Schema<User>(
45
45
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
46
46
  );
47
47
 
48
- // biome-ignore lint/suspicious/noExplicitAny: passport-local-mongoose's plugin type is incompatible with mongoose Schema generics
49
- userSchema.plugin(passportLocalMongoose as any, {usernameField: "email"});
48
+ userSchema.plugin(passportLocalMongoose as unknown as Parameters<typeof userSchema.plugin>[0], {
49
+ usernameField: "email",
50
+ });
50
51
  userSchema.plugin(createdUpdatedPlugin);
51
52
  userSchema.plugin(isDeletedPlugin);
52
53
  userSchema.plugin(findOneOrNone);
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
3
4
  import {Writable} from "node:stream";
@@ -951,6 +952,18 @@ describe("expressServer", () => {
951
952
  expect(warnTimer).toBeDefined();
952
953
  expect(closeTimer).toBeDefined();
953
954
  });
955
+
956
+ it("terminate timeout callback reports the timeout and exits with code 2", async () => {
957
+ const func = async () => "ok";
958
+ await expect(wrapScript(func, {terminateTimeout: 100})).rejects.toThrow("__EXIT__");
959
+
960
+ const closeTimer = timerCallbacks.find((t) => t.delay === 100000);
961
+ expect(closeTimer).toBeDefined();
962
+
963
+ const runCloseTimer = closeTimer?.callback as unknown as () => Promise<void>;
964
+ await expect(runCloseTimer()).rejects.toThrow("__EXIT__");
965
+ expect(process.exit).toHaveBeenCalledWith(2);
966
+ });
954
967
  });
955
968
 
956
969
  describe("TerrenoApp error handling", () => {
@@ -8,7 +8,7 @@ import onFinished from "on-finished";
8
8
  import passport from "passport";
9
9
  import type {ModelRouterOptions} from "./api";
10
10
  import {type LoggingOptions, logger} from "./logger";
11
- import {sendToSlack} from "./notifiers";
11
+ import {sendToSlack} from "./notifiers/slackNotifier";
12
12
 
13
13
  const SLOW_READ_MAX = 200;
14
14
  const SLOW_WRITE_MAX = 500;
@@ -171,9 +171,11 @@ export interface AuthOptions {
171
171
  // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
172
172
  // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
173
173
  generateJWTPayload?: (user: any) => Record<string, unknown>;
174
- // biome-ignore lint/suspicious/noExplicitAny: see above
174
+ // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
175
+ // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
175
176
  generateTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
176
- // biome-ignore lint/suspicious/noExplicitAny: see above
177
+ // noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
178
+ // biome-ignore lint/suspicious/noExplicitAny: user shape is provided by the consumer's User model — any preserves the loose-binding contract
177
179
  generateRefreshTokenExpiration?: (user: any) => number | jwt.SignOptions["expiresIn"];
178
180
  }
179
181
 
@@ -1,3 +1,4 @@
1
+ // noExplicitAny: test mock typing
1
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
3
  import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
3
4
  import type express from "express";