@terreno/api 57.20.0 → 57.21.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 (116) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/api.d.ts +3 -3
  4. package/dist/frameworkModelNames.d.ts +4 -0
  5. package/dist/frameworkModelNames.js +4 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +9 -3
  8. package/dist/mcp/adminTracking.d.ts +28 -0
  9. package/dist/mcp/adminTracking.js +80 -0
  10. package/dist/mcp/auth.d.ts +6 -0
  11. package/dist/mcp/auth.js +12 -2
  12. package/dist/mcp/server.d.ts +8 -0
  13. package/dist/mcp/server.js +48 -4
  14. package/dist/models/mcpOAuthToken.js +27 -0
  15. package/dist/models/mcpRequestLog.d.ts +2 -0
  16. package/dist/models/mcpRequestLog.js +73 -0
  17. package/dist/models/mcpServiceToken.js +4 -0
  18. package/dist/models/mcpToolSetting.d.ts +2 -0
  19. package/dist/models/mcpToolSetting.js +119 -0
  20. package/dist/models/versionConfig.d.ts +2 -0
  21. package/dist/rbac/auditModel.d.ts +2 -1
  22. package/dist/terrenoApp.d.ts +12 -0
  23. package/dist/terrenoApp.js +3 -0
  24. package/dist/tests/models.d.ts +17 -22
  25. package/dist/tests/models.js +7 -1
  26. package/dist/tests/testHelper.d.ts +6 -12
  27. package/dist/tests.d.ts +1 -0
  28. package/dist/tests.js +3 -1
  29. package/dist/types/mcpAdmin.d.ts +58 -0
  30. package/dist/types/mcpAdmin.js +2 -0
  31. package/dist/types/mcpOAuth.d.ts +2 -0
  32. package/dist/types/mcpServiceToken.d.ts +2 -0
  33. package/e2e/smoke.ts +193 -0
  34. package/package.json +7 -5
  35. package/src/adminModelRouter.test.ts +8 -6
  36. package/src/api.arrayOperations.test.ts +31 -22
  37. package/src/api.hooks.test.ts +12 -11
  38. package/src/api.query.test.ts +2 -2
  39. package/src/api.test.ts +8 -7
  40. package/src/api.ts +3 -3
  41. package/src/audit/auditApp.test.ts +1 -1
  42. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  43. package/src/auth.test.ts +21 -7
  44. package/src/authRecovery.test.ts +10 -10
  45. package/src/authVerification.test.ts +7 -7
  46. package/src/betterAuthFeatures.test.ts +3 -2
  47. package/src/betterAuthLinking.test.ts +3 -1
  48. package/src/betterAuthSetup.test.ts +77 -51
  49. package/src/collectionRegistry.test.ts +4 -4
  50. package/src/frameworkModelNames.test.ts +8 -0
  51. package/src/frameworkModelNames.ts +4 -0
  52. package/src/githubAuth.test.ts +11 -11
  53. package/src/index.ts +8 -0
  54. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  55. package/src/mcp/actionTools.test.ts +11 -5
  56. package/src/mcp/adminTracking.test.ts +272 -0
  57. package/src/mcp/adminTracking.ts +104 -0
  58. package/src/mcp/auth.ts +18 -2
  59. package/src/mcp/oauth.test.ts +1 -1
  60. package/src/mcp/server.ts +67 -4
  61. package/src/mcp/serviceTokens.test.ts +2 -1
  62. package/src/mcp/toolGenerator.test.ts +9 -5
  63. package/src/migrations/cli.test.ts +15 -14
  64. package/src/migrations/cli.ts +1 -1
  65. package/src/migrations/generate.test.ts +2 -2
  66. package/src/migrations/load.test.ts +1 -1
  67. package/src/migrations/lock.test.ts +8 -3
  68. package/src/migrations/runner.test.ts +16 -5
  69. package/src/migrations/schemaCatalog.test.ts +4 -1
  70. package/src/models/mcpOAuthToken.test.ts +42 -0
  71. package/src/models/mcpOAuthToken.ts +32 -0
  72. package/src/models/mcpRequestLog.ts +81 -0
  73. package/src/models/mcpServiceToken.test.ts +23 -0
  74. package/src/models/mcpServiceToken.ts +10 -0
  75. package/src/models/mcpToolSetting.test.ts +69 -0
  76. package/src/models/mcpToolSetting.ts +138 -0
  77. package/src/models/versionConfig.ts +2 -0
  78. package/src/notifications/notificationsApp.test.ts +5 -8
  79. package/src/notifiers/slackWebApi.test.ts +30 -8
  80. package/src/openApi.test.ts +4 -4
  81. package/src/openApiValidator.test.ts +3 -3
  82. package/src/orgs/orgPermissions.test.ts +2 -2
  83. package/src/orgs/orgPlugin.test.ts +4 -3
  84. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  85. package/src/orgs/organizationSettings.test.ts +1 -1
  86. package/src/orgs/orgsApp.test.ts +5 -3
  87. package/src/permissions.test.ts +2 -2
  88. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  89. package/src/rbac/assertAllowed.test.ts +1 -1
  90. package/src/rbac/auditModel.ts +10 -2
  91. package/src/rbac/realtimeAccess.test.ts +3 -2
  92. package/src/rbac/routes.test.ts +1 -1
  93. package/src/rbac/userWriteGuards.test.ts +8 -5
  94. package/src/realtime/realtime.test.ts +35 -31
  95. package/src/scrubAdminFields.test.ts +1 -1
  96. package/src/sync/adminWindowMutation.test.ts +4 -3
  97. package/src/sync/executors.test.ts +1 -1
  98. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  99. package/src/sync/sync.test.ts +1 -1
  100. package/src/sync/syncPhaseC.test.ts +14 -11
  101. package/src/sync/syncRoutes.test.ts +8 -8
  102. package/src/sync/syncSeqPlugin.test.ts +1 -2
  103. package/src/sync/syncSocket.test.ts +5 -4
  104. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  105. package/src/terrenoApp.migrations.test.ts +8 -7
  106. package/src/terrenoApp.ts +14 -0
  107. package/src/tests/betterAuthStubs.ts +3 -2
  108. package/src/tests/bunSetup.ts +1 -1
  109. package/src/tests/models.ts +10 -0
  110. package/src/tests/testEnv.ts +7 -0
  111. package/src/tests.ts +1 -0
  112. package/src/types/mcpAdmin.ts +80 -0
  113. package/src/types/mcpOAuth.ts +5 -0
  114. package/src/types/mcpServiceToken.ts +5 -0
  115. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  116. package/tsconfig.typecheck.json +14 -0
