@terreno/api 0.31.0 → 56.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/CHANGELOG.md +122 -2
  2. package/LICENSE +202 -21
  3. package/dist/api.d.ts +12 -3
  4. package/dist/api.js +110 -361
  5. package/dist/auth.d.ts +26 -0
  6. package/dist/auth.js +100 -1
  7. package/dist/betterAuth.d.ts +5 -0
  8. package/dist/betterAuthSetup.d.ts +1 -15
  9. package/dist/betterAuthSetup.js +29 -8
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/docLoader.js +12 -9
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.js +29 -1
  14. package/dist/expressServer.js +5 -11
  15. package/dist/githubAuth.js +4 -1
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +29 -1
  18. package/dist/middleware.d.ts +7 -0
  19. package/dist/middleware.js +16 -1
  20. package/dist/openApiCompat.d.ts +10 -1
  21. package/dist/openApiCompat.js +115 -47
  22. package/dist/permissions.d.ts +27 -0
  23. package/dist/permissions.js +42 -1
  24. package/dist/plugins.d.ts +15 -3
  25. package/dist/plugins.js +36 -6
  26. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  27. package/dist/realtime/changeStreamWatcher.js +542 -137
  28. package/dist/realtime/realtimeApp.d.ts +3 -1
  29. package/dist/realtime/realtimeApp.js +75 -27
  30. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  31. package/dist/realtime/sessionRevalidation.js +438 -0
  32. package/dist/realtime/socketAuth.d.ts +97 -0
  33. package/dist/realtime/socketAuth.js +272 -0
  34. package/dist/realtime/socketUser.d.ts +54 -0
  35. package/dist/realtime/socketUser.js +75 -5
  36. package/dist/realtime/types.d.ts +40 -0
  37. package/dist/secretProviders.d.ts +23 -0
  38. package/dist/secretProviders.js +9 -3
  39. package/dist/sync/executors.d.ts +198 -0
  40. package/dist/sync/executors.js +670 -0
  41. package/dist/sync/loadHarness.js +807 -0
  42. package/dist/sync/models.d.ts +216 -0
  43. package/dist/sync/models.js +644 -0
  44. package/dist/sync/mutationHandler.d.ts +97 -0
  45. package/dist/sync/mutationHandler.js +886 -0
  46. package/dist/sync/registry.d.ts +73 -0
  47. package/dist/sync/registry.js +223 -0
  48. package/dist/sync/routes.d.ts +62 -0
  49. package/dist/sync/routes.js +936 -0
  50. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  51. package/dist/sync/scripts/compactTombstones.js +270 -0
  52. package/dist/sync/serialize.d.ts +20 -0
  53. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  54. package/dist/sync/socketHandlers.d.ts +54 -0
  55. package/dist/sync/socketHandlers.js +470 -0
  56. package/dist/sync/streams.d.ts +85 -0
  57. package/dist/sync/streams.js +221 -0
  58. package/dist/sync/syncApp.d.ts +29 -0
  59. package/dist/sync/syncApp.js +44 -0
  60. package/dist/sync/syncBatch.d.ts +71 -0
  61. package/dist/sync/syncBatch.js +252 -0
  62. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  63. package/dist/sync/syncSeqPlugin.js +903 -0
  64. package/dist/sync/types.d.ts +254 -0
  65. package/dist/sync/types.js +9 -0
  66. package/dist/terrenoApp.js +90 -27
  67. package/dist/tests/models.d.ts +11 -27
  68. package/dist/tests/models.js +3 -5
  69. package/dist/tests/testHelper.d.ts +3 -9
  70. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  71. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  72. package/package.json +10 -8
  73. package/src/__tests__/openApiCompat.test.ts +20 -0
  74. package/src/actions.test.ts +12 -19
  75. package/src/actions.ts +2 -2
  76. package/src/api.coverage.test.ts +9 -7
  77. package/src/api.errorPaths.test.ts +1 -47
  78. package/src/api.test.ts +12 -0
  79. package/src/api.ts +98 -317
  80. package/src/auth.test.ts +128 -176
  81. package/src/auth.ts +109 -0
  82. package/src/betterAuth.ts +6 -0
  83. package/src/betterAuthSetup.test.ts +34 -0
  84. package/src/betterAuthSetup.ts +27 -8
  85. package/src/configurationPlugin.ts +2 -2
  86. package/src/consentApp.test.ts +12 -12
  87. package/src/docLoader.ts +3 -1
  88. package/src/errors.ts +33 -0
  89. package/src/expressServer.test.ts +7 -1
  90. package/src/expressServer.ts +5 -11
  91. package/src/githubAuth.ts +3 -1
  92. package/src/index.ts +42 -0
  93. package/src/middleware.test.ts +40 -1
  94. package/src/middleware.ts +15 -0
  95. package/src/models/versionConfig.ts +1 -1
  96. package/src/openApiBuilder.test.ts +9 -24
  97. package/src/openApiCompat.ts +99 -45
  98. package/src/openApiValidator.test.ts +0 -41
  99. package/src/permissions.test.ts +75 -1
  100. package/src/permissions.ts +49 -0
  101. package/src/plugins.test.ts +54 -14
  102. package/src/plugins.ts +47 -9
  103. package/src/populate.test.ts +16 -25
  104. package/src/realtime/changeStreamWatcher.ts +552 -114
  105. package/src/realtime/realtime.test.ts +157 -239
  106. package/src/realtime/realtimeApp.ts +80 -19
  107. package/src/realtime/sessionRevalidation.test.ts +423 -0
  108. package/src/realtime/sessionRevalidation.ts +273 -0
  109. package/src/realtime/socketAuth.test.ts +355 -0
  110. package/src/realtime/socketAuth.ts +228 -0
  111. package/src/realtime/socketUser.ts +69 -0
  112. package/src/realtime/types.ts +40 -0
  113. package/src/secretProviders.test.ts +7 -1
  114. package/src/secretProviders.ts +15 -3
  115. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  116. package/src/sync/executors.test.ts +882 -0
  117. package/src/sync/executors.ts +703 -0
  118. package/src/sync/integration.test.ts +1160 -0
  119. package/src/sync/loadHarness.ts +618 -0
  120. package/src/sync/models.ts +640 -0
  121. package/src/sync/mutationHandler.test.ts +1252 -0
  122. package/src/sync/mutationHandler.ts +850 -0
  123. package/src/sync/registry.ts +232 -0
  124. package/src/sync/routes.ts +812 -0
  125. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  126. package/src/sync/scripts/compactTombstones.ts +145 -0
  127. package/src/sync/serialize.ts +48 -0
  128. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  129. package/src/sync/socketHandlers.ts +320 -0
  130. package/src/sync/streams.ts +188 -0
  131. package/src/sync/sync.test.ts +582 -0
  132. package/src/sync/syncApp.ts +44 -0
  133. package/src/sync/syncBatch.ts +219 -0
  134. package/src/sync/syncFrontier.test.ts +494 -0
  135. package/src/sync/syncPhaseC.test.ts +718 -0
  136. package/src/sync/syncRoutes.test.ts +865 -0
  137. package/src/sync/syncSeqPlugin.ts +738 -0
  138. package/src/sync/syncSocket.test.ts +1440 -0
  139. package/src/sync/types.ts +270 -0
  140. package/src/terrenoApp.ts +37 -17
  141. package/src/tests/bunSetup.ts +8 -0
  142. package/src/tests/models.ts +6 -8
  143. package/tsconfig.json +4 -4
  144. package/tsconfig.typedoc.json +7 -1
  145. package/dist/__tests__/openApiCompat.test.js +0 -317
  146. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  147. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  148. package/dist/actions.openApi.test.d.ts +0 -1
  149. package/dist/actions.openApi.test.js +0 -253
  150. package/dist/actions.test.d.ts +0 -1
  151. package/dist/actions.test.js +0 -1087
  152. package/dist/api.arrayOperations.test.d.ts +0 -1
  153. package/dist/api.arrayOperations.test.js +0 -878
  154. package/dist/api.asyncHandler.test.d.ts +0 -1
  155. package/dist/api.asyncHandler.test.js +0 -236
  156. package/dist/api.coverage.test.d.ts +0 -1
  157. package/dist/api.coverage.test.js +0 -192
  158. package/dist/api.errorPaths.test.d.ts +0 -1
  159. package/dist/api.errorPaths.test.js +0 -887
  160. package/dist/api.errors.test.d.ts +0 -1
  161. package/dist/api.errors.test.js +0 -185
  162. package/dist/api.hooks.test.d.ts +0 -1
  163. package/dist/api.hooks.test.js +0 -950
  164. package/dist/api.query.test.d.ts +0 -1
  165. package/dist/api.query.test.js +0 -948
  166. package/dist/api.test.d.ts +0 -1
  167. package/dist/api.test.js +0 -2820
  168. package/dist/auth.compile.test.d.ts +0 -1
  169. package/dist/auth.compile.test.js +0 -201
  170. package/dist/auth.coverage.test.d.ts +0 -1
  171. package/dist/auth.coverage.test.js +0 -202
  172. package/dist/auth.test.d.ts +0 -1
  173. package/dist/auth.test.js +0 -2286
  174. package/dist/betterAuth.test.d.ts +0 -1
  175. package/dist/betterAuth.test.js +0 -181
  176. package/dist/betterAuthApp.test.d.ts +0 -1
  177. package/dist/betterAuthApp.test.js +0 -242
  178. package/dist/betterAuthSetup.test.d.ts +0 -1
  179. package/dist/betterAuthSetup.test.js +0 -762
  180. package/dist/config.test.d.ts +0 -1
  181. package/dist/config.test.js +0 -353
  182. package/dist/configuration.test.d.ts +0 -1
  183. package/dist/configuration.test.js +0 -980
  184. package/dist/configurationPlugin.test.d.ts +0 -1
  185. package/dist/configurationPlugin.test.js +0 -827
  186. package/dist/consentApp.test.d.ts +0 -1
  187. package/dist/consentApp.test.js +0 -1411
  188. package/dist/docLoader.test.d.ts +0 -1
  189. package/dist/docLoader.test.js +0 -137
  190. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  191. package/dist/envConfigurationPlugin.test.js +0 -369
  192. package/dist/errors.test.d.ts +0 -1
  193. package/dist/errors.test.js +0 -607
  194. package/dist/expressServer.test.d.ts +0 -1
  195. package/dist/expressServer.test.js +0 -1249
  196. package/dist/githubAuth.test.d.ts +0 -1
  197. package/dist/githubAuth.test.js +0 -1142
  198. package/dist/httpClient.test.d.ts +0 -1
  199. package/dist/httpClient.test.js +0 -1471
  200. package/dist/logger.test.d.ts +0 -1
  201. package/dist/logger.test.js +0 -685
  202. package/dist/middleware.test.d.ts +0 -1
  203. package/dist/middleware.test.js +0 -241
  204. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  205. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  206. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  207. package/dist/notifiers/slackNotifier.test.js +0 -297
  208. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  209. package/dist/notifiers/zoomNotifier.test.js +0 -373
  210. package/dist/openApi.test.d.ts +0 -1
  211. package/dist/openApi.test.js +0 -620
  212. package/dist/openApiBuilder.test.d.ts +0 -1
  213. package/dist/openApiBuilder.test.js +0 -599
  214. package/dist/openApiEtag.test.d.ts +0 -1
  215. package/dist/openApiEtag.test.js +0 -86
  216. package/dist/openApiValidator.test.d.ts +0 -1
  217. package/dist/openApiValidator.test.js +0 -795
  218. package/dist/permissions.middleware.test.d.ts +0 -1
  219. package/dist/permissions.middleware.test.js +0 -308
  220. package/dist/permissions.test.d.ts +0 -1
  221. package/dist/permissions.test.js +0 -439
  222. package/dist/plugins.test.d.ts +0 -1
  223. package/dist/plugins.test.js +0 -902
  224. package/dist/populate.test.d.ts +0 -1
  225. package/dist/populate.test.js +0 -370
  226. package/dist/realtime/realtime.test.d.ts +0 -10
  227. package/dist/realtime/realtime.test.js +0 -4213
  228. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  229. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  230. package/dist/requestContext.test.d.ts +0 -1
  231. package/dist/requestContext.test.js +0 -412
  232. package/dist/scriptRunner.test.d.ts +0 -1
  233. package/dist/scriptRunner.test.js +0 -386
  234. package/dist/secretProviders.test.d.ts +0 -1
  235. package/dist/secretProviders.test.js +0 -726
  236. package/dist/syncConsents.test.d.ts +0 -1
  237. package/dist/syncConsents.test.js +0 -522
  238. package/dist/terrenoApp.test.d.ts +0 -1
  239. package/dist/terrenoApp.test.js +0 -489
  240. package/dist/tests/bunSetup.d.ts +0 -1
  241. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  242. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  243. package/dist/tests/testEnv.d.ts +0 -0
  244. package/dist/tests/testEnv.js +0 -6
  245. package/dist/transformers.test.d.ts +0 -1
  246. package/dist/transformers.test.js +0 -423
  247. package/dist/utils.test.d.ts +0 -1
  248. package/dist/utils.test.js +0 -242
  249. package/src/realtime/realtimeAppSetup.test.ts +0 -161
  250. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -1,27 +1,26 @@
