@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
package/src/auth.ts CHANGED
@@ -227,6 +227,18 @@ export const setPasswordForUser = async (
227
227
  });
228
228
  };
229
229
 
230
+ /**
231
+ * Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
232
+ * keeps its default. Signing a token with an unparseable duration throws instead.
233
+ */
234
+ const validateDuration = (envName: string, value: string): StringValue | undefined => {
235
+ if (ms(value as StringValue) === undefined) {
236
+ logger.error(`${envName} is not a valid duration: "${value}". Using the default instead.`);
237
+ return undefined;
238
+ }
239
+ return value as StringValue;
240
+ };
241
+
230
242
  /**
231
243
  * Generates both an access token (JWT) and a refresh token for a given user.
232
244
  *
@@ -269,14 +281,9 @@ export const generateTokens = async (
269
281
  if (authOptions?.generateTokenExpiration) {
270
282
  tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
271
283
  } else if (process.env.TOKEN_EXPIRES_IN) {
272
- try {
273
- // this call to ms is purely for validation of the env variable. If it is invalid,
274
- // we want to be able to log the error and use the default.
275
- ms(process.env.TOKEN_EXPIRES_IN as StringValue);
276
- tokenOptions.expiresIn = process.env.TOKEN_EXPIRES_IN as StringValue;
277
- } catch (error) {
278
- // This error will result in using the default value above of 15m.
279
- logger.error(error as string);
284
+ const expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
285
+ if (expiresIn) {
286
+ tokenOptions.expiresIn = expiresIn;
280
287
  }
281
288
  }
282
289
  if (process.env.TOKEN_ISSUER) {
@@ -293,14 +300,12 @@ export const generateTokens = async (
293
300
  if (authOptions?.generateRefreshTokenExpiration) {
294
301
  refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
295
302
  } else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
296
- try {
297
- // this call to ms is purely for validation of the env variable. If it is invalid,
298
- // we want to be able to log the error and use the default.
299
- ms(process.env.REFRESH_TOKEN_EXPIRES_IN as StringValue);
300
- refreshTokenOptions.expiresIn = process.env.REFRESH_TOKEN_EXPIRES_IN as StringValue;
301
- } catch (error) {
302
- // This error will result in using the default value above of 30d.
303
- logger.error(error as string);
303
+ const expiresIn = validateDuration(
304
+ "REFRESH_TOKEN_EXPIRES_IN",
305
+ process.env.REFRESH_TOKEN_EXPIRES_IN
306
+ );
307
+ if (expiresIn) {
308
+ refreshTokenOptions.expiresIn = expiresIn;
304
309
  }
305
310
  }
306
311
  refreshToken = jwt.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
@@ -311,6 +316,10 @@ export const generateTokens = async (
311
316
  };
312
317
 
313
318
  export const setupAuth = (app: express.Application, userModel: UserModel): void => {
319
+ if (!userModel.createStrategy) {
320
+ throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
321
+ }
322
+
314
323
  passport.use(new AnonymousStrategy());
315
324
  passport.use(userModel.createStrategy());
316
325
  passport.use(
@@ -331,10 +340,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
331
340
  ) as passport.Strategy
332
341
  );
333
342
 
334
- if (!userModel.createStrategy) {
335
- throw new APIError({status: 500, title: "setupAuth userModel must have .createStrategy()"});
336
- }
337
-
338
343
  const customTokenExtractor: JwtFromRequestFunction = (req) => {
339
344
  let token: string | null = null;
340
345
  if (req?.cookies?.jwt) {
@@ -351,9 +356,6 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
351
356
  }
352
357
 
353
358
  const secretOrKey = process.env.TOKEN_SECRET;
354
- if (!secretOrKey) {
355
- throw new APIError({status: 500, title: "TOKEN_SECRET must be set in env."});
356
- }
357
359
  const jwtOpts: StrategyOptions = {
358
360
  issuer: process.env.TOKEN_ISSUER,
359
361
  jwtFromRequest: customTokenExtractor,
@@ -192,6 +192,7 @@ export const createBetterAuthSessionMiddleware = (
192
192
  // Loose shape used when mutating Mongoose user documents during Better Auth sync.
193
193
  // The fields are added by the consumer's user schema (via baseUserPlugin or similar).
194
194
  interface MutableUserDoc {
195
+ admin?: boolean;
195
196
  email?: string;
196
197
  name?: string;
197
198
  betterAuthId?: string;
@@ -204,9 +205,7 @@ export const syncBetterAuthUser = async (
204
205
  userModel: UserModel,
205
206
  betterAuthUser: BetterAuthUser,
206
207
  oauthProvider?: string
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> => {
208
+ ): Promise<MutableUserDoc> => {
210
209
  try {
211
210
  const existingUser = (await findOneOrNoneFor(userModel, {
212
211
  betterAuthId: betterAuthUser.id,
@@ -238,16 +237,17 @@ export const syncBetterAuthUser = async (
238
237
 
239
238
  // Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
240
239
  const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
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)({
240
+ const UserDocumentConstructor = userModel as unknown as new (
241
+ doc: Record<string, unknown>
242
+ ) => MutableUserDoc;
243
+ const newUser = new UserDocumentConstructor({
244
244
  ...useAsId,
245
245
  admin: false,
246
246
  betterAuthId: betterAuthUser.id,
247
247
  email: betterAuthUser.email,
248
248
  name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
249
249
  oauthProvider: oauthProvider || null,
250
- }) as MutableUserDoc;
250
+ });
251
251
  await newUser.save();
252
252
  logger.info(`Created new user from Better Auth: ${newUser.id}`);
253
253
  return newUser;
@@ -1,15 +1,18 @@
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
3
  import mongoose, {Schema} from "mongoose";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
- import {addAuthRoutes, setupAuth} from "./auth";
10
- import {ConfigurationApp} from "./configurationApp";
7
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
8
+ import {
9
+ ConfigurationApp,
10
+ type ConfigurationAppOptions,
11
+ type ConfigurationMetaResponse,
12
+ } from "./configurationApp";
11
13
  import {type ConfigurationModel, configurationPlugin} from "./configurationPlugin";
12
14
  import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "./errors";
15
+ import type {PermissionMethod} from "./permissions";
13
16
  import {createdUpdatedPlugin} from "./plugins";
14
17
  import {authAsUser, getBaseServer, setupDb, UserModel} from "./tests";
15
18
 
@@ -92,13 +95,31 @@ const ScalarConfig = (mongoose.models.ScalarConfig ||
92
95
 
93
96
  // -- Helpers --
94
97
 
98
+ /** APIError exposes `title`; plain errors only `message`. */
99
+ const errorText = (error: unknown): string => {
100
+ if (error && typeof error === "object" && "title" in error && typeof error.title === "string") {
101
+ return error.title;
102
+ }
103
+ return error instanceof Error ? error.message : String(error);
104
+ };
105
+
106
+ const findSection = (
107
+ body: ConfigurationMetaResponse,
108
+ name: string
109
+ ): ConfigurationMetaResponse["sections"][number] | undefined =>
110
+ body.sections.find((s) => s.name === name);
111
+
112
+ /** Hook payloads are untyped bags of section values. */
113
+ const section = (payload: Record<string, unknown>, name: string): Record<string, unknown> =>
114
+ payload[name] as Record<string, unknown>;
115
+
95
116
  const buildApp = (
96
- configModel: mongoose.Model<any>,
97
- options?: Partial<Omit<ConstructorParameters<typeof ConfigurationApp>[0], "model">>
117
+ configModel: ConfigurationAppOptions["model"],
118
+ options?: Partial<Omit<ConfigurationAppOptions, "model">>
98
119
  ): express.Application => {
99
120
  const app = getBaseServer();
100
- setupAuth(app, UserModel as any);
101
- addAuthRoutes(app, UserModel as any);
121
+ setupAuth(app, UserModel as unknown as AuthUserModel);
122
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
102
123
 
103
124
  const configApp = new ConfigurationApp({
104
125
  model: configModel,
@@ -201,8 +222,8 @@ describe("configurationPlugin", () => {
201
222
  try {
202
223
  await TestConfig.create({});
203
224
  throw new Error("Should have thrown");
204
- } catch (error: any) {
205
- expect(error.title || error.message).toInclude("Only one configuration document");
225
+ } catch (error) {
226
+ expect(errorText(error)).toInclude("Only one configuration document");
206
227
  }
207
228
  });
208
229
  });
@@ -213,8 +234,8 @@ describe("configurationPlugin", () => {
213
234
  try {
214
235
  await TestConfig.deleteOne({});
215
236
  throw new Error("Should have thrown");
216
- } catch (error: any) {
217
- expect(error.title || error.message).toInclude("Cannot hard-delete");
237
+ } catch (error) {
238
+ expect(errorText(error)).toInclude("Cannot hard-delete");
218
239
  }
219
240
  });
220
241
 
@@ -223,8 +244,8 @@ describe("configurationPlugin", () => {
223
244
  try {
224
245
  await TestConfig.deleteMany({});
225
246
  throw new Error("Should have thrown");
226
- } catch (error: any) {
227
- expect(error.title || error.message).toInclude("Cannot hard-delete");
247
+ } catch (error) {
248
+ expect(errorText(error)).toInclude("Cannot hard-delete");
228
249
  }
229
250
  });
230
251
 
@@ -233,8 +254,8 @@ describe("configurationPlugin", () => {
233
254
  try {
234
255
  await TestConfig.findOneAndDelete({});
235
256
  throw new Error("Should have thrown");
236
- } catch (error: any) {
237
- expect(error.title || error.message).toInclude("Cannot hard-delete");
257
+ } catch (error) {
258
+ expect(errorText(error)).toInclude("Cannot hard-delete");
238
259
  }
239
260
  });
240
261
  });
