@terreno/api 56.0.0-beta.0 → 57.0.0-beta.1

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 (64) hide show
  1. package/CHANGELOG.md +2 -122
  2. package/LICENSE +21 -202
  3. package/dist/api.d.ts +3 -2
  4. package/dist/auth.js +21 -25
  5. package/dist/betterAuthSetup.d.ts +15 -1
  6. package/dist/betterAuthSetup.js +4 -6
  7. package/dist/configurationPlugin.js +2 -2
  8. package/dist/expressServer.js +11 -5
  9. package/dist/githubAuth.js +1 -4
  10. package/dist/plugins.d.ts +7 -6
  11. package/dist/plugins.js +24 -8
  12. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  13. package/dist/realtime/changeStreamWatcher.js +0 -2
  14. package/dist/realtime/realtimeApp.d.ts +1 -1
  15. package/dist/realtime/realtimeApp.js +16 -8
  16. package/dist/realtime/types.d.ts +14 -0
  17. package/dist/sync/executors.js +14 -14
  18. package/dist/sync/models.js +1 -1
  19. package/dist/sync/registry.d.ts +4 -4
  20. package/dist/sync/registry.js +1 -1
  21. package/dist/sync/socketHandlers.d.ts +1 -1
  22. package/dist/sync/syncSeqPlugin.js +25 -29
  23. package/dist/tests/models.d.ts +27 -11
  24. package/dist/tests/models.js +5 -3
  25. package/dist/tests/testHelper.d.ts +9 -3
  26. package/package.json +5 -6
  27. package/src/actions.test.ts +19 -12
  28. package/src/actions.ts +2 -2
  29. package/src/api.coverage.test.ts +7 -9
  30. package/src/api.errorPaths.test.ts +47 -1
  31. package/src/api.errors.test.ts +32 -23
  32. package/src/api.ts +22 -12
  33. package/src/auth.test.ts +251 -1
  34. package/src/auth.ts +25 -23
  35. package/src/betterAuthSetup.ts +7 -7
  36. package/src/configuration.test.ts +59 -38
  37. package/src/configurationPlugin.test.ts +72 -42
  38. package/src/configurationPlugin.ts +2 -2
  39. package/src/consentApp.test.ts +12 -12
  40. package/src/expressServer.ts +11 -5
  41. package/src/githubAuth.ts +1 -3
  42. package/src/middleware.test.ts +16 -0
  43. package/src/models/versionConfig.ts +1 -1
  44. package/src/openApiBuilder.test.ts +24 -9
  45. package/src/openApiValidator.test.ts +41 -0
  46. package/src/permissions.middleware.test.ts +73 -81
  47. package/src/permissions.test.ts +35 -25
  48. package/src/plugins.test.ts +74 -29
  49. package/src/plugins.ts +29 -11
  50. package/src/populate.test.ts +25 -16
  51. package/src/realtime/changeStreamWatcher.ts +1 -4
  52. package/src/realtime/realtime.test.ts +239 -0
  53. package/src/realtime/realtimeApp.ts +15 -8
  54. package/src/realtime/realtimeAppSetup.test.ts +159 -0
  55. package/src/realtime/types.ts +14 -0
  56. package/src/secretProvidersGcpClient.test.ts +66 -0
  57. package/src/sync/executors.ts +16 -14
  58. package/src/sync/models.ts +2 -1
  59. package/src/sync/registry.ts +6 -8
  60. package/src/sync/socketHandlers.ts +1 -3
  61. package/src/sync/syncFrontier.test.ts +2 -2
  62. package/src/sync/syncSeqPlugin.test.ts +446 -0
  63. package/src/sync/syncSeqPlugin.ts +43 -51
  64. package/src/tests/models.ts +8 -6
@@ -1,22 +1,29 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {beforeEach, describe, expect, it} from "bun:test";
4
2
  import type express from "express";
5
- import {type Model, model, Schema} from "mongoose";
3
+ import {type HydratedDocument, type Model, model, Schema} from "mongoose";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
  import {
9
7
  ACTION_NAME_PATTERN,
8
+ type CollectionActionConfig,
10
9
  createActionOpenApiMiddleware,
11
10
  defineCollectionAction,
12
11
  defineInstanceAction,
13
12
  } from "./actions";