1
+ // noExplicitAny: test mock typing
2
+ // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
1
3
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
4
  import type express from "express";
3
- import type {HydratedDocument} from "mongoose";
4
5
  import supertest from "supertest";
5
6
  import type TestAgent from "supertest/lib/agent";
6
- import type {UserModel as UserMongooseModel} from "./auth";
7
- import {ConsentApp, type ConsentAppOptions} from "./consentApp";
7
+ import {ConsentApp} from "./consentApp";
8
8
  import {ConsentForm} from "./models/consentForm";
9
9
  import {ConsentResponse} from "./models/consentResponse";
10
10
  import {TerrenoApp} from "./terrenoApp";
11
- import {authAsUser, setupDb, type User, UserModel} from "./tests";
12
- import type {ConsentFormDocument} from "./types/consentForm";
11
+ import {authAsUser, setupDb, UserModel} from "./tests";
13
12
 
14
- const buildApp = (consentAppOptions: ConsentAppOptions = {}): express.Application =>
13
+ const buildApp = (consentAppOptions = {}): express.Application =>
15
14
  new TerrenoApp({
16
15
  skipListen: true,
17
- userModel: UserModel as unknown as UserMongooseModel,
16
+ userModel: UserModel as any,
18
17
  })
19
18
  .register(new ConsentApp(consentAppOptions))