@@ -295,17 +316,17 @@ describe("ConfigurationApp routes", () => {
295
316
  expect(res.body.sections).toBeDefined();
296
317
  expect(res.body.sections.length).toBeGreaterThan(0);
297
318
 
298
- const generalSection = res.body.sections.find((s: any) => s.name === "general");
319
+ const generalSection = findSection(res.body, "general");
299
320
  expect(generalSection).toBeDefined();
300
- expect(generalSection.fields.appName).toBeDefined();
301
- expect(generalSection.fields.appName.type).toBe("string");
321
+ expect(generalSection?.fields.appName).toBeDefined();
322
+ expect(generalSection?.fields.appName.type).toBe("string");
302
323
  });
303
324
 
304
325
  it("marks secret fields in metadata", async () => {
305
326
  const res = await adminAgent.get("/configuration/meta").expect(200);
306
- const intSection = res.body.sections.find((s: any) => s.name === "integrations");
307
- expect(intSection.fields.apiKey.secret).toBe(true);
308
- expect(intSection.fields.webhookUrl.secret).toBeFalsy();
327
+ const intSection = findSection(res.body, "integrations");
328
+ expect(intSection?.fields.apiKey.secret).toBe(true);
329
+ expect(intSection?.fields.webhookUrl.secret).toBeFalsy();
309
330
  });