14
13
  import {modelRouter, type OpenApiMiddleware} from "./api";
15
- import {addAuthRoutes, setupAuth} from "./auth";
14
+ import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
16
15
  import {apiUnauthorizedMiddleware} from "./errors";
17
16
  import {Permissions} from "./permissions";
18
17
  import {type IsDeleted, isDeletedPlugin} from "./plugins";
19
- import {authAsUser, type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
18
+ import {
19
+ authAsUser,
20
+ type Food,
21
+ FoodModel,
22
+ getBaseServer,
23
+ setupDb,
24
+ type User,
25
+ UserModel,
26
+ } from "./tests";
20
27
  import {z} from "./zodOpenApi";
21
28
 
22
29
  interface Stuff extends IsDeleted {
@@ -49,7 +56,7 @@ describe("modelRouter actions", () => {
49
56
  broken: {
50
57
  handler: async () => ({ok: true}),
51
58
  method: "POST",
52
- } as any,
59
+ } as unknown as CollectionActionConfig<unknown, unknown, unknown>,
53
60
  },
54
61
  permissions: allPermissions,
55
62
  })
@@ -142,8 +149,8 @@ describe("modelRouter actions", () => {
142
149
  describe("integration", () => {
143
150
  let app: express.Application;
144
151
  let server: TestAgent;
145
- let admin: any;
146
- let notAdmin: any;
152
+ let admin: HydratedDocument<User>;
153
+ let notAdmin: HydratedDocument<User>;
147
154
  let spinach: Food;
148
155
 
149
156
  const mountFoodRouter = (options: Parameters<typeof modelRouter<Food>>[1]): void => {
@@ -174,8 +181,8 @@ describe("modelRouter actions", () => {
174
181
  }),
175
182
  ]);
176
183
  app = getBaseServer();
177
- setupAuth(app, UserModel as any);
178
- addAuthRoutes(app, UserModel as any);
184
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
185
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
179
186
  server = supertest(app);
180
187
  });
181
188
 
@@ -284,8 +291,8 @@ describe("modelRouter actions", () => {
284
291
  await StuffModel.deleteMany({});
285
292
  const doc = await StuffModel.create({deleted: true, name: "hidden", ownerId: "1"});
286
293
  app = getBaseServer();
287
- setupAuth(app, UserModel as any);
288
- addAuthRoutes(app, UserModel as any);
294
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
295
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
289
296
  app.use(
290
297
  "/stuff",
291
298
  modelRouter(StuffModel as Model<Stuff>, {
package/src/actions.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import {OpenAPIRegistry, OpenApiGeneratorV3} from "@asteasolutions/zod-to-openapi";
2
2
  import type express from "express";
3
3
  import type {NextFunction, Request, Response} from "express";
4
- import type {Model} from "mongoose";
4
+ import type {Model, SchemaType} from "mongoose";
5
5
  import type {ZodSchema, ZodType} from "zod";
6
6
  import {asyncHandler, type ModelRouterOptions, type RESTMethod} from "./api";
7
7
  import {authenticateMiddleware, type User} from "./auth";
@@ -282,7 +282,7 @@ export const createActionOpenApiMiddleware = <T>({
282
282
  };
283
283
 
284
284
  const getArrayFieldNames = <T>(model: Model<T>): string[] => {
285
- return Object.values(model.schema.paths)
285
+ return (Object.values(model.schema.paths) as SchemaType[])
286
286
  .filter((config) => config.instance === "Array")
287
287
  .map((config) => config.path);
288
288
  };
@@ -1,15 +1,13 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {beforeEach, describe, expect, it} from "bun:test";
4
2
  import type express from "express";
5
- import mongoose from "mongoose";
3
+ import mongoose, {type HydratedDocument} from "mongoose";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
7
  import {modelRouter} from "./api";
10
- import {addAuthRoutes, setupAuth} from "./auth";
8
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
11
9
  import {Permissions} from "./permissions";
12
- import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
10
+ import {type Food, FoodModel, getBaseServer, setupDb, type User, UserModel} from "./tests";
13
11
 
14
12
  // A model without the isDeleted plugin so deletes call doc.deleteOne(). The
15
13
  // document delete hook throws to exercise the hard-delete error branch.
@@ -24,7 +22,7 @@ const ExplosiveModel = mongoose.model<{name: string}>("ExplosiveCoverage", explo
24
22
  describe("modelRouter error path coverage", () => {
25
23
  let server: TestAgent;
26
24
  let app: express.Application;
27
- let admin: any;
25
+ let admin: HydratedDocument<User>;
28
26
  let apple: Food;
29
27
 
30
28
  beforeEach(async () => {
@@ -44,8 +42,8 @@ describe("modelRouter error path coverage", () => {
44
42
  });
45
43
 
46
44
  app = getBaseServer();
47
- setupAuth(app, UserModel as any);
48
- addAuthRoutes(app, UserModel as any);
45
+ setupAuth(app, UserModel as unknown as AuthUserModel);
46
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
49
47
  });
50
48
 
51
49
  it("returns 400 when an array operation transformer throws a non-APIError", async () => {
@@ -104,7 +102,7 @@ describe("modelRouter error path coverage", () => {
104
102
  const doc = await ExplosiveModel.create({name: "boom"});
105
103
  app.use(
106
104
  "/explosive",
107
- modelRouter(ExplosiveModel as any, {
105
+ modelRouter(ExplosiveModel, {
108
106
  allowAnonymous: true,
109
107
  permissions: {
110
108
  create: [Permissions.IsAny],
@@ -2,11 +2,12 @@ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
2
2
  import * as Sentry from "@sentry/bun";
3
3
  import {assert} from "chai";
4
4
  import type express from "express";
5
+ import {DateTime} from "luxon";
5
6
  import mongoose from "mongoose";
6
7
  import supertest from "supertest";
7
8
  import type TestAgent from "supertest/lib/agent";
8
9
 
9
- import {type ModelRouterOptions, modelRouter} from "./api";
10
+ import {type JSONValue, type ModelRouterOptions, modelRouter} from "./api";
10
11
  import {addAuthRoutes, setupAuth} from "./auth";
11
12
  import {ConflictError} from "./errors";
12
13
  import {Permissions} from "./permissions";
@@ -192,6 +193,51 @@ describe("modelRouter error paths", () => {
192
193
  saveSpy.mockRestore();
193
194
  }
194
195
  });
196
+
197
+ it("wraps failures while assembling the list response", async () => {
198
+ mountFood({
199
+ responseHandler: async (data) => {
200
+ const serialized = [...(data as Food[])] as Food[] & {slice: () => never};
201
+ serialized.slice = () => {
202
+ throw new Error("slice exploded");
203
+ };
204
+ return serialized as unknown as JSONValue;
205
+ },
206
+ });
207
+ const ownerId = new mongoose.Types.ObjectId();
208
+ await FoodModel.create([
209
+ {calories: 1, name: "First", ownerId},
210
+ {calories: 2, name: "Second", ownerId},
211
+ ] as Partial<Food>[]);
212
+
213
+ // limit=1 fetches an extra doc, so the handler slices off the overflow.
214
+ const res = await server.get("/food?limit=1");
215
+ assert.equal(res.body.title, "Serialization error");
216
+ assert.include(res.body.detail, "slice exploded");
217
+ });
218
+
219
+ it("rejects a patch when the stored timestamp cannot be parsed", async () => {
220
+ // `updated` is a string here so the router has to parse it as an ISO date.
221
+ const timestampSchema = new mongoose.Schema({
222
+ name: {description: "The name", type: String},
223
+ updated: {description: "Last update, as an ISO string", type: String},
224
+ });
225
+ const TimestampModel = mongoose.model(`StringTimestamp_${Date.now()}`, timestampSchema);
226
+ app.use(
227
+ "/timestamped",
228
+ modelRouter(TimestampModel, {allowAnonymous: true, permissions: anyPermissions})
229
+ );
230
+ server = supertest(app);
231
+
232
+ const doc = await TimestampModel.create({name: "Timeless", updated: "not-a-date"});
233
+
234
+ const res = await server
235
+ .patch(`/timestamped/${doc._id}`)
236
+ .set("If-Unmodified-Since", DateTime.now().toHTTP() as string)
237
+ .send({name: "Renamed"})
238
+ .expect(400);
239
+ assert.equal(res.body.title, "Invalid server timestamp");
240
+ });
195
241
  });
196
242
 
197
243
  interface Guarded {
@@ -1,7 +1,5 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {describe, expect, it} from "bun:test";
4
- import type {NextFunction} from "express";
2
+ import type {NextFunction, Request, Response} from "express";
5
3
  import mongoose from "mongoose";
6
4
 
7
5
  import {
@@ -122,47 +120,58 @@ describe("errors module", () => {
122
120
  });
123
121
 
124
122
  describe("apiUnauthorizedMiddleware", () => {
125
- it("returns 401 for Unauthorized errors", () => {
126
- const err = new Error("Unauthorized");
127
- const res = {
128
- json: function (data: any) {
129
- (this as any).body = data;
130
- return this;
131
- },
132
- send: function () {
133
- return this;
123
+ interface MockResponse {
124
+ body?: {status: number; title: string};
125
+ statusCode?: number;
126
+ json: (data: {status: number; title: string}) => MockResponse;
127
+ send: () => MockResponse;
128
+ status: (code: number) => MockResponse;
129
+ }
130
+
131
+ const createMockResponse = (): MockResponse => {
132
+ const res: MockResponse = {
133
+ json: (data) => {
134
+ res.body = data;
135
+ return res;
134
136
  },
135
- status: function (code: number) {
136
- (this as any).statusCode = code;
137
- return this;
137
+ send: () => res,
138
+ status: (code) => {
139
+ res.statusCode = code;
140
+ return res;
138
141
  },
139
142
  };
140
- const next = () => {};
143
+ return res;
144
+ };
145
+
146
+ it("returns 401 for Unauthorized errors", () => {
147
+ const err = new Error("Unauthorized");
148
+ const res = createMockResponse();
149
+ const next: NextFunction = () => {};
141
150
 
142
- apiUnauthorizedMiddleware(err, {} as any, res as any, next);
143
- expect((res as any).statusCode).toBe(401);
144
- expect((res as any).body.title).toBe("Unauthorized");
151
+ apiUnauthorizedMiddleware(err, {} as Request, res as unknown as Response, next);
152
+ expect(res.statusCode).toBe(401);
153
+ expect(res.body?.title).toBe("Unauthorized");
145
154
  });
146
155
 
147
156
  it("calls next for non-Unauthorized errors", () => {
148
157
  const err = new Error("Some other error");
149
158
  let nextCalled = false;
150
- const next = () => {
159
+ const next: NextFunction = () => {
151
160
  nextCalled = true;
152
161
  };
153
162
 
154
- apiUnauthorizedMiddleware(err, {} as any, {} as any, next);
163
+ apiUnauthorizedMiddleware(err, {} as Request, {} as Response, next);
155
164
  expect(nextCalled).toBe(true);
156
165
  });
157
166
 
158
167
  it("calls next for an APIError whose title is Unauthorized", () => {
159
168
  const err = new APIError({code: "not-a-member", status: 403, title: "Unauthorized"});
160
169
  let nextArg: unknown;
161
- const next = (error?: unknown) => {
170
+ const next: NextFunction = (error) => {
162
171
  nextArg = error;
163
172
  };
164
173
 
165
- apiUnauthorizedMiddleware(err, {} as any, {} as any, next as unknown as NextFunction);
174
+ apiUnauthorizedMiddleware(err, {} as Request, {} as Response, next);
166
175
  expect(nextArg).toBe(err);
167
176
  });
168
177
  });
package/src/api.ts CHANGED
@@ -22,7 +22,6 @@ import {
22
22
  BadRequestError,
23
23
  errorDetail,
24
24
  ForbiddenError,
25
- isAPIError,
26
25
  NotFoundError,
27
26
  passthroughOrWrap,
28
27
  passthroughOrWrapWrite,
@@ -62,6 +61,10 @@ import {
62
61
  } from "./transformers";
63
62
  import {isValidObjectId} from "./utils";
64
63
 
64
+ // noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
65
+ // biome-ignore lint/suspicious/noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
66
+ type ModelLike<T> = Model<T, any, any, any, any, any>;
67
+
65
68
  export type JSONPrimitive = string | number | boolean | null;
66
69
  export interface JSONArray extends Array<JSONValue> {}
67
70
  export interface JSONObject {
@@ -387,7 +390,7 @@ const parseDateRangeBound = (rawValue: unknown, queryKey: string): Date => {
387
390
  * so admin changelist date-range filters map to valid Mongoose range queries.
388
391
  */
389
392
  const mergeDateRangeQueryParams = <T>(
390
- model: Model<T>,
393
+ model: ModelLike<T>,
391
394
  query: Record<string, unknown>
392
395
  ): Record<string, unknown> => {
393
396
  const schema = model.schema;
@@ -510,7 +513,7 @@ const shouldValidate = <T>(
510
513
 
511
514
  // Get body validation middleware if validation is enabled
512
515
  const getBodyValidationMiddleware = <T>(
513
- model: Model<T>,
516
+ model: ModelLike<T>,
514
517
  options: ModelRouterOptions<T>,
515
518
  operation: "create" | "update"
516
519
  ): ((req: Request, res: Response, next: NextFunction) => void) => {
@@ -540,7 +543,7 @@ const getBodyValidationMiddleware = <T>(
540
543
 
541
544
  // Get query validation middleware if validation is enabled
542
545
  const getQueryValidationMiddleware = <T>(
543
- model: Model<T>,
546
+ model: ModelLike<T>,
544
547
  options: ModelRouterOptions<T>
545
548
  ): ((req: Request, res: Response, next: NextFunction) => void) => {
546
549
  const querySchema = buildQuerySchemaFromFields(model, options.queryFields);
@@ -591,22 +594,22 @@ export interface ModelRouterRegistration {
591
594
  */
592
595
  export function modelRouter<T>(
593
596
  path: string,
594
- model: Model<T>,
597
+ model: ModelLike<T>,
595
598
  options: ModelRouterOptions<T>
596
599
  ): ModelRouterRegistration;
597
- export function modelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>): express.Router;
600
+ export function modelRouter<T>(model: ModelLike<T>, options: ModelRouterOptions<T>): express.Router;
598
601
  export function modelRouter<T>(
599
- pathOrModel: string | Model<T>,
600
- modelOrOptions: Model<T> | ModelRouterOptions<T>,
602
+ pathOrModel: string | ModelLike<T>,
603
+ modelOrOptions: ModelLike<T> | ModelRouterOptions<T>,
601
604
  maybeOptions?: ModelRouterOptions<T>
602
605
  ): express.Router | ModelRouterRegistration {
603
- let model: Model<T>;
606
+ let model: ModelLike<T>;
604
607
  let options: ModelRouterOptions<T>;
605
608
  let path: string | undefined;
606
609
 
607
610
  if (typeof pathOrModel === "string") {
608
611
  path = pathOrModel;
609
- model = modelOrOptions as Model<T>;
612
+ model = modelOrOptions as ModelLike<T>;
610
613
  options = maybeOptions as ModelRouterOptions<T>;
611
614
  } else {
612
615
  model = pathOrModel;
@@ -655,7 +658,10 @@ export function modelRouter<T>(
655
658
  return router;
656
659
  }
657
660
 
658
- const _buildModelRouter = <T>(model: Model<T>, options: ModelRouterOptions<T>): express.Router => {
661
+ const _buildModelRouter = <T>(
662
+ model: ModelLike<T>,
663
+ options: ModelRouterOptions<T>
664
+ ): express.Router => {
659
665
  const router = express.Router();
660
666
 
661
667
  assertNoActionCollisions(model, options);
@@ -1181,7 +1187,11 @@ const _buildModelRouter = <T>(model: Model<T>, options: ModelRouterOptions<T>):
1181
1187
  return arrayOperation(req, res, "DELETE");
1182
1188
  };
1183
1189
  // Set up routes for managing array fields. Check if there any array fields to add this for.
1184
- if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
1190
+ if (
1191
+ (Object.values(model.schema.paths) as mongoose.SchemaType[]).find(
1192
+ (config) => config.instance === "Array"
1193
+ )
1194
+ ) {
1185
1195
  router.post(
1186
1196
  "/:id/:field",
1187
1197
  authenticateMiddleware(options.allowAnonymous),
package/src/auth.test.ts CHANGED
@@ -1,13 +1,15 @@
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 type express from "express";
4
+ import {assert} from "chai";
5
+ import express from "express";
5
6
  import type jwt from "jsonwebtoken";
6
7
  import supertest from "supertest";
7
8
  import type TestAgent from "supertest/lib/agent";
8
9
 
9
10
  import {modelRouter} from "./api";
10
11
  import {
12
+ type UserModel as AuthUserModel,
11
13
  addAuthRoutes,
12
14
  addMeRoutes,
13
15
  generateTokens,
@@ -15,6 +17,7 @@ import {
15
17
  MAX_PASSWORD_LENGTH,
16
18
  setPasswordForUser,
17
19
  setupAuth,
20
+ signupUser,
18
21
  } from "./auth";
19
22
  import {logger} from "./logger";
20
23
  import {Permissions} from "./permissions";
@@ -811,6 +814,38 @@ describe("generateTokens edge cases", () => {
811
814
  expect(result.token).toBeDefined();
812
815
  expect(result.refreshToken).toBeUndefined();
813
816
  });
817
+
818
+ it("falls back to the default expiration when TOKEN_EXPIRES_IN is invalid", async () => {
819
+ process.env.TOKEN_EXPIRES_IN = "not-a-duration";
820
+ const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
821
+ try {
822
+ const result = await generateTokens({_id: "user-123"});
823
+ const decoded = decodeTokenPayload<{exp: number}>(result.token as string);
824
+ // Falls back to the 15 minute default rather than failing token generation.
825
+ const expectedExp = Math.floor(Date.now() / 1000) + 15 * 60;
826
+ assert.isAbove(decoded.exp, expectedExp - 10);
827
+ assert.isBelow(decoded.exp, expectedExp + 10);
828
+ assert.include(String(errorSpy.mock.calls[0]?.[0]), "TOKEN_EXPIRES_IN");
829
+ } finally {
830
+ errorSpy.mockRestore();
831
+ }
832
+ });
833
+
834
+ it("falls back to the default expiration when REFRESH_TOKEN_EXPIRES_IN is invalid", async () => {
835
+ process.env.REFRESH_TOKEN_EXPIRES_IN = "not-a-duration";
836
+ const errorSpy = spyOn(logger, "error").mockImplementation(() => logger);
837
+ try {
838
+ const result = await generateTokens({_id: "user-123"});
839
+ const decoded = decodeTokenPayload<{exp: number}>(result.refreshToken as string);
840
+ // Falls back to the 30 day default rather than failing token generation.
841
+ const expectedExp = Math.floor(Date.now() / 1000) + 30 * 24 * 3600;
842
+ assert.isAbove(decoded.exp, expectedExp - 10);
843
+ assert.isBelow(decoded.exp, expectedExp + 10);
844
+ assert.include(String(errorSpy.mock.calls[0]?.[0]), "REFRESH_TOKEN_EXPIRES_IN");
845
+ } finally {
846
+ errorSpy.mockRestore();
847
+ }
848
+ });
814
849
  });
815
850
 
816
851
  describe("addAuthRoutes /refresh_token error paths", () => {
@@ -1554,3 +1589,218 @@ describe("setPasswordForUser", () => {
1554
1589
  infoSpy.mockRestore();
1555
1590
  });
1556
1591
  });
1592
+
1593
+ describe("signupUser postCreate failures", () => {
1594
+ it("wraps and rethrows errors thrown by user.postCreate", async () => {
1595
+ let saveCalled = false;
1596
+ const failingUser = {
1597
+ postCreate: async () => {
1598
+ throw new Error("postCreate failed");
1599
+ },
1600
+ save: async () => {
1601
+ saveCalled = true;
1602
+ },
1603
+ };
1604
+ const fakeModel = {
1605
+ register: async () => failingUser,
1606
+ } as unknown as Parameters<typeof signupUser>[0];
1607
+
1608
+ await expect(signupUser(fakeModel, "new@example.com", "password123")).rejects.toThrow(
1609
+ "postCreate failed"
1610
+ );
1611
+ expect(saveCalled).toBe(false);
1612
+ });
1613
+ });
1614
+
1615
+ describe("auth error paths when the user lookup fails", () => {
1616
+ let app: express.Application;
1617
+ let agent: TestAgent;
1618
+ let admin: {_id: {toString: () => string}};
1619
+
1620
+ beforeEach(async () => {
1621
+ setSystemTime();
1622
+ const testData = await setupTestData();
1623
+ admin = testData.users.admin;
1624
+ app = new TerrenoApp({
1625
+ configureApp: () => {},
1626
+ skipListen: true,
1627
+ userModel: UserModel as any,
1628
+ }).build();
1629
+ agent = supertest.agent(app);
1630
+ });
1631
+
1632
+ afterEach(() => {
1633
+ setSystemTime();
1634
+ });
1635
+
1636
+ it("responds with an error when userModel.findById throws during authentication", async () => {
1637
+ const jwtLib = (await import("jsonwebtoken")).default;
1638
+ const token = jwtLib.sign({id: admin._id.toString()}, process.env.TOKEN_SECRET as string, {
1639
+ issuer: process.env.TOKEN_ISSUER,
1640
+ });
1641
+ const findSpy = spyOn(UserModel, "findById").mockImplementation(() => {
1642
+ throw new Error("database unavailable");
1643
+ });
1644
+ try {
1645
+ const res = await agent.get("/auth/me").set("authorization", `Bearer ${token}`);
1646
+ expect(res.status).toBeGreaterThanOrEqual(400);
1647
+ } finally {
1648
+ findSpy.mockRestore();
1649
+ }
1650
+ });
1651
+
1652
+ it("calls next(err) when the local login strategy errors", async () => {
1653
+ type Authenticator = (
1654
+ username: string,
1655
+ password: string,
1656
+ done: (err: Error | null) => void
1657
+ ) => void;
1658
+ const authSpy = spyOn(
1659
+ UserModel as unknown as {authenticate: () => Authenticator},
1660
+ "authenticate"
1661
+ ).mockReturnValue((_username, _password, done) => {
1662
+ done(new Error("strategy failure"));
1663
+ });
1664
+ try {
1665
+ const errApp = new TerrenoApp({
1666
+ configureApp: () => {},
1667
+ skipListen: true,
1668
+ userModel: UserModel as any,
1669
+ }).build();
1670
+ const errAgent = supertest.agent(errApp);
1671
+ const res = await errAgent
1672
+ .post("/auth/login")
1673
+ .send({email: "notAdmin@example.com", password: "password"});
1674
+ expect(res.status).toBeGreaterThanOrEqual(400);
1675
+ } finally {
1676
+ authSpy.mockRestore();
1677
+ }
1678
+ });
1679
+ });
1680
+
1681
+ describe("cookie based JWT extraction", () => {
1682
+ afterEach(() => {
1683
+ setSystemTime();
1684
+ });
1685
+
1686
+ it("authenticates /auth/me from a jwt cookie", async () => {
1687
+ setSystemTime();
1688
+ const {users} = await setupTestData();
1689
+ const jwtLib = (await import("jsonwebtoken")).default;
1690
+ const token = jwtLib.sign({id: String(users.admin._id)}, process.env.TOKEN_SECRET as string, {
1691
+ issuer: process.env.TOKEN_ISSUER,
1692
+ });
1693
+ const app = getBaseServer();
1694
+ // Stand in for cookie-parser: the extractor prefers req.cookies.jwt over the auth header.
1695
+ app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
1696
+ req.cookies = {jwt: token};
1697
+ next();
1698
+ });
1699
+ setupAuth(app, UserModel as unknown as AuthUserModel);
1700
+ addMeRoutes(app, UserModel as unknown as AuthUserModel);
1701
+
1702
+ const res = await supertest.agent(app).get("/auth/me").expect(200);
1703
+ expect(res.body.data.email).toBe("admin@example.com");
1704
+ });
1705
+ });
1706
+
1707
+ describe("auth logging outside of the test environment", () => {
1708
+ const originalNodeEnv = process.env.NODE_ENV;
1709
+
1710
+ afterEach(() => {
1711
+ setSystemTime();
1712
+ process.env.NODE_ENV = originalNodeEnv;
1713
+ });
1714
+
1715
+ it("logs JWT setup and successful logins when NODE_ENV is not test", async () => {
1716
+ setSystemTime();
1717
+ await setupTestData();
1718
+ process.env.NODE_ENV = "development";
1719
+ const debugSpy = spyOn(logger, "debug");
1720
+ const infoSpy = spyOn(logger, "info");
1721
+ try {
1722
+ const app = getBaseServer();
1723
+ setupAuth(app, UserModel as unknown as AuthUserModel);
1724
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
1725
+
1726
+ const res = await supertest
1727
+ .agent(app)
1728
+ .post("/auth/login")
1729
+ .send({email: "notAdmin@example.com", password: "password"})
1730
+ .expect(200);
1731
+ expect(res.body.data.token).toBeDefined();
1732
+ expect(
1733
+ debugSpy.mock.calls.some(([message]) =>
1734
+ String(message).includes("Setting up JWT Authentication")
1735
+ )
1736
+ ).toBe(true);
1737
+ expect(
1738
+ infoSpy.mock.calls.some(([message]) => String(message).includes("User logged in"))
1739
+ ).toBe(true);
1740
+ } finally {
1741
+ debugSpy.mockRestore();
1742
+ infoSpy.mockRestore();
1743
+ }
1744
+ });
1745
+ });
1746
+
1747
+ describe("setupAuth validation", () => {
1748
+ it("throws when the user model has no createStrategy", () => {
1749
+ const app = getBaseServer();
1750
+ const modelWithoutStrategy = {} as unknown as AuthUserModel;
1751
+
1752
+ assert.throws(
1753
+ () => setupAuth(app, modelWithoutStrategy),
1754
+ "setupAuth userModel must have .createStrategy()"
1755
+ );
1756
+ });
1757
+ });
1758
+
1759
+ describe("/me routes with an already populated req.user", () => {
1760
+ const buildApp = (
1761
+ user: {_id?: string; id?: string} | undefined,
1762
+ foundUser: unknown
1763
+ ): express.Application => {
1764
+ const app = express();
1765
+ app.use(express.json());
1766
+ app.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
1767
+ req.user = user as unknown as express.Request["user"];
1768
+ next();
1769
+ });
1770
+ const stubUserModel = {
1771
+ findById: async () => foundUser,
1772
+ } as unknown as AuthUserModel;
1773
+ addMeRoutes(app, stubUserModel);
1774
+ return app;
1775
+ };
1776
+
1777
+ it("returns 401 from GET /auth/me when the request user has no id", async () => {
1778
+ await supertest
1779
+ .agent(buildApp({_id: "abc"}, null))
1780
+ .get("/auth/me")
1781
+ .expect(401);
1782
+ });
1783
+
1784
+ it("returns 401 from PATCH /auth/me when the request user has no id", async () => {
1785
+ await supertest
1786
+ .agent(buildApp({_id: "abc"}, null))
1787
+ .patch("/auth/me")
1788
+ .send({name: "Updated"})
1789
+ .expect(401);
1790
+ });
1791
+
1792
+ it("returns 404 from GET /auth/me when the user record no longer exists", async () => {
1793
+ await supertest
1794
+ .agent(buildApp({id: "abc"}, null))
1795
+ .get("/auth/me")
1796
+ .expect(404);
1797
+ });
1798
+
1799
+ it("returns 404 from PATCH /auth/me when the user record no longer exists", async () => {
1800
+ await supertest
1801
+ .agent(buildApp({id: "abc"}, null))
1802
+ .patch("/auth/me")
1803
+ .send({name: "Updated"})
1804
+ .expect(404);
1805
+ });
1806
+ });