20
19
  .build();
21
20
 
22
21
  describe("ConsentApp", () => {
23
- let admin: HydratedDocument<User>;
24
- let notAdmin: HydratedDocument<User>;
22
+ let admin: any;
23
+ let notAdmin: any;
25
24
  let adminAgent: TestAgent;
26
25
  let userAgent: TestAgent;
27
26
 
@@ -345,7 +344,8 @@ describe("ConsentApp", () => {
345
344
 
346
345
  // Build app with resolver that only returns privacy forms
347
346
  const filteredApp = buildApp({
348
- resolveConsentForms: (_user, forms) => forms.filter((f) => f.type === "privacy"),
347
+ resolveConsentForms: (_user: any, forms: any[]) =>
348
+ forms.filter((f) => f.type === "privacy"),
349
349
  });
350
350
  const filteredAgent = await authAsUser(filteredApp, "notAdmin");
351
351
 
@@ -367,7 +367,7 @@ describe("ConsentApp", () => {
367
367
 
368
368
  // Build app with resolver that skips admin users
369
369
  const filteredApp = buildApp({
370
- resolveConsentForms: (user, forms) => (user.admin ? [] : forms),
370
+ resolveConsentForms: (user: any, forms: any[]) => (user.admin ? [] : forms),
371
371
  });
372
372
  const filteredAdmin = await authAsUser(filteredApp, "admin");
373
373
  const filteredUser = await authAsUser(filteredApp, "notAdmin");
@@ -388,7 +388,7 @@ describe("ConsentApp", () => {
388
388
  });
389
389
 
390
390
  describe("POST /consents/respond", () => {
391
- let form: ConsentFormDocument;
391
+ let form: any;
392
392
 
393
393
  beforeEach(async () => {
394
394
  form = await ConsentForm.create({
package/src/docLoader.ts CHANGED
@@ -35,8 +35,10 @@ export const loadDocOr404 = async <T>(
35
35
  });
36
36
  }
37
37
  if (!data) {
38
+ const idSchemaType = model.schema?.path("_id");
39
+ const hiddenId = idSchemaType?.instance === "String" ? id : new mongoose.Types.ObjectId(id);
38
40
  const hiddenDoc = await model.collection.findOne({
39
- _id: new mongoose.Types.ObjectId(id),
41
+ _id: hiddenId as never,
40
42
  });
41
43
 
42
44
  const notFoundDetail = `Document ${id} not found for model ${model.modelName}`;
package/src/errors.ts CHANGED
@@ -478,6 +478,39 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
478
478
  return null;
479
479
  };
480
480
 
481
+ /**
482
+ * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
483
+ * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
484
+ * anything else is wrapped in the given framework error. `wrapper` may override any field,
485
+ * including `detail`, which defaults to the caught error's text.
486
+ */
487
+ export const passthroughOrWrap = (error: unknown, wrapper: APIErrorOptions): APIError => {
488
+ if (isAPIError(error)) {
489
+ return error;
490
+ }
491
+ return new APIError({
492
+ cause: error,
493
+ detail: errorDetail(error),
494
+ disableExternalErrorTracking: getDisableExternalErrorTracking(error),
495
+ ...wrapper,
496
+ });
497
+ };
498
+
499
+ /**
500
+ * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
501
+ * errors are converted first so their per-field messages survive as `meta.fields` instead of being
502
+ * flattened into the wrapper's `detail`.
503
+ */
504
+ export const passthroughOrWrapWrite = (error: unknown, wrapper: APIErrorOptions): APIError => {
505
+ if (!isAPIError(error) && error instanceof Error) {
506
+ const converted = mongooseErrorToAPIError(error);
507
+ if (converted) {
508
+ return converted;
509
+ }
510
+ }
511
+ return passthroughOrWrap(error, wrapper);
512
+ };
513
+
481
514
  // Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
482
515
  // Sentry unless external tracking is disabled. Fingerprints on the logical error type
483
516
  // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
@@ -833,7 +833,7 @@ describe("expressServer", () => {
833
833
  }
834
834
  });
835
835
 
836
- it("handles listen errors", () => {
836
+ it("handles listen errors", async () => {
837
837
  const configureApp = (): void => {};
838
838
  const http = require("node:http") as typeof import("node:http");
839
839
  const originalListen = http.Server.prototype.listen;
@@ -849,6 +849,12 @@ describe("expressServer", () => {
849
849
  skipListen: false,
850
850
  userModel: typedUserModel,
851
851
  }).start();
852
+ // start() defers listen behind an awaited ensureSyncIndexes(), so the
853
+ // exit-on-listen-error path settles asynchronously.
854
+ const deadline = Date.now() + 2_000;
855
+ while (exit.mock.calls.length === 0 && Date.now() < deadline) {
856
+ await new Promise((resolve) => setTimeout(resolve, 5));
857
+ }
852
858
  expect(exit).toHaveBeenCalledWith(1);
853
859
  } finally {
854
860
  http.Server.prototype.listen = originalListen;
@@ -7,7 +7,6 @@ import cloneDeep from "lodash/cloneDeep";
7
7
  import onFinished from "on-finished";
8
8
  import passport from "passport";
9
9
  import type {ModelRouterOptions} from "./api";
10
- import {APIError} from "./errors";
11
10
  import {type LoggingOptions, logger} from "./logger";
12
11
  import {sendToSlack} from "./notifiers/slackNotifier";
13
12
 
@@ -17,16 +16,16 @@ const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
17
16
 
18
17
  export const setupEnvironment = (): void => {
19
18
  if (!process.env.TOKEN_ISSUER) {
20
- throw new APIError({status: 500, title: "TOKEN_ISSUER must be set in env."});
19
+ throw new Error("TOKEN_ISSUER must be set in env.");
21
20
  }
22
21
  if (!process.env.TOKEN_SECRET) {
23
- throw new APIError({status: 500, title: "TOKEN_SECRET must be set."});
22
+ throw new Error("TOKEN_SECRET must be set.");
24
23
  }
25
24
  if (!process.env.REFRESH_TOKEN_SECRET) {
26
- throw new APIError({status: 500, title: "REFRESH_TOKEN_SECRET must be set."});
25
+ throw new Error("REFRESH_TOKEN_SECRET must be set.");
27
26
  }
28
27
  if (!process.env.SESSION_SECRET) {
29
- throw new APIError({status: 500, title: "SESSION_SECRET must be set."});
28
+ throw new Error("SESSION_SECRET must be set.");
30
29
  }
31
30
  if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
32
31
  logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
@@ -191,12 +190,7 @@ export const cronjob = (
191
190
  try {
192
191
  new cron.CronJob(cronSchedule, callback, null, true, "America/Chicago");
193
192
  } catch (error) {
194
- throw new APIError({
195
- cause: error,
196
- detail: `Failed to create cronjob ${name} with schedule ${cronSchedule}: ${error}`,
197
- status: 500,
198
- title: "Failed to create cronjob",
199
- });
193
+ throw new Error(`Failed to create cronjob: ${error}`);
200
194
  }
201
195
  };
202
196
 
package/src/githubAuth.ts CHANGED
@@ -90,7 +90,9 @@ export const setupGitHubAuth = (
90
90
 
91
91
  passport.use(
92
92
  "github",
93
- new GitHubStrategy(
93
+ // noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
94
+ // biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
95
+ new (GitHubStrategy as any)(
94
96
  {
95
97
  callbackURL: githubOptions.callbackURL,
96
98
  clientID: githubOptions.clientId,
package/src/index.ts CHANGED
@@ -29,6 +29,9 @@ export * from "./permissions";
29
29
  export * from "./plugins";
30
30
  export * from "./populate";
31
31
  export {
32
+ type AuthorizedEmitEntry,
33
+ emitPayloadToAuthorizedRoom,
34
+ emitSyncDeltaForChange,
32
35
  startChangeStreamWatcher,
33
36
  stopChangeStreamWatcher,
34
37
  } from "./realtime/changeStreamWatcher";
@@ -57,6 +60,32 @@ export {
57
60
  type RealtimeRegistryEntry,
58
61
  registerRealtime,
59
62
  } from "./realtime/registry";
63
+ export {
64
+ DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
65
+ loadFullUserForSocket,
66
+ type RevalidatableSocket,
67
+ type RevalidationOutcome,
68
+ reresolveSyncRoomsForSocket,
69
+ revalidateSocketSession,
70
+ runSessionRevalidationSweep,
71
+ type SessionRevalidationHandle,
72
+ type SessionRevalidationOptions,
73
+ startSessionRevalidationSweep,
74
+ } from "./realtime/sessionRevalidation";
75
+ export {
76
+ type AuthenticatableSocket,
77
+ type BetterAuthSocketOptions,
78
+ createBetterAuthValidator,
79
+ createLegacyJwtValidator,
80
+ createSocketAuthMiddleware,
81
+ type SocketAuthValidator,
82
+ } from "./realtime/socketAuth";
83
+ export {
84
+ type DecodedRealtimeToken,
85
+ getSocketUser,
86
+ type SocketDataBag,
87
+ type SocketWithDecodedToken,
88
+ } from "./realtime/socketUser";
60
89
  export type {
61
90
  ChangeStreamConfig,
62
91
  DocumentSubscription,
@@ -68,6 +97,19 @@ export type {
68
97
  export * from "./requestContext";
69
98
  export * from "./scriptRunner";
70
99
  export * from "./secretProviders";
100
+ export * from "./sync/executors";
101
+ export * from "./sync/models";
102
+ export * from "./sync/mutationHandler";
103
+ export * from "./sync/registry";
104
+ export * from "./sync/routes";
105
+ export * from "./sync/scripts/compactTombstones";
106
+ export * from "./sync/serialize";
107
+ export * from "./sync/socketHandlers";
108
+ export * from "./sync/streams";
109
+ export * from "./sync/syncApp";
110
+ export * from "./sync/syncBatch";
111
+ export * from "./sync/syncSeqPlugin";
112
+ export * from "./sync/types";
71
113
  export * from "./syncConsents";
72
114
  export * from "./terrenoApp";
73
115
  export * from "./terrenoPlugin";
@@ -3,7 +3,11 @@ import * as Sentry from "@sentry/bun";
3
3
  import express, {type NextFunction, type Request, type Response} from "express";
4
4
  import supertest from "supertest";
5
5
 
6
- import {jsonResponseRequestIdMiddleware, sentryAppVersionMiddleware} from "./middleware";
6
+ import {
7
+ jsonResponseRequestIdMiddleware,
8
+ requireAdminMiddleware,
9
+ sentryAppVersionMiddleware,
10
+ } from "./middleware";
7
11
  import {requestContextMiddleware} from "./requestContext";
8
12
 
9
13
  const buildReq = (headers: Record<string, string | undefined>): Request => {
@@ -14,6 +18,41 @@ const buildReq = (headers: Record<string, string | undefined>): Request => {
14
18
 
15
19
  const buildNext = (): Mock<() => void> => mock(() => {});
16
20
 
21
+ describe("requireAdminMiddleware", () => {
22
+ it("calls next when the user is an admin", () => {
23
+ const next = buildNext();
24
+ const req = {user: {admin: true}} as unknown as Request;
25
+
26
+ requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
27
+
28
+ expect(next).toHaveBeenCalledTimes(1);
29
+ });
30
+
31
+ it("throws a 403 APIError when the user is not an admin", () => {
32
+ const next = buildNext();
33
+ const req = {user: {admin: false}} as unknown as Request;
34
+
35
+ expect(() =>
36
+ requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction)
37
+ ).toThrow("Admin access required");
38
+ expect(next).not.toHaveBeenCalled();
39
+ });
40
+
41
+ it("throws a 403 APIError when there is no user", () => {
42
+ const next = buildNext();
43
+ const req = {} as unknown as Request;
44
+
45
+ let status: number | undefined;
46
+ try {
47
+ requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
48
+ } catch (error) {
49
+ status = (error as {status?: number}).status;
50
+ }
51
+ expect(status).toBe(403);
52
+ expect(next).not.toHaveBeenCalled();
53
+ });
54
+ });
55
+
17
56
  describe("sentryAppVersionMiddleware", () => {
18
57
  let setTagMock: Mock<(key: string, value: string) => void>;
19
58
 
package/src/middleware.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  import * as Sentry from "@sentry/bun";
2
2
  import type {NextFunction, Request, Response} from "express";
3
3
 
4
+ import {APIError} from "./errors";
4
5
  import {getCurrentRequestContext} from "./requestContext";
5
6
 
7
+ /**
8
+ * Express middleware that rejects the request with a 403 unless the authenticated user is an admin
9
+ * (`req.user.admin === true`). Run it after {@link authenticateMiddleware} so `req.user` is
10
+ * populated, e.g. `[authenticateMiddleware(), requireAdminMiddleware]`. Use this for admin-only
11
+ * custom routes instead of hand-rolling an inline admin guard.
12
+ */
13
+ export const requireAdminMiddleware = (req: Request, _res: Response, next: NextFunction): void => {
14
+ const user = req.user as {admin?: boolean} | undefined;
15
+ if (!user?.admin) {
16
+ throw new APIError({status: 403, title: "Admin access required"});
17
+ }
18
+ next();
19
+ };
20
+
6
21
  /**
7
22
  * Express middleware that captures the app version from the request header
8
23
  * and adds it as a tag to the current Sentry scope.
@@ -79,7 +79,7 @@ const versionConfigSchema = new mongoose.Schema<VersionConfigDocument, VersionCo
79
79
  // Enforce singleton: only one VersionConfig document can exist.
80
80
  // The _singleton field is always "config" (required, immutable, enum-constrained)
81
81
  // and a unique index guarantees at most one document.
82
- (versionConfigSchema as unknown as mongoose.Schema).add({
82
+ (versionConfigSchema as mongoose.Schema).add({
83
83
  _singleton: {
84
84
  default: "config",
85
85
  description: "Sentinel field to enforce singleton via unique index",
@@ -1,3 +1,5 @@
1
+ // noExplicitAny: test mock typing
2
+ // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
1
3
  import {beforeEach, describe, expect, it} from "bun:test";
2
4
  import type express from "express";
3
5
  import type {Router} from "express";
@@ -5,25 +7,12 @@ import supertest from "supertest";
5
7
  import type TestAgent from "supertest/lib/agent";
6
8
 
7
9
  import {type ModelRouterOptions, modelRouter} from "./api";
8
- import type {UserModel as AuthUserModel} from "./auth";
9
10
  import {createOpenApiBuilder, OpenApiMiddlewareBuilder} from "./openApiBuilder";
10
11
  import {Permissions} from "./permissions";
11
12
  import {TerrenoApp} from "./terrenoApp";
12
- import {type Food, FoodModel, UserModel} from "./tests";
13
-
14
- /** The subset of an OpenAPI parameter object the assertions below inspect. */
15
- interface OpenApiParameter {
16
- name: string;
17
- in: string;
18
- required?: boolean;
19
- description?: string;
20
- schema: {type: string};
21
- }
13
+ import {FoodModel, UserModel} from "./tests";
22
14
 
23
- function addRoutesWithBuilder(
24
- router: Router,
25
- options?: Partial<ModelRouterOptions<unknown>>
26
- ): void {
15
+ function addRoutesWithBuilder(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
27
16
  // Add a custom endpoint using the OpenApiMiddlewareBuilder
28
17
  const statsMiddleware = createOpenApiBuilder(options ?? {})
29
18
  .withTags(["Stats"])
@@ -135,8 +124,8 @@ function addRoutesWithBuilder(
135
124
  // Standard modelRouter for food
136
125
  router.use(
137
126
  "/food",
138
- modelRouter(FoodModel, {
139
- ...(options as Partial<ModelRouterOptions<Food>>),
127
+ modelRouter(FoodModel as any, {
128
+ ...options,
140
129
  allowAnonymous: true,
141
130
  permissions: {
142
131
  create: [Permissions.IsAny],
@@ -160,7 +149,7 @@ describe("OpenApiMiddlewareBuilder", () => {
160
149
  app = new TerrenoApp({
161
150
  configureApp: addRoutesWithBuilder,
162
151
  skipListen: true,
163
- userModel: UserModel as unknown as AuthUserModel,
152
+ userModel: UserModel as any,
164
153
  }).build();
165
154
  });
166
155
 
@@ -200,9 +189,7 @@ describe("OpenApiMiddlewareBuilder", () => {
200
189
  expect(statsPath.get.description).toBe("Returns aggregated statistics about food items");
201
190
 
202
191
  // Check query parameter
203
- const categoryParam = statsPath.get.parameters.find(
204
- (p: OpenApiParameter) => p.name === "category"
205
- );
192
+ const categoryParam = statsPath.get.parameters.find((p: any) => p.name === "category");
206
193
  expect(categoryParam).toBeDefined();
207
194
  expect(categoryParam.in).toBe("query");
208
195
  expect(categoryParam.schema.type).toBe("string");
@@ -282,9 +269,7 @@ describe("OpenApiMiddlewareBuilder", () => {
282
269
  const categoryPath = res.body.paths["/food/categories/{categoryId}"];
283
270
  expect(categoryPath).toBeDefined();
284
271
 
285
- const pathParam = categoryPath.get.parameters.find(
286
- (p: OpenApiParameter) => p.name === "categoryId"
287
- );
272
+ const pathParam = categoryPath.get.parameters.find((p: any) => p.name === "categoryId");
288
273
  expect(pathParam).toBeDefined();
289
274
  expect(pathParam.in).toBe("path");
290
275
  expect(pathParam.required).toBe(true);
@@ -8,9 +8,10 @@
8
8
  *
9
9
  * @see https://github.com/wesleytodd/express-openapi/issues/70
10
10
  */
11
- import type {Application, NextFunction, Request, Response} from "express";
11
+ import express, {type Application, type NextFunction, type Request, type Response} from "express";
12
12
 
13
13
  const MOUNT_PATH_KEY = "__openApiMountPath";
14
+ let isExpressRouterUsePatched = false;
14
15
 
15
16
  interface ExpressKey {
16
17
  name: string;
@@ -74,46 +75,64 @@ const buildRegexpForPath = (pathStr: string, isMount: boolean): RegExp => {
74
75
  return new RegExp(`^${pattern}\\/?$`);
75
76
  };
76
77
 
77
- const patchRouterStack = (stack: PatchedLayer[]): void => {
78
- for (const layer of stack) {
79
- if (layer.regexp !== undefined) {
80
- continue;
81
- }
78
+ const annotateMountLayers = (
79
+ stack: PatchedLayer[] | undefined,
80
+ stackBefore: number,
81
+ args: unknown[]
82
+ ): void => {
83
+ if (!stack) {
84
+ return;
85
+ }
82
86
 
83
- // Determine the path string for this layer
84
- let pathStr: string | undefined;
85
- const isMount = layer.name === "router" || !!layer.handle?.stack;
86
-
87
- if (layer.slash) {
88
- // Express 5 layers use .slash instead of .regexp.fast_slash
89
- layer.regexp = {fast_slash: true};
90
- } else if (layer[MOUNT_PATH_KEY]) {
91
- pathStr = layer[MOUNT_PATH_KEY];
92
- layer.regexp = buildRegexpForPath(pathStr, isMount);
93
- } else if (layer.path && typeof layer.path === "string") {
94
- pathStr = layer.path;
95
- layer.regexp = buildRegexpForPath(pathStr, false);
96
- } else if (layer.route?.path && typeof layer.route.path === "string") {
97
- pathStr = layer.route.path;
98
- layer.regexp = buildRegexpForPath(pathStr, false);
99
- } else {
100
- layer.regexp = /^\/?$/;
101
- }
87
+ const mountPath = typeof args[0] === "string" ? args[0] : undefined;
88
+ if (!mountPath || mountPath === "/") {
89
+ return;
90
+ }
91
+
92
+ const normalizedMountPath = mountPath.replace(/\/+$/, "");
93
+ for (let i = stackBefore; i < stack.length; i++) {
94
+ stack[i][MOUNT_PATH_KEY] = normalizedMountPath;
95
+ }
96
+ };
102
97
 
103
- // Populate keys in Express 4 format: [{name, optional}]
104
- // @wesleytodd/openapi reads layer.keys[i].name for path parameters
105
- if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
106
- if (pathStr) {
107
- layer.keys = extractKeysFromPath(pathStr);
98
+ const patchRouterStack = (stack: PatchedLayer[]): void => {
99
+ for (const layer of stack) {
100
+ if (layer.regexp === undefined) {
101
+ // Determine the path string for this layer
102
+ let pathStr: string | undefined;
103
+ const isMount = layer.name === "router" || !!layer.handle?.stack;
104
+
105
+ if (layer.slash) {
106
+ // Express 5 layers use .slash instead of .regexp.fast_slash
107
+ layer.regexp = {fast_slash: true};
108
+ } else if (layer[MOUNT_PATH_KEY]) {
109
+ pathStr = layer[MOUNT_PATH_KEY];
110
+ layer.regexp = buildRegexpForPath(pathStr, isMount);
111
+ } else if (layer.path && typeof layer.path === "string") {
112
+ pathStr = layer.path;
113
+ layer.regexp = buildRegexpForPath(pathStr, false);
114
+ } else if (layer.route?.path && typeof layer.route.path === "string") {
115
+ pathStr = layer.route.path;
116
+ layer.regexp = buildRegexpForPath(pathStr, false);
108
117
  } else {
109
- layer.keys = [];
118
+ layer.regexp = /^\/?$/;
119
+ }
120
+
121
+ // Populate keys in Express 4 format: [{name, optional}]
122
+ // @wesleytodd/openapi reads layer.keys[i].name for path parameters
123
+ if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
124
+ if (pathStr) {
125
+ layer.keys = extractKeysFromPath(pathStr);
126
+ } else {
127
+ layer.keys = [];
128
+ }
129
+ } else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
130
+ // Express 5 stores keys as plain strings after match() — convert to objects
131
+ layer.keys = (layer.keys as string[]).map((k) => ({name: k, optional: false}));
110
132
  }
111
- } else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
112
- // Express 5 stores keys as plain strings after match() — convert to objects
113
- layer.keys = (layer.keys as string[]).map((k) => ({name: k, optional: false}));
114
133
  }
115
134
 
116
- // Recursively patch nested stacks
135
+ // Recursively patch nested stacks even when this layer already had a regexp.
117
136
  if (layer.handle?.stack) {
118
137
  patchRouterStack(layer.handle.stack);
119
138
  }
@@ -123,6 +142,48 @@ const patchRouterStack = (stack: PatchedLayer[]): void => {
123
142
  }
124
143
  };
125
144
 
145
+ /**
146
+ * Patches `express.Router().use` so nested mounts (e.g. `router.use("/gpt/histories", ...)`)
147
+ * record `__openApiMountPath` the same way `app.use` does. Without this, nested
148
+ * modelRouter OpenAPI paths are omitted from `/openapi.json`.
149
+ *
150
+ * Express 5's Router puts `use` a few prototypes up from the instance, so we walk
151
+ * the chain until we find the own `use` descriptor.
152
+ */
153
+ export const patchExpressRouterUse = (): void => {
154
+ if (isExpressRouterUsePatched) {
155
+ return;
156
+ }
157
+ isExpressRouterUsePatched = true;
158
+
159
+ let routerPrototype: object | null = Object.getPrototypeOf(express.Router());
160
+ while (routerPrototype && !Object.getOwnPropertyDescriptor(routerPrototype, "use")) {
161
+ routerPrototype = Object.getPrototypeOf(routerPrototype);
162
+ }
163
+ if (!routerPrototype) {
164
+ return;
165
+ }
166
+
167
+ const useDescriptor = Object.getOwnPropertyDescriptor(routerPrototype, "use");
168
+ if (!useDescriptor?.value) {
169
+ return;
170
+ }
171
+
172
+ const originalUse = useDescriptor.value as (
173
+ this: {stack?: PatchedLayer[]},
174
+ ...args: unknown[]
175
+ ) => unknown;
176
+ Object.defineProperty(routerPrototype, "use", {
177
+ ...useDescriptor,
178
+ value: function patchedRouterUse(this: {stack?: PatchedLayer[]}, ...args: unknown[]): unknown {
179
+ const stackBefore = this.stack?.length ?? 0;
180
+ const result = originalUse.apply(this, args);
181
+ annotateMountLayers(this.stack, stackBefore, args);
182
+ return result;
183
+ },
184
+ });
185
+ };
186
+
126
187
  /**
127
188
  * Wraps an Express app's `use` method to record the mount path on each
128
189
  * layer added to the router stack. This runs at setup time so that
@@ -131,6 +192,8 @@ const patchRouterStack = (stack: PatchedLayer[]): void => {
131
192
  * Must be called before any routes are registered.
132
193
  */
133
194
  export const patchAppUse = (app: Application): void => {
195
+ patchExpressRouterUse();
196
+
134
197
  const internal = app as unknown as AppWithRouter;
135
198
  const originalUse = app.use.bind(app);
136
199
  const patchedUse = (...args: unknown[]): unknown => {
@@ -142,16 +205,7 @@ export const patchAppUse = (app: Application): void => {
142
205
 
143
206
  // After use(), check if new layers were added and annotate them
144
207
  const routerAfter = internal._router ?? internal.router;
145
- if (routerAfter?.stack) {
146
- const stackAfter = routerAfter.stack.length;
147
- // The first arg is the mount path if it's a string
148
- const mountPath = typeof args[0] === "string" ? args[0] : undefined;
149
- if (mountPath && mountPath !== "/") {
150
- for (let i = stackBefore; i < stackAfter; i++) {
151
- routerAfter.stack[i][MOUNT_PATH_KEY] = mountPath.replace(/\/+$/, "");
152
- }
153
- }
154
- }
208
+ annotateMountLayers(routerAfter?.stack, stackBefore, args);
155
209
 
156
210
  return result;
157
211
  };
@@ -563,47 +563,6 @@ describe("openApiValidator", () => {
563
563
  expect(req.query.page).toBe(5);
564
564
  });
565
565
 
566
- it("runs only body validation when no query schema is provided", () => {
567
- configureOpenApiValidator({coerceTypes: true});
568
-
569
- const middleware = createValidator({
570
- body: {count: {type: "number"}, name: {required: true, type: "string"}},
571
- });
572
-
573
- const req = {
574
- body: {count: "3", name: "ok"},
575
- method: "POST",
576
- path: "/test",
577
- query: {unchecked: "kept"},
578
- } as unknown as Request;
579
- const res = {} as Response;
580
-
581
- const nextCalls: unknown[][] = [];
582
- middleware(req, res, ((...args: unknown[]) => {
583
- nextCalls.push(args);
584
- }) as NextFunction);
585
-
586
- expect(nextCalls).toEqual([[]]);
587
- expect(req.body.count).toBe(3);
588
- // Query params are untouched when no query schema is configured.
589
- expect(req.query.unchecked).toBe("kept");
590
- });
591
-
592
- it("throws body validation errors when only a body schema is provided", () => {
593
- configureOpenApiValidator({});
594
-
595
- const middleware = createValidator({
596
- body: {name: {required: true, type: "string"}},
597
- });
598
-
599
- const req = {body: {}, method: "POST", path: "/test", query: {}} as unknown as Request;
600
- const res = {} as Response;
601
-
602
- expect(() => middleware(req, res, (() => {}) as NextFunction)).toThrow(
603
- "Request validation failed"
604
- );
605
- });
606
-
607
566
  it("propagates body validation error via next", () => {
608
567
  let capturedErrors: ErrorObject[] = [];
609
568
  configureOpenApiValidator({