310
331
 
311
332
  it("returns 403 for non-admin", async () => {
@@ -326,7 +347,7 @@ describe("ConfigurationApp routes", () => {
326
347
 
327
348
  it("redacts secret fields", async () => {
328
349
  // Set a secret value first
329
- await (TestConfig as any).updateConfig({integrations: {apiKey: "super-secret-key"}});
350
+ await TestConfig.updateConfig({integrations: {apiKey: "super-secret-key"}});
330
351
  const res = await adminAgent.get("/configuration").expect(200);
331
352
  expect(res.body.data.integrations.apiKey).toBe("********");
332
353
  expect(res.body.data.integrations.webhookUrl).toBe("https://example.com/hook");
@@ -362,7 +383,7 @@ describe("ConfigurationApp routes", () => {
362
383
  expect(res.body.data.integrations.webhookUrl).toBe("https://changed.example.com");
363
384
 
364
385
  // Confirm the raw stored document holds no secret value.
365
- const stored = await (TestConfig as any).getConfig();
386
+ const stored = await TestConfig.getConfig();
366
387
  expect(stored.integrations.apiKey).toBe("");
367
388
  });
368
389
 
@@ -387,9 +408,9 @@ describe("ConfigurationApp routes", () => {
387
408
  });
388
409
 
389
410
  it("does not mutate the stored config document's secret fields", async () => {
390
- await (TestConfig as any).getConfig();
411
+ await TestConfig.getConfig();
391
412
  await adminAgent.post("/configuration/list-secrets").expect(200);
392
- const stored = await (TestConfig as any).getConfig();
413
+ const stored = await TestConfig.getConfig();
393
414
  // list-secrets must never write resolved values into the document.
394
415
  expect(stored.integrations.apiKey).toBe("");
395
416
  });
@@ -419,11 +440,11 @@ describe("ConfigurationApp with scalar fields", () => {
419
440
 
420
441
  it("puts scalar fields into __root__ section", async () => {
421
442
  const res = await adminAgent.get("/configuration/meta").expect(200);
422
- const rootSection = res.body.sections.find((s: any) => s.name === "__root__");
443
+ const rootSection = findSection(res.body, "__root__");
423
444
  expect(rootSection).toBeDefined();
424
- expect(rootSection.displayName).toBe("General");
425
- expect(rootSection.fields.siteName).toBeDefined();
426
- expect(rootSection.fields.debugMode).toBeDefined();
445
+ expect(rootSection?.displayName).toBe("General");
446
+ expect(rootSection?.fields.siteName).toBeDefined();
447
+ expect(rootSection?.fields.debugMode).toBeDefined();
427
448
  });
428
449
  });
429
450
 
@@ -442,8 +463,8 @@ describe("ConfigurationApp with field overrides", () => {
442
463
 
443
464
  it("applies widget overrides to metadata", async () => {
444
465
  const res = await adminAgent.get("/configuration/meta").expect(200);
445
- const intSection = res.body.sections.find((s: any) => s.name === "integrations");
446
- expect(intSection.fields.webhookUrl.widget).toBe("url");
466
+ const intSection = findSection(res.body, "integrations");
467
+ expect(intSection?.fields.webhookUrl.widget).toBe("url");
447
468
  });
448
469
  });
449
470
 
@@ -453,7 +474,7 @@ describe("ConfigurationApp with custom permissions", () => {
453
474
  let notAdminAgent: TestAgent;
454
475
 
455
476
  // Terreno-style permission: any authenticated user (not just admins).
456
- const isAuthenticated = (_method: any, user?: any): boolean => Boolean(user?.id);
477
+ const isAuthenticated: PermissionMethod<unknown> = (_method, user) => Boolean(user?.id);
457
478
 
458
479
  beforeEach(async () => {
459
480
  await setupDb();
@@ -541,13 +562,13 @@ describe("ConfigurationApp with update hooks", () => {
541
562
  expect(res.body.data.general.appName).toBe("Safe");
542
563
  expect(res.body.data.integrations.apiKey).toBe("");
543
564
 
544
- const stored = await (TestConfig as any).getConfig();
565
+ const stored = await TestConfig.getConfig();
545
566
  expect(stored.integrations.apiKey).toBe("");
546
567
  });
547
568
 
548
569
  it("runs postUpdate with redacted config and previous value", async () => {
549
570
  // Seed a secret so we can confirm it is redacted in hook payloads.
550
- await (TestConfig as any).updateConfig({integrations: {apiKey: "should-not-leak"}});
571
+ await TestConfig.updateConfig({integrations: {apiKey: "should-not-leak"}});
551
572
  await adminAgent
552
573
  .patch("/configuration")
553
574
  .send({general: {appName: "Audited"}})
@@ -555,10 +576,10 @@ describe("ConfigurationApp with update hooks", () => {
555
576
 
556
577
  expect(postUpdateCalls).toHaveLength(1);
557
578
  const {config, prev} = postUpdateCalls[0];
558
- expect((config.general as any).appName).toBe("Audited");
579
+ expect(section(config, "general").appName).toBe("Audited");
559
580
  // Secret values must be redacted in both payloads.
560
- expect((config.integrations as any).apiKey).toBe("********");
561
- expect((prev.integrations as any).apiKey).toBe("********");
581
+ expect(section(config, "integrations").apiKey).toBe("********");
582
+ expect(section(prev, "integrations").apiKey).toBe("********");
562
583
  expect(JSON.stringify(postUpdateCalls)).not.toContain("should-not-leak");
563
584
  });
564
585
  });
@@ -1,10 +1,12 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
4
2
  import mongoose, {model, Schema} from "mongoose";
5
- import type {SecretProvider} from "./configurationPlugin";
3
+ import type {ConfigurationModel, Paths, SecretProvider} from "./configurationPlugin";
6
4
  import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
7
- import {isDeletedPlugin} from "./plugins";
5
+ import type {APIError} from "./errors";
6
+ import {type FindOneOrNonePlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
7
+
8
+ /** A configuration model as created by the plugin, including the findOneOrNone static it adds. */
9
+ type ConfigModel<T extends object> = ConfigurationModel<T> & FindOneOrNonePlugin<T>;
8
10
 
9
11
  // --- Test schema with secret fields ---
10
12
 
@@ -57,36 +59,58 @@ const testConfigSchema = new Schema<TestConfig>({
57
59
 
58
60
  testConfigSchema.plugin(configurationPlugin);
59
61
 
60
- const TestConfigModel = model("TestConfiguration", testConfigSchema) as any;
62
+ const TestConfigModel = model<TestConfig, ConfigModel<TestConfig>>(
63
+ "TestConfiguration",
64
+ testConfigSchema
65
+ );
61
66
 
62
67
  // --- Simple schema for singleton tests ---
63
68
 
64
- const simpleSchema = new Schema({
69
+ interface SimpleConfig {
70
+ value: string;
71
+ }
72
+
73
+ const simpleSchema = new Schema<SimpleConfig>({
65
74
  value: {default: "default", description: "A value", type: String},
66
75
  });
67
76
  simpleSchema.plugin(configurationPlugin);
68
- const SimpleConfigModel = model("SimpleConfiguration", simpleSchema) as any;
77
+ const SimpleConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
78
+ "SimpleConfiguration",
79
+ simpleSchema
80
+ );
69
81
 
70
82
  // --- Schema opting into the _singleton unique index ---
71
83
 
72
- const indexedSchema = new Schema({
84
+ const indexedSchema = new Schema<SimpleConfig>({
73
85
  value: {default: "default", description: "A value", type: String},
74
86
  });
75
87
  indexedSchema.plugin(configurationPlugin, {enforceSingletonIndex: true});
76
- const IndexedConfigModel = model("IndexedConfiguration", indexedSchema) as any;
88
+ const IndexedConfigModel = model<SimpleConfig, ConfigModel<SimpleConfig>>(
89
+ "IndexedConfiguration",
90
+ indexedSchema
91
+ );
77
92
 
78
93
  // --- Soft-delete-aware schema ---
79
94
 
80
- const softDeleteSchema = new Schema({
95
+ interface SoftDeleteConfig extends SimpleConfig, IsDeleted {}
96
+
97
+ const softDeleteSchema = new Schema<SoftDeleteConfig>({
81
98
  value: {default: "default", description: "A value", type: String},
82
99
  });
83
100
  softDeleteSchema.plugin(configurationPlugin);
84
101
  softDeleteSchema.plugin(isDeletedPlugin);
85
- const SoftDeleteConfigModel = model("SoftDeleteConfiguration", softDeleteSchema) as any;
102
+ const SoftDeleteConfigModel = model<SoftDeleteConfig, ConfigModel<SoftDeleteConfig>>(
103
+ "SoftDeleteConfiguration",
104
+ softDeleteSchema
105
+ );
86
106
 
87
107
  // --- Schema with a validated field (enum) for runValidators coverage ---
88
108
 
89
- const validatedSchema = new Schema({
109
+ interface ValidatedConfig {
110
+ level: string;
111
+ }
112
+
113
+ const validatedSchema = new Schema<ValidatedConfig>({
90
114
  level: {
91
115
  default: "low",
92
116
  description: "Severity level",
@@ -95,26 +119,25 @@ const validatedSchema = new Schema({
95
119
  },
96
120
  });
97
121
  validatedSchema.plugin(configurationPlugin);
98
- const ValidatedConfigModel = model("ValidatedConfiguration", validatedSchema) as any;
122
+ const ValidatedConfigModel = model<ValidatedConfig, ConfigModel<ValidatedConfig>>(
123
+ "ValidatedConfiguration",
124
+ validatedSchema
125
+ );
99
126
 
100
127
  describe("configurationPlugin", () => {
101
128
  describe("schema setup", () => {
102
129
  it("does not add a _singleton index by default", () => {
103
130
  const indexes = SimpleConfigModel.schema.indexes();
104
- const singletonIndex = indexes.find(
105
- ([fields]: [Record<string, any>]) => fields._singleton !== undefined
106
- );
131
+ const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
107
132
  expect(singletonIndex).toBeUndefined();
108
133
  expect(SimpleConfigModel.schema.path("_singleton")).toBeUndefined();
109
134
  });
110
135
 
111
136
  it("adds a _singleton field with unique index when enforceSingletonIndex is true", () => {
112
137
  const indexes = IndexedConfigModel.schema.indexes();
113
- const singletonIndex = indexes.find(
114
- ([fields]: [Record<string, any>]) => fields._singleton !== undefined
115
- );
138
+ const singletonIndex = indexes.find(([fields]) => fields._singleton !== undefined);
116
139
  expect(singletonIndex).toBeDefined();
117
- expect(singletonIndex[1].unique).toBe(true);
140
+ expect(singletonIndex?.[1]?.unique).toBe(true);
118
141
  });
119
142
 
120
143
  it("adds getConfig static", () => {
@@ -137,22 +160,22 @@ describe("configurationPlugin", () => {
137
160
  describe("getSecretFields", () => {
138
161
  it("discovers top-level secret fields", () => {
139
162
  const secrets = TestConfigModel.getSecretFields();
140
- const apiKeySecret = secrets.find((s: {path: string}) => s.path === "apiKey");
163
+ const apiKeySecret = secrets.find((s) => s.path === "apiKey");
141
164
  expect(apiKeySecret).toBeDefined();
142
- expect(apiKeySecret.secretName).toBe("ext-api-key");
165
+ expect(apiKeySecret?.secretName).toBe("ext-api-key");
143
166
  });
144
167
 
145
168
  it("discovers nested secret fields", () => {
146
169
  const secrets = TestConfigModel.getSecretFields();
147
- const nestedSecret = secrets.find((s: {path: string}) => s.path === "nested.secretToken");
170
+ const nestedSecret = secrets.find((s) => s.path === "nested.secretToken");
148
171
  expect(nestedSecret).toBeDefined();
149
- expect(nestedSecret.secretName).toBe("nested-token");
150
- expect(nestedSecret.secretProvider).toBe("vault");
172
+ expect(nestedSecret?.secretName).toBe("nested-token");
173
+ expect(nestedSecret?.secretProvider).toBe("vault");
151
174
  });
152
175
 
153
176
  it("does not include non-secret fields", () => {
154
177
  const secrets = TestConfigModel.getSecretFields();
155
- const nonSecret = secrets.find((s: {path: string}) => s.path === "appName");
178
+ const nonSecret = secrets.find((s) => s.path === "appName");
156
179
  expect(nonSecret).toBeUndefined();
157
180
  });
158
181
 
@@ -211,7 +234,7 @@ describe("configurationPlugin", () => {
211
234
  });
212
235
 
213
236
  it("passes the discovered secret version to the provider", async () => {
214
- const versionedSchema = new Schema({
237
+ const versionedSchema = new Schema<{token: string}>({
215
238
  token: {
216
239
  default: "",
217
240
  description: "Pinned secret",
@@ -222,7 +245,10 @@ describe("configurationPlugin", () => {
222
245
  },
223
246
  });
224
247
  versionedSchema.plugin(configurationPlugin);
225
- const VersionedModel = model("VersionedConfiguration", versionedSchema) as any;
248
+ const VersionedModel = model<{token: string}, ConfigModel<{token: string}>>(
249
+ "VersionedConfiguration",
250
+ versionedSchema
251
+ );
226
252
 
227
253
  const received: Array<{name: string; version?: string}> = [];
228
254
  const provider: SecretProvider = {
@@ -311,7 +337,7 @@ describe("configurationPlugin", () => {
311
337
  }
312
338
  const first = await SimpleConfigModel.getConfig();
313
339
  const second = await SimpleConfigModel.getConfig();
314
- expect(first._id.toString()).toBe(second._id.toString());
340
+ expect(String(first._id)).toBe(String(second._id));
315
341
  });
316
342
 
317
343
  it("prevents creating a second document via save", async () => {
@@ -327,14 +353,14 @@ describe("configurationPlugin", () => {
327
353
  if (!dbConnected) {
328
354
  return;
329
355
  }
330
- const existing = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
356
+ const existing = await SimpleConfigModel.getConfig();
331
357
  // Simulate a race: the initial lookup misses, so getConfig attempts a create
332
358
  // that the pre-save singleton guard rejects with a 409. getConfig should then
333
359
  // re-fetch and return the document created by the "other process".
334
360
  const spy = spyOn(SimpleConfigModel, "findOneOrNone").mockResolvedValueOnce(null);
335
361
  try {
336
- const config = (await SimpleConfigModel.getConfig()) as {_id: {toString(): string}};
337
- expect(config._id.toString()).toBe(existing._id.toString());
362
+ const config = await SimpleConfigModel.getConfig();
363
+ expect(String(config._id)).toBe(String(existing._id));
338
364
  } finally {
339
365
  spy.mockRestore();
340
366
  }
@@ -362,9 +388,13 @@ describe("configurationPlugin", () => {
362
388
  }
363
389
  await SimpleConfigModel.getConfig();
364
390
  // `value` is a string, so descending into `value.missing` bails out.
365
- expect(await SimpleConfigModel.getConfig("value.missing")).toBeUndefined();
391
+ expect(
392
+ await SimpleConfigModel.getConfig("value.missing" as Paths<SimpleConfig>)
393
+ ).toBeUndefined();
366
394
  // A missing top-level segment also resolves to undefined.
367
- expect(await SimpleConfigModel.getConfig("nope.deeper")).toBeUndefined();
395
+ expect(
396
+ await SimpleConfigModel.getConfig("nope.deeper" as Paths<SimpleConfig>)
397
+ ).toBeUndefined();
368
398
  });
369
399
 
370
400
  it("updates an existing document via updateConfig", async () => {
@@ -411,8 +441,8 @@ describe("configurationPlugin", () => {
411
441
  try {
412
442
  await SimpleConfigModel.deleteOne({}).exec();
413
443
  expect.unreachable("Should have thrown");
414
- } catch (err: any) {
415
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
444
+ } catch (err) {
445
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
416
446
  }
417
447
  });
418
448
 
@@ -424,8 +454,8 @@ describe("configurationPlugin", () => {
424
454
  try {
425
455
  await SimpleConfigModel.findOneAndDelete({}).exec();
426
456
  expect.unreachable("Should have thrown");
427
- } catch (err: any) {
428
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
457
+ } catch (err) {
458
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
429
459
  }
430
460
  });
431
461
 
@@ -437,8 +467,8 @@ describe("configurationPlugin", () => {
437
467
  try {
438
468
  await SimpleConfigModel.deleteMany({}).exec();
439
469
  expect.unreachable("Should have thrown");
440
- } catch (err: any) {
441
- expect(err.title).toMatch(/Cannot hard-delete the configuration document/);
470
+ } catch (err) {
471
+ expect((err as APIError).title).toMatch(/Cannot hard-delete the configuration document/);
442
472
  }
443
473
  });
444
474
  });
@@ -496,7 +526,7 @@ describe("configurationPlugin", () => {
496
526
  // A new non-deleted singleton can now be created
497
527
  const second = await SoftDeleteConfigModel.getConfig();
498
528
  expect(second.deleted).toBe(false);
499
- expect(second._id.toString()).not.toBe(first._id.toString());
529
+ expect(String(second._id)).not.toBe(String(first._id));
500
530
  });
501
531
 
502
532
  it("does not let updateConfig touch a soft-deleted document", async () => {
@@ -511,7 +541,7 @@ describe("configurationPlugin", () => {
511
541
  const updated = await SoftDeleteConfigModel.updateConfig({value: "fresh"});
512
542
  expect(updated.deleted).toBe(false);
513
543
  expect(updated.value).toBe("fresh");
514
- expect(updated._id.toString()).not.toBe(first._id.toString());
544
+ expect(String(updated._id)).not.toBe(String(first._id));
515
545
  });
516
546
  });
517
547
  });
@@ -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
- {new: true, runValidators: true}
347
+ {returnDocument: "after", 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
- {new: true, runValidators: true}
359
+ {returnDocument: "after", runValidators: true}
360
360
  ).orFail();
361
361
  };
362
362