@@ -2,7 +2,7 @@ import {describe, expect, it} from "bun:test";
2
2
  import mongoose from "mongoose";
3
3
 
4
4
  import {enrichModelRouterOptions} from "./adminModelRouter";
5
- import type {ModelRouterOptions} from "./api";
5
+ import type {ModelRouterOptions, OpenApiMiddleware} from "./api";
6
6
 
7
7
  interface Widget {
8
8
  secret?: string;
@@ -34,10 +34,9 @@ describe("enrichModelRouterOptions", () => {
34
34
  const options: ModelRouterOptions<Widget> = {
35
35
  permissions: {create: [], delete: [], list: [], read: [], update: []},
36
36
  };
37
- const enriched = enrichModelRouterOptions(WidgetModel, options, {
38
- openApi: {enabled: true} as never,
39
- });
40
- expect(enriched.openApi).toEqual({enabled: true});
37
+ const openApi = {enabled: true} as unknown as OpenApiMiddleware;
38
+ const enriched = enrichModelRouterOptions(WidgetModel, options, {openApi});
39
+ expect(enriched.openApi).toEqual(openApi);
41
40
  });
42
41
 
43
42
  it("scrubs admin fields in preCreate/preUpdate and honors user hooks", async () => {
@@ -49,7 +48,10 @@ describe("enrichModelRouterOptions", () => {
49
48
  listFields: ["title"],
50
49
  },
51
50
  permissions: {create: [], delete: [], list: [], read: [], update: []},
52
- preCreate: async (body) => ({...body, title: `${body.title}-created`}),
51
+ preCreate: async (body) => {
52
+ const widget = body as Partial<Widget>;
53
+ return {...widget, title: `${widget.title}-created`};
54
+ },
53
55
  preUpdate: async () => null,
54
56
  };
55
57
  const enriched = enrichModelRouterOptions(WidgetModel, options, {});
@@ -20,6 +20,14 @@ import {AdminOwnerTransformer} from "./transformers";
20
20
 
21
21
  type TestUser = Awaited<ReturnType<typeof setupDb>>[number];
22
22
 
23
+ /** Returns a document a postUpdate hook captured, failing the test if the hook never ran. */
24
+ const captured = (doc: Food | undefined): Food => {
25
+ if (!doc) {
26
+ throw new Error("Expected postUpdate to capture a document");
27
+ }
28
+ return doc;
29
+ };
30
+
23
31
  describe("model array operations", () => {
24
32
  let _server: TestAgent;
25
33
  let app: express.Application;
@@ -219,7 +227,7 @@ describe("model array operations", () => {
219
227
 
220
228
  expect(updatedCategory.updated).not.toBe(updatedCategory.created);
221
229
  expect(unchangedCategory.updated).toBe(unchangedCategory.created);
222
- expect(updatedCategory.name).toBe("Updated Category");
230
+ expect(updatedCategory?.name).toBe("Updated Category");
223
231
  // Unchanged.
224
232
  expect(updatedCategory.show).toBe(true);
225
233
  expect(unchangedCategory.show).toBe(true);
@@ -268,8 +276,8 @@ describe("model array operations", () => {
268
276
  expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
269
277
 
270
278
  // Verify the content is different (new category added)
271
- expect(postUpdateDoc.categories).toHaveLength(3);
272
- expect(postUpdatePrevDoc.categories).toHaveLength(2);
279
+ expect(captured(postUpdateDoc).categories).toHaveLength(3);
280
+ expect(captured(postUpdatePrevDoc).categories).toHaveLength(2);
273
281
 
274
282
  // Reset for next test
275
283
  postUpdateCalled = false;
@@ -294,15 +302,15 @@ describe("model array operations", () => {
294
302
  expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
295
303
 
296
304
  // Verify the content is different (category updated)
297
- const updatedCategory = postUpdateDoc.categories.find(
298
- (c: FoodCategory) => c._id.toString() === categoryId.toString()
305
+ const updatedCategory = captured(postUpdateDoc).categories.find(
306
+ (c: FoodCategory) => c._id?.toString() === categoryId.toString()
299
307
  );
300
- const prevCategory = postUpdatePrevDoc.categories.find(
301
- (c: FoodCategory) => c._id.toString() === categoryId.toString()
308
+ const prevCategory = captured(postUpdatePrevDoc).categories.find(
309
+ (c: FoodCategory) => c._id?.toString() === categoryId.toString()
302
310
  );
303
311
 
304
- expect(updatedCategory.name).toBe("Updated Category");
305
- expect(prevCategory.name).toBe("Fruit");
312
+ expect(updatedCategory?.name).toBe("Updated Category");
313
+ expect(prevCategory?.name).toBe("Fruit");
306
314
 
307
315
  // Reset for next test
308
316
  postUpdateCalled = false;
@@ -320,11 +328,11 @@ describe("model array operations", () => {
320
328
  expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
321
329
 
322
330
  // Verify the content is different (category removed)
323
- const remainingCategories = postUpdateDoc.categories.filter(
324
- (c: FoodCategory) => c._id.toString() === categoryId.toString()
331
+ const remainingCategories = captured(postUpdateDoc).categories.filter(
332
+ (c: FoodCategory) => c._id?.toString() === categoryId.toString()
325
333
  );
326
- const prevCategories = postUpdatePrevDoc.categories.filter(
327
- (c: FoodCategory) => c._id.toString() === categoryId.toString()
334
+ const prevCategories = captured(postUpdatePrevDoc).categories.filter(
335
+ (c: FoodCategory) => c._id?.toString() === categoryId.toString()
328
336
  );
329
337
 
330
338
  expect(remainingCategories).toHaveLength(0);
@@ -371,10 +379,10 @@ describe("model array operations", () => {
371
379
  expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
372
380
 
373
381
  // Verify the content is different (new tag added)
374
- expect(postUpdateDoc.tags).toHaveLength(3);
375
- expect(postUpdatePrevDoc.tags).toHaveLength(2);
376
- expect(postUpdateDoc.tags).toContain("organic");
377
- expect(postUpdatePrevDoc.tags).not.toContain("organic");
382
+ expect(captured(postUpdateDoc).tags).toHaveLength(3);
383
+ expect(captured(postUpdatePrevDoc).tags).toHaveLength(2);
384
+ expect(captured(postUpdateDoc).tags).toContain("organic");
385
+ expect(captured(postUpdatePrevDoc).tags).not.toContain("organic");
378
386
 
379
387
  // Reset for next test
380
388
  postUpdateCalled = false;
@@ -388,10 +396,10 @@ describe("model array operations", () => {
388
396
  expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
389
397
 
390
398
  // Verify the content is different (tag updated)
391
- expect(postUpdateDoc.tags).toContain("super-healthy");
392
- expect(postUpdatePrevDoc.tags).toContain("healthy");
393
- expect(postUpdateDoc.tags).not.toContain("healthy");
394
- expect(postUpdatePrevDoc.tags).not.toContain("super-healthy");
399
+ expect(captured(postUpdateDoc).tags).toContain("super-healthy");
400
+ expect(captured(postUpdatePrevDoc).tags).toContain("healthy");
401
+ expect(captured(postUpdateDoc).tags).not.toContain("healthy");
402
+ expect(captured(postUpdatePrevDoc).tags).not.toContain("super-healthy");
395
403
  });
396
404
  });
397
405
 
@@ -829,7 +837,8 @@ describe("array subdocument PATCH with a stripping preUpdate", () => {
829
837
  read: [Permissions.IsAdmin],
830
838
  update: [Permissions.IsAdmin],
831
839
  },
832
- preUpdate: (body) => preUpdate(body as Partial<Food>),
840
+ // The hook returns the stripped update body, not a whole document.
841
+ preUpdate: (body) => preUpdate(body) as Food,
833
842
  })
834
843
  );
835
844
  agent = await authAsUser(app, "admin");
@@ -1,6 +1,7 @@
1
1
  import {beforeEach, describe, expect, it, type mock} from "bun:test";
2
2
  import * as Sentry from "@sentry/bun";
3
3
  import type express from "express";
4
+ import type {HydratedDocument} from "mongoose";
4
5
  import supertest from "supertest";
5
6
  import type TestAgent from "supertest/lib/agent";
6
7
 
@@ -48,8 +49,9 @@ describe("pre and post hooks", () => {
48
49
  update: [Permissions.IsAny],
49
50
  },
50
51
  preCreate: (data) => {
51
- data.calories = 14;
52
- return data;
52
+ const food = data as Partial<Food>;
53
+ food.calories = 14;
54
+ return food as Food;
53
55
  },
54
56
  preDelete: (data) => {
55
57
  deleteCalled = true;
@@ -57,7 +59,7 @@ describe("pre and post hooks", () => {
57
59
  },
58
60
  preUpdate: (data) => {
59
61
  data.calories = 15;
60
- return data;
62
+ return data as Food;
61
63
  },
62
64
  })
63
65
  );
@@ -158,18 +160,17 @@ describe("pre and post hooks", () => {
158
160
  update: [Permissions.IsAny],
159
161
  },
160
162
  postCreate: async (data) => {
161
- data.calories = 14;
162
- await data.save();
163
- return data;
163
+ const food = data as HydratedDocument<Food>;
164
+ food.calories = 14;
165
+ await food.save();
164
166
  },
165
- postDelete: (data) => {
167
+ postDelete: () => {
166
168
  deleteCalled = true;
167
- return data;
168
169
  },
169
170
  postUpdate: async (data) => {
170
- data.calories = 15;
171
- await data.save();
172
- return data;
171
+ const food = data as HydratedDocument<Food>;
172
+ food.calories = 15;
173
+ await food.save();
173
174
  },
174
175
  })
175
176
  );
@@ -471,7 +471,7 @@ describe("query and list methods", () => {
471
471
  .get(`/food?${qs.stringify({$or: [{name: "Carrots"}, {name: "Pizza"}]})}`)
472
472
  .expect(200);
473
473
  expect(res.body.data).toHaveLength(2);
474
- const ids1 = res.body.data.map((d: Food) => d.id);
474
+ const ids1 = res.body.data.map((d: {id: string}) => d.id);
475
475
  expect(ids1).toEqual(expect.arrayContaining([carrots?._id.toString(), pizza?._id.toString()]));
476
476
  expect(ids1).toHaveLength(2);
477
477
  });
@@ -486,7 +486,7 @@ describe("query and list methods", () => {
486
486
  )
487
487
  .expect(200);
488
488
  expect(res.body.data).toHaveLength(2);
489
- const ids2 = res.body.data.map((d: Food) => d.id);
489
+ const ids2 = res.body.data.map((d: {id: string}) => d.id);
490
490
  expect(ids2).toEqual(
491
491
  expect.arrayContaining([carrots?._id.toString(), spinach?._id.toString()])
492
492
  );
package/src/api.test.ts CHANGED
@@ -5,11 +5,12 @@ import mongoose, {type Model} from "mongoose";
5
5
  import supertest from "supertest";
6
6
  import type TestAgent from "supertest/lib/agent";
7
7
 
8
- import {addPopulateToQuery, modelRouter} from "./api";
8
+ import {addPopulateToQuery, type JSONValue, modelRouter} from "./api";
9
9
  import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
10
10
  import {APIError} from "./errors";
11
11
  import {clearMCPRegistry, getMCPRegistry} from "./mcp/registry";
12
12
  import {Permissions} from "./permissions";
13
+ import type {AnyTerrenoAccess} from "./rbac/types";
13
14
  import {
14
15
  authAsUser,
15
16
  type Food,
@@ -403,7 +404,7 @@ describe("@terreno/api", () => {
403
404
  read: [Permissions.IsAny],
404
405
  update: [Permissions.IsAny],
405
406
  },
406
- responseHandler: async (_data, method) => {
407
+ responseHandler: async (_data, method): Promise<JSONValue> => {
407
408
  if (method === "list") {
408
409
  return {custom: "response"};
409
410
  }
@@ -1443,7 +1444,7 @@ describe("@terreno/api", () => {
1443
1444
 
1444
1445
  it("model.create validation error is handled", async () => {
1445
1446
  // Use a model that has required fields
1446
- const {RequiredModel} = await import("./tests");
1447
+ const {RequiredModel} = await import("./tests.js");
1447
1448
 
1448
1449
  app.use(
1449
1450
  "/required",
@@ -2234,8 +2235,8 @@ describe("@terreno/api", () => {
2234
2235
  }),
2235
2236
  queryFilter: async (): Promise<Record<string, unknown>> => ({}),
2236
2237
  statements: {food: ["list", "read", "create", "update", "delete"]},
2237
- };
2238
- registration._buildWithContext({accessControl: accessControl as never});
2238
+ } as unknown as AnyTerrenoAccess;
2239
+ registration._buildWithContext({accessControl});
2239
2240
 
2240
2241
  const after = getMCPRegistry()[0];
2241
2242
  expect(after?.options.accessControl).toBe(accessControl);
@@ -2253,10 +2254,10 @@ describe("@terreno/api", () => {
2253
2254
  }),
2254
2255
  queryFilter: async (): Promise<Record<string, unknown>> => ({}),
2255
2256
  statements: {food: ["list", "read", "create", "update", "delete"]},
2256
- };
2257
+ } as unknown as AnyTerrenoAccess;
2257
2258
  modelRouter(FoodModel, {
2258
2259
  access: {resource: "food"},
2259
- accessControl: accessControl as never,
2260
+ accessControl,
2260
2261
  mcp: {methods: ["list"]},
2261
2262
  permissions: {
2262
2263
  create: [Permissions.IsAny],
package/src/api.ts CHANGED
@@ -264,7 +264,7 @@ export interface ModelRouterOptions<T> {
264
264
  preCreate?: (
265
265
  value: Partial<T> | (Partial<T> | undefined)[] | null | undefined,
266
266
  request: express.Request
267
- ) => T | Promise<T> | null;
267
+ ) => T | null | Promise<T | null>;
268
268
  /**
269
269
  * Hook that runs after `transformer.transform` but before changes are made for update operations.
270
270
  * Can update the body fields based on the request or the user.
@@ -274,7 +274,7 @@ export interface ModelRouterOptions<T> {
274
274
  * @param value - The request body relative to the model update (type: Partial<T>). Note: this does not contain the entire document to be updated, only the fields being updated.
275
275
  * @param request - The Express request object.
276
276
  */
277
- preUpdate?: (value: Partial<T>, request: express.Request) => T | Promise<T> | null;
277
+ preUpdate?: (value: Partial<T>, request: express.Request) => T | null | Promise<T | null>;
278
278
  /**
279
279
  * Hook that runs after `transformer.transform` but before the object is deleted.
280
280
  * Return null to return a generic 403 error.
@@ -283,7 +283,7 @@ export interface ModelRouterOptions<T> {
283
283
  * @param value - The document to be deleted, before the soft update of deleted: true (type: T).
284
284
  * @param request - The Express request object.
285
285
  */
286
- preDelete?: (value: T, request: express.Request) => T | Promise<T> | null;
286
+ preDelete?: (value: T, request: express.Request) => T | null | Promise<T | null>;
287
287
  /**
288
288
  * Hook that runs after the object is created but before the responseHandler serializes and
289
289
  * returned. This is a good spot to perform dependent changes to other models or performing async
@@ -48,7 +48,7 @@ describe("AuditApp", () => {
48
48
 
49
49
  it("does not register AuditEvent on the default connection when @terreno/api is imported", async () => {
50
50
  deleteAuditEventModel();
51
- await import("../index");
51
+ await import("../index.js");
52
52
  assert.isUndefined(mongoose.connection.models.TerrenoAuditEvent);
53
53
  });
54
54
 
@@ -2,6 +2,7 @@ import {describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
 
4
4
  import {APIError} from "../errors";
5
+ import {partialEnv} from "../tests/testEnv";
5
6
  import {auditEnqueueFromEnv, createCloudTasksAuditEnqueue} from "./cloudTasksEnqueue";
6
7
  import type {AuditEventWrite} from "./record";
7
8
 
@@ -102,23 +103,27 @@ describe("createCloudTasksAuditEnqueue", () => {
102
103
 
103
104
  describe("auditEnqueueFromEnv", () => {
104
105
  it("returns undefined until project, location, queue, url, and secret are set", () => {
105
- assert.isUndefined(auditEnqueueFromEnv({}));
106
+ assert.isUndefined(auditEnqueueFromEnv(partialEnv({})));
106
107
  assert.isUndefined(
107
- auditEnqueueFromEnv({
108
- AUDIT_TASKS_SECRET: "s",
109
- AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
110
- GCP_LOCATION: "us-central1",
111
- GCP_PROJECT: "proj",
112
- })
108
+ auditEnqueueFromEnv(
109
+ partialEnv({
110
+ AUDIT_TASKS_SECRET: "s",
111
+ AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
112
+ GCP_LOCATION: "us-central1",
113
+ GCP_PROJECT: "proj",
114
+ })
115
+ )
113
116
  );
114
117
  assert.isDefined(
115
- auditEnqueueFromEnv({
116
- AUDIT_TASKS_SECRET: "s",
117
- AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
118
- GCP_LOCATION: "us-central1",
119
- GCP_PROJECT: "proj",
120
- GCP_TASKS_AUDIT_QUEUE: "audit-q",
121
- })
118
+ auditEnqueueFromEnv(
119
+ partialEnv({
120
+ AUDIT_TASKS_SECRET: "s",
121
+ AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
122
+ GCP_LOCATION: "us-central1",
123
+ GCP_PROJECT: "proj",
124
+ GCP_TASKS_AUDIT_QUEUE: "audit-q",
125
+ })
126
+ )
122
127
  );
123
128
  });
124
129
  });
package/src/auth.test.ts CHANGED
@@ -966,7 +966,7 @@ describe("addMeRoutes edge cases", () => {
966
966
  it("PATCH /auth/me returns 404 when user is deleted after auth", async () => {
967
967
  const [_admin, notAdmin] = await setupDb();
968
968
  const jwtLib = (await import("jsonwebtoken")).default;
969
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
969
+ const notAdminId = notAdmin._id;
970
970
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
971
971
  issuer: process.env.TOKEN_ISSUER,
972
972
  });
@@ -1172,7 +1172,7 @@ describe("privileged user fields", () => {
1172
1172
  it("does not let PATCH /auth/me escalate to admin or join organizations", async () => {
1173
1173
  const [_admin, notAdmin] = await setupDb();
1174
1174
  const jwtLib = (await import("jsonwebtoken")).default;
1175
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1175
+ const notAdminId = notAdmin._id;
1176
1176
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1177
1177
  issuer: process.env.TOKEN_ISSUER,
1178
1178
  });
@@ -1202,7 +1202,7 @@ describe("privileged user fields", () => {
1202
1202
  it("clears email verification when PATCH /auth/me changes the mailbox", async () => {
1203
1203
  const [_admin, notAdmin] = await setupDb();
1204
1204
  const jwtLib = (await import("jsonwebtoken")).default;
1205
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1205
+ const notAdminId = notAdmin._id;
1206
1206
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1207
1207
  issuer: process.env.TOKEN_ISSUER,
1208
1208
  });
@@ -1221,7 +1221,7 @@ describe("privileged user fields", () => {
1221
1221
  it("keeps email verification for a casing-only email update", async () => {
1222
1222
  const [_admin, notAdmin] = await setupDb();
1223
1223
  const jwtLib = (await import("jsonwebtoken")).default;
1224
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1224
+ const notAdminId = notAdmin._id;
1225
1225
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1226
1226
  issuer: process.env.TOKEN_ISSUER,
1227
1227
  });
@@ -1452,8 +1452,22 @@ describe("PATCH /auth/me email change step-up", () => {
1452
1452
  });
1453
1453
  });
1454
1454
 
1455
+ interface IdentityUser {
1456
+ admin: boolean;
1457
+ betterAuthId?: string;
1458
+ email?: string;
1459
+ githubId?: string;
1460
+ githubUsername?: string;
1461
+ /** passport-local-mongoose credential fields, selected explicitly with `+hash +salt`. */
1462
+ hash?: string;
1463
+ name?: string;
1464
+ oauthProvider?: string;
1465
+ salt?: string;
1466
+ tokenEpoch: number;
1467
+ }
1468
+
1455
1469
  // A user schema that declares the identity-binding fields Better Auth and GitHub linking add.
1456
- const identityUserSchema = new Schema({
1470
+ const identityUserSchema = new Schema<IdentityUser>({
1457
1471
  admin: {default: false, description: "Admin flag", type: Boolean},
1458
1472
  betterAuthId: {description: "Better Auth user id", type: String},
1459
1473
  email: {description: "Email", type: String},
@@ -1467,8 +1481,8 @@ identityUserSchema.plugin(
1467
1481
  );
1468
1482
  identityUserSchema.plugin(githubUserPlugin);
1469
1483
  const IdentityUserModel =
1470
- (mongoose.models.AuthIdentityUser as mongoose.Model<Record<string, unknown>> | undefined) ??
1471
- mongoose.model("AuthIdentityUser", identityUserSchema);
1484
+ (mongoose.models.AuthIdentityUser as mongoose.Model<IdentityUser> | undefined) ??
1485
+ mongoose.model<IdentityUser>("AuthIdentityUser", identityUserSchema);
1472
1486
 
1473
1487
  describe("self-service identity and credential fields", () => {
1474
1488
  const identityFields = {
@@ -8,7 +8,7 @@ import {MAX_PASSWORD_LENGTH} from "./auth";
8
8
  import {changeUserPassword} from "./authRecovery";
9
9
  import {AuthToken} from "./authTokens";
10
10
  import {TerrenoApp} from "./terrenoApp";
11
- import {setupDb, UserModel} from "./tests";
11
+ import {authUserModel, setupDb, UserModel} from "./tests";
12
12
 
13
13
  interface CapturedMail {
14
14
  html?: string;
@@ -41,7 +41,7 @@ describe("password reset routes", () => {
41
41
  },
42
42
  },
43
43
  skipListen: true,
44
- userModel: UserModel,
44
+ userModel: authUserModel,
45
45
  }).build();
46
46
  });
47
47
 
@@ -171,7 +171,7 @@ describe("password reset routes", () => {
171
171
  publicAppUrl: "https://app.example.com",
172
172
  },
173
173
  skipListen: true,
174
- userModel: UserModel,
174
+ userModel: authUserModel,
175
175
  }).build();
176
176
 
177
177
  await supertest(noLegacyAliasApp).post("/resetPassword").send({}).expect(404);
@@ -185,7 +185,7 @@ describe("password reset routes", () => {
185
185
  publicAppUrl: "https://app.example.com",
186
186
  },
187
187
  skipListen: true,
188
- userModel: UserModel,
188
+ userModel: authUserModel,
189
189
  }).build();
190
190
 
191
191
  await supertest(noPasswordResetApp).post("/auth/forgotPassword").send({}).expect(404);
@@ -200,7 +200,7 @@ describe("password reset routes", () => {
200
200
  publicAppUrl: "https://app.example.com",
201
201
  },
202
202
  skipListen: true,
203
- userModel: UserModel,
203
+ userModel: authUserModel,
204
204
  }).build();
205
205
 
206
206
  await supertest(noEmailVerificationApp).post("/auth/sendVerification").send({}).expect(404);
@@ -220,7 +220,7 @@ describe("password reset routes", () => {
220
220
  },
221
221
  },
222
222
  skipListen: true,
223
- userModel: UserModel,
223
+ userModel: authUserModel,
224
224
  }).build();
225
225
 
226
226
  await supertest(bridgedApp)
@@ -322,7 +322,7 @@ describe("password reset routes", () => {
322
322
  },
323
323
  },
324
324
  skipListen: true,
325
- userModel: UserModel,
325
+ userModel: authUserModel,
326
326
  }).build();
327
327
  const before = await AuthToken.countDocuments({});
328
328
  await supertest(noUrlApp)
@@ -359,7 +359,7 @@ describe("password reset routes", () => {
359
359
  publicAppUrl: "https://app.example.com",
360
360
  },
361
361
  skipListen: true,
362
- userModel: UserModel,
362
+ userModel: authUserModel,
363
363
  }).build();
364
364
  await supertest(consoleApp)
365
365
  .post("/auth/forgotPassword")
@@ -376,7 +376,7 @@ describe("password reset routes", () => {
376
376
  publicAppUrl: "https://app.example.com",
377
377
  },
378
378
  skipListen: true,
379
- userModel: UserModel,
379
+ userModel: authUserModel,
380
380
  }).build();
381
381
  await supertest(consoleApp)
382
382
  .post("/auth/forgotPassword")
@@ -402,7 +402,7 @@ describe("changeUserPassword", () => {
402
402
  },
403
403
  },
404
404
  skipListen: true,
405
- userModel: UserModel,
405
+ userModel: authUserModel,
406
406
  }).build();
407
407
  const login = await supertest(app)
408
408
  .post("/auth/login")
@@ -8,7 +8,7 @@ import supertest from "supertest";
8
8
  import type {UserModel as AuthUserModel} from "./auth";
9
9
  import {AuthToken} from "./authTokens";
10
10
  import {TerrenoApp} from "./terrenoApp";
11
- import {setupDb, UserModel} from "./tests";
11
+ import {authUserModel, setupDb, UserModel} from "./tests";
12
12
 
13
13
  interface CapturedMail {
14
14
  html?: string;
@@ -44,7 +44,7 @@ describe("email verification gating", () => {
44
44
  },
45
45
  },
46
46
  skipListen: true,
47
- userModel: UserModel,
47
+ userModel: authUserModel,
48
48
  }).build();
49
49
 
50
50
  openApp = new TerrenoApp({
@@ -55,7 +55,7 @@ describe("email verification gating", () => {
55
55
  },
56
56
  },
57
57
  skipListen: true,
58
- userModel: UserModel,
58
+ userModel: authUserModel,
59
59
  }).build();
60
60
  });
61
61
 
@@ -109,7 +109,7 @@ describe("email verification gating", () => {
109
109
  },
110
110
  },
111
111
  skipListen: true,
112
- userModel: UserModel,
112
+ userModel: authUserModel,
113
113
  }).build();
114
114
 
115
115
  await supertest(noVerificationRoutesApp)
@@ -144,7 +144,7 @@ describe("email verification gating", () => {
144
144
  },
145
145
  },
146
146
  skipListen: true,
147
- userModel: UserModel,
147
+ userModel: authUserModel,
148
148
  }).build();
149
149
  const login = await supertest(failingApp)
150
150
  .post("/auth/login")
@@ -165,7 +165,7 @@ describe("email verification gating", () => {
165
165
  },
166
166
  },
167
167
  skipListen: true,
168
- userModel: UserModel,
168
+ userModel: authUserModel,
169
169
  }).build();
170
170
  const login = await supertest(noUrlApp)
171
171
  .post("/auth/login")
@@ -275,7 +275,7 @@ describe("email verification gating", () => {
275
275
  }
276
276
  );
277
277
  const JwtResetOnlyUser = (mongoose.models.JwtResetOnlyUser ??
278
- mongoose.model("JwtResetOnlyUser", jwtResetOnlySchema)) as AuthUserModel;
278
+ mongoose.model("JwtResetOnlyUser", jwtResetOnlySchema)) as unknown as AuthUserModel;
279
279
  await JwtResetOnlyUser.deleteMany({});
280
280
  const registerable = JwtResetOnlyUser as unknown as {
281
281
  register: (
@@ -2,6 +2,7 @@ import {afterAll, describe, expect, it} from "bun:test";
2
2
  import {createVerify, generateKeyPairSync} from "node:crypto";
3
3
  import type {BetterAuthPlugin} from "better-auth";
4
4
  import {twoFactor} from "better-auth/plugins";
5
+ import type {GoogleProfile} from "better-auth/social-providers";
5
6
  import express from "express";
6
7
  import {DateTime} from "luxon";
7
8
  import mongoose, {Schema} from "mongoose";
@@ -325,8 +326,8 @@ describe("signUp: closed", () => {
325
326
  socialProviders: {
326
327
  google: {
327
328
  getUserInfo: async () => ({
328
- data: {sub: "google-sub"},
329
- user: {email, emailVerified: true, id: "google-sub", name: "Google User"},
329
+ data: {sub: "google-sub"} as GoogleProfile,
330
+ user: {email, emailVerified: true, name: "Google User"},
330
331
  }),
331
332
  verifyIdToken: async () => true,
332
333
  },
@@ -782,7 +782,9 @@ describe("syncBetterAuthUser email matches", () => {
782
782
 
783
783
  await syncBetterAuthUser(userModel, unverifiedUser(email), undefined, {password: PASSWORD});
784
784
 
785
- const stored = await LinkingUser.collection.findOne({_id: legacy._id});
785
+ const stored = await LinkingUser.collection.findOne({
786
+ _id: legacy._id as mongoose.Types.ObjectId,
787
+ });
786
788
  expect(typeof stored?.hash).toBe("string");
787
789
  });
788
790