@terreno/api 0.31.0 → 56.0.0-beta.2

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 (232) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +121 -26
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +47 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +83 -27
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +54 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +899 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/dist/auth.d.ts CHANGED
@@ -24,6 +24,32 @@ export interface GenerateTokensOptions {
24
24
  }
25
25
  export declare const authenticateMiddleware: (anonymous?: boolean) => (req: express.Request, res: express.Response, next: express.NextFunction) => any;
26
26
  export declare const signupUser: (userModel: UserModel, email: string, password: string, body?: Record<string, unknown>) => Promise<any>;
27
+ /** A user document exposing passport-local-mongoose's `setPassword`. */
28
+ export interface HasSetPassword {
29
+ _id?: unknown;
30
+ id?: string;
31
+ setPassword: (password: string, callback?: (error?: unknown) => void) => Promise<unknown> | unknown;
32
+ }
33
+ /** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
34
+ export declare const MAX_PASSWORD_LENGTH = 256;
35
+ /** Optional audit context for {@link setPasswordForUser} — never includes the password itself. */
36
+ export interface SetPasswordAuditContext {
37
+ /** The admin performing the change, when set via an admin-only route. */
38
+ adminId?: unknown;
39
+ }
40
+ /**
41
+ * Sets a password on a passport-local-mongoose user document, returning a Promise regardless of
42
+ * whether the installed version of `setPassword` is callback- or promise-based. Newer versions
43
+ * return a promise while older ones only invoke the callback; this helper normalizes both and
44
+ * rejects after `timeoutMs` (default 15s) if neither settles. Call `user.save()` afterwards to
45
+ * persist the new hash/salt.
46
+ *
47
+ * Rejects synchronously (before touching `setPassword`) when `password` exceeds
48
+ * {@link MAX_PASSWORD_LENGTH} characters. When `audit.adminId` is provided (an admin-initiated
49
+ * password change), logs a `logger.info` audit line with the admin id, target user id, and
50
+ * timestamp — NEVER the password itself.
51
+ */
52
+ export declare const setPasswordForUser: (user: HasSetPassword, password: string, timeoutMs?: number, audit?: SetPasswordAuditContext) => Promise<void>;
27
53
  /**
28
54
  * Generates both an access token (JWT) and a refresh token for a given user.
29
55
  *
package/dist/auth.js CHANGED
@@ -86,7 +86,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
86
86
  return (mod && mod.__esModule) ? mod : { "default": mod };
87
87
  };
88
88
  Object.defineProperty(exports, "__esModule", { value: true });
89
- exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.signupUser = exports.authenticateMiddleware = void 0;
89
+ exports.addMeRoutes = exports.addAuthRoutes = exports.setupAuth = exports.generateTokens = exports.setPasswordForUser = exports.MAX_PASSWORD_LENGTH = exports.signupUser = exports.authenticateMiddleware = void 0;
90
90
  var node_crypto_1 = require("node:crypto");
91
91
  var express_1 = __importDefault(require("express"));
92
92
  var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
@@ -170,6 +170,103 @@ var signupUser = function (userModel, email, password, body) { return __awaiter(
170
170
  });
171
171
  }); };
172
172
  exports.signupUser = signupUser;
173
+ /** Upper bound on password length accepted by {@link setPasswordForUser} (D5). */
174
+ exports.MAX_PASSWORD_LENGTH = 256;
175
+ /**
176
+ * Sets a password on a passport-local-mongoose user document, returning a Promise regardless of
177
+ * whether the installed version of `setPassword` is callback- or promise-based. Newer versions
178
+ * return a promise while older ones only invoke the callback; this helper normalizes both and
179
+ * rejects after `timeoutMs` (default 15s) if neither settles. Call `user.save()` afterwards to
180
+ * persist the new hash/salt.
181
+ *
182
+ * Rejects synchronously (before touching `setPassword`) when `password` exceeds
183
+ * {@link MAX_PASSWORD_LENGTH} characters. When `audit.adminId` is provided (an admin-initiated
184
+ * password change), logs a `logger.info` audit line with the admin id, target user id, and
185
+ * timestamp — NEVER the password itself.
186
+ */
187
+ var setPasswordForUser = function (user_1, password_1) {
188
+ var args_1 = [];
189
+ for (var _i = 2; _i < arguments.length; _i++) {
190
+ args_1[_i - 2] = arguments[_i];
191
+ }
192
+ return __awaiter(void 0, __spreadArray([user_1, password_1], __read(args_1), false), void 0, function (user, password, timeoutMs, audit) {
193
+ var targetUserId;
194
+ var _a, _b;
195
+ if (timeoutMs === void 0) { timeoutMs = 15000; }
196
+ return __generator(this, function (_c) {
197
+ switch (_c.label) {
198
+ case 0:
199
+ if (password.length > exports.MAX_PASSWORD_LENGTH) {
200
+ throw new errors_1.APIError({
201
+ status: 400,
202
+ title: "Password must be at most ".concat(exports.MAX_PASSWORD_LENGTH, " characters"),
203
+ });
204
+ }
205
+ if ((audit === null || audit === void 0 ? void 0 : audit.adminId) !== undefined) {
206
+ targetUserId = (_b = (_a = user._id) !== null && _a !== void 0 ? _a : user.id) !== null && _b !== void 0 ? _b : "unknown";
207
+ logger_1.logger.info("[auth] Admin ".concat(String(audit.adminId), " set password for user ").concat(String(targetUserId), " ") +
208
+ "at ".concat(luxon_1.DateTime.now().toISO()));
209
+ }
210
+ return [4 /*yield*/, new Promise(function (resolve, reject) {
211
+ var isSettled = false;
212
+ var timeout = setTimeout(function () {
213
+ if (isSettled) {
214
+ return;
215
+ }
216
+ isSettled = true;
217
+ reject(new Error("Timed out while setting password"));
218
+ }, timeoutMs);
219
+ var resolveOnce = function () {
220
+ if (isSettled) {
221
+ return;
222
+ }
223
+ isSettled = true;
224
+ clearTimeout(timeout);
225
+ resolve();
226
+ };
227
+ var rejectOnce = function (error) {
228
+ if (isSettled) {
229
+ return;
230
+ }
231
+ isSettled = true;
232
+ clearTimeout(timeout);
233
+ reject(error);
234
+ };
235
+ try {
236
+ var maybePromise = user.setPassword(password, function (error) {
237
+ if (error) {
238
+ rejectOnce(error);
239
+ return;
240
+ }
241
+ resolveOnce();
242
+ });
243
+ if (maybePromise && typeof maybePromise.then === "function") {
244
+ maybePromise.then(resolveOnce).catch(rejectOnce);
245
+ }
246
+ }
247
+ catch (error) {
248
+ rejectOnce(error);
249
+ }
250
+ })];
251
+ case 1:
252
+ _c.sent();
253
+ return [2 /*return*/];
254
+ }
255
+ });
256
+ });
257
+ };
258
+ exports.setPasswordForUser = setPasswordForUser;
259
+ /**
260
+ * Returns the duration when `ms` can parse it, otherwise logs and returns undefined so the caller
261
+ * keeps its default. Signing a token with an unparseable duration throws instead.
262
+ */
263
+ var validateDuration = function (envName, value) {
264
+ if ((0, ms_1.default)(value) === undefined) {
265
+ logger_1.logger.error("".concat(envName, " is not a valid duration: \"").concat(value, "\". Using the default instead."));
266
+ return undefined;
267
+ }
268
+ return value;
269
+ };
173
270
  /**
174
271
  * Generates both an access token (JWT) and a refresh token for a given user.
175
272
  *
@@ -193,7 +290,7 @@ var generateTokens = function (user_1, authOptions_1) {
193
290
  args_1[_i - 2] = arguments[_i];
194
291
  }
195
292
  return __awaiter(void 0, __spreadArray([user_1, authOptions_1], __read(args_1), false), void 0, function (user, authOptions, options) {
196
- var tokenSecretOrKey, tokenUser, sessionId, payload, tokenOptions, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions;
293
+ var tokenSecretOrKey, tokenUser, sessionId, payload, tokenOptions, expiresIn, token, refreshTokenSecretOrKey, refreshToken, refreshTokenOptions, expiresIn;
197
294
  var _a;
198
295
  if (options === void 0) { options = {}; }
199
296
  return __generator(this, function (_b) {
@@ -218,15 +315,9 @@ var generateTokens = function (user_1, authOptions_1) {
218
315
  tokenOptions.expiresIn = authOptions.generateTokenExpiration(user);
219
316
  }
220
317
  else if (process.env.TOKEN_EXPIRES_IN) {
221
- try {
222
- // this call to ms is purely for validation of the env variable. If it is invalid,
223
- // we want to be able to log the error and use the default.
224
- (0, ms_1.default)(process.env.TOKEN_EXPIRES_IN);
225
- tokenOptions.expiresIn = process.env.TOKEN_EXPIRES_IN;
226
- }
227
- catch (error) {
228
- // This error will result in using the default value above of 15m.
229
- logger_1.logger.error(error);
318
+ expiresIn = validateDuration("TOKEN_EXPIRES_IN", process.env.TOKEN_EXPIRES_IN);
319
+ if (expiresIn) {
320
+ tokenOptions.expiresIn = expiresIn;
230
321
  }
231
322
  }
232
323
  if (process.env.TOKEN_ISSUER) {
@@ -242,15 +333,9 @@ var generateTokens = function (user_1, authOptions_1) {
242
333
  refreshTokenOptions.expiresIn = authOptions.generateRefreshTokenExpiration(user);
243
334
  }
244
335
  else if (process.env.REFRESH_TOKEN_EXPIRES_IN) {
245
- try {
246
- // this call to ms is purely for validation of the env variable. If it is invalid,
247
- // we want to be able to log the error and use the default.
248
- (0, ms_1.default)(process.env.REFRESH_TOKEN_EXPIRES_IN);
249
- refreshTokenOptions.expiresIn = process.env.REFRESH_TOKEN_EXPIRES_IN;
250
- }
251
- catch (error) {
252
- // This error will result in using the default value above of 30d.
253
- logger_1.logger.error(error);
336
+ expiresIn = validateDuration("REFRESH_TOKEN_EXPIRES_IN", process.env.REFRESH_TOKEN_EXPIRES_IN);
337
+ if (expiresIn) {
338
+ refreshTokenOptions.expiresIn = expiresIn;
254
339
  }
255
340
  }
256
341
  refreshToken = jsonwebtoken_1.default.sign(payload, refreshTokenSecretOrKey, refreshTokenOptions);
@@ -264,6 +349,9 @@ var generateTokens = function (user_1, authOptions_1) {
264
349
  };
265
350
  exports.generateTokens = generateTokens;
266
351
  var setupAuth = function (app, userModel) {
352
+ if (!userModel.createStrategy) {
353
+ throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
354
+ }
267
355
  passport_1.default.use(new passport_anonymous_1.Strategy());
268
356
  passport_1.default.use(userModel.createStrategy());
269
357
  passport_1.default.use("signup", new passport_local_1.Strategy({
@@ -289,9 +377,6 @@ var setupAuth = function (app, userModel) {
289
377
  }
290
378
  });
291
379
  }); }));
292
- if (!userModel.createStrategy) {
293
- throw new errors_1.APIError({ status: 500, title: "setupAuth userModel must have .createStrategy()" });
294
- }
295
380
  var customTokenExtractor = function (req) {
296
381
  var _a, _b, _c;
297
382
  var token = null;
@@ -308,9 +393,6 @@ var setupAuth = function (app, userModel) {
308
393
  logger_1.logger.debug("Setting up JWT Authentication");
309
394
  }
310
395
  var secretOrKey = process.env.TOKEN_SECRET;
311
- if (!secretOrKey) {
312
- throw new errors_1.APIError({ status: 500, title: "TOKEN_SECRET must be set in env." });
313
- }
314
396
  var jwtOpts = {
315
397
  issuer: process.env.TOKEN_ISSUER,
316
398
  jwtFromRequest: customTokenExtractor,
@@ -381,6 +463,19 @@ var setupAuth = function (app, userModel) {
381
463
  });
382
464
  }
383
465
  catch (error) {
466
+ // A bearer token that is not a JWT at all (e.g. a Better Auth opaque session
467
+ // token) is not ours to reject — fall through so a later auth layer (Better
468
+ // Auth session middleware) or the route's own permissions can handle it.
469
+ // Detect this by decoding the token's header/payload structure (D1) rather
470
+ // than counting dot-delimited segments: an opaque token can coincidentally
471
+ // contain exactly two dots, and a malformed-but-JWT-shaped string can fail
472
+ // this same check for the wrong reason — `jwt.decode` parses the actual
473
+ // base64url JSON structure of each segment, which dot-counting cannot.
474
+ // Genuine JWTs that fail verification (malformed/expired) still return 401 so the
475
+ // client's token-refresh flow is preserved.
476
+ if (jsonwebtoken_1.default.decode(token, { complete: true }) === null) {
477
+ return [2 /*return*/, next()];
478
+ }
384
479
  userText = ((_c = req.user) === null || _c === void 0 ? void 0 : _c._id) ? " for user ".concat(req.user._id, " ") : "";
385
480
  expiredAt = error && typeof error === "object" && "expiredAt" in error
386
481
  ? error.expiredAt
@@ -36,6 +36,11 @@ export interface BetterAuthConfig {
36
36
  * Include your app's deep link schemes (e.g., "terreno://", "exp://").
37
37
  */
38
38
  trustedOrigins?: string[];
39
+ /**
40
+ * Allow credential cookies when the frontend and API are hosted on different sites.
41
+ * Enables `SameSite=None; Secure` cookie attributes. Keep disabled for local HTTP.
42
+ */
43
+ crossDomainCookies?: boolean;
39
44
  /**
40
45
  * Base path for Better Auth routes.
41
46
  * @default "/api/auth"
@@ -60,10 +60,11 @@ exports.hasBetterAuthSession = exports.getBetterAuthSession = exports.setupBette
60
60
  var better_auth_1 = require("better-auth");
61
61
  var mongodb_1 = require("better-auth/adapters/mongodb");
62
62
  var node_1 = require("better-auth/node");
63
+ var plugins_1 = require("better-auth/plugins");
63
64
  var mongoose_1 = __importDefault(require("mongoose"));
64
65
  var errors_1 = require("./errors");
65
66
  var logger_1 = require("./logger");
66
- var plugins_1 = require("./plugins");
67
+ var plugins_2 = require("./plugins");
67
68
  var requestContext_1 = require("./requestContext");
68
69
  /**
69
70
  * Creates a Better Auth instance with MongoDB adapter.
@@ -106,12 +107,27 @@ var createBetterAuth = function (options) {
106
107
  };
107
108
  }
108
109
  var auth = (0, better_auth_1.betterAuth)({
110
+ advanced: config.crossDomainCookies
111
+ ? {
112
+ defaultCookieAttributes: {
113
+ httpOnly: true,
114
+ sameSite: "none",
115
+ secure: true,
116
+ },
117
+ }
118
+ : undefined,
109
119
  basePath: basePath,
110
120
  baseURL: baseURL,
111
121
  database: (0, mongodb_1.mongodbAdapter)(mongoClient.db()),
112
122
  emailAndPassword: {
113
123
  enabled: true,
114
124
  },
125
+ // The bearer plugin lets clients authenticate with `Authorization: Bearer <sessionToken>`
126
+ // instead of the signed session cookie. Required for cross-origin/native clients and for
127
+ // websocket handshakes (RealtimeApp's Better Auth socket validator forwards the handshake
128
+ // token as a bearer header) — without it, a raw session token cannot be validated and
129
+ // socket auth silently fails (the sync client shows perpetually "offline").
130
+ plugins: [(0, plugins_1.bearer)()],
115
131
  secret: secret,
116
132
  session: {
117
133
  cookieCache: {
@@ -122,6 +138,9 @@ var createBetterAuth = function (options) {
122
138
  socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
123
139
  trustedOrigins: (_b = config.trustedOrigins) !== null && _b !== void 0 ? _b : [],
124
140
  });
141
+ // Cast through unknown: enabling the bearer plugin narrows betterAuth()'s inferred
142
+ // return type to a plugin-specific tuple that no longer matches the plugin-agnostic
143
+ // BetterAuthInstance alias, though the runtime instance is a valid better-auth instance.
125
144
  return auth;
126
145
  };
127
146
  exports.createBetterAuth = createBetterAuth;
@@ -145,7 +164,7 @@ var createBetterAuthSessionMiddleware = function (auth, userModel) {
145
164
  betterAuthUser = session.user;
146
165
  reqWithSession = req;
147
166
  if (!userModel) return [3 /*break*/, 6];
148
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(userModel, {
167
+ return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, {
149
168
  betterAuthId: betterAuthUser.id,
150
169
  })];
151
170
  case 2:
@@ -196,7 +215,7 @@ var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider) { r
196
215
  switch (_a.label) {
197
216
  case 0:
198
217
  _a.trys.push([0, 8, , 9]);
199
- return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(userModel, {
218
+ return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, {
200
219
  betterAuthId: betterAuthUser.id,
201
220
  })];
202
221
  case 1:
@@ -211,7 +230,7 @@ var syncBetterAuthUser = function (userModel, betterAuthUser, oauthProvider) { r
211
230
  case 2:
212
231
  _a.sent();
213
232
  return [2 /*return*/, existingUser];
214
- case 3: return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(userModel, {
233
+ case 3: return [4 /*yield*/, (0, plugins_2.findOneOrNoneFor)(userModel, {
215
234
  email: betterAuthUser.email,
216
235
  })];
217
236
  case 4:
package/dist/docLoader.js CHANGED
@@ -48,21 +48,22 @@ var errors_1 = require("./errors");
48
48
  * Matches permission middleware behavior including soft-delete metadata.
49
49
  */
50
50
  var loadDocOr404 = function (model, id, populatePaths) { return __awaiter(void 0, void 0, void 0, function () {
51
- var builtQuery, populatedQuery, data, error_1, hiddenDoc, notFoundDetail, reason;
52
- return __generator(this, function (_a) {
53
- switch (_a.label) {
51
+ var builtQuery, populatedQuery, data, error_1, idSchemaType, hiddenId, hiddenDoc, notFoundDetail, reason;
52
+ var _a;
53
+ return __generator(this, function (_b) {
54
+ switch (_b.label) {
54
55
  case 0:
55
56
  builtQuery = model.findById(id);
56
57
  populatedQuery = (0, api_1.addPopulateToQuery)(builtQuery, populatePaths);
57
- _a.label = 1;
58
+ _b.label = 1;
58
59
  case 1:
59
- _a.trys.push([1, 3, , 4]);
60
+ _b.trys.push([1, 3, , 4]);
60
61
  return [4 /*yield*/, populatedQuery.exec()];
61
62
  case 2:
62
- data = (_a.sent());
63
+ data = (_b.sent());
63
64
  return [3 /*break*/, 4];
64
65
  case 3:
65
- error_1 = _a.sent();
66
+ error_1 = _b.sent();
66
67
  if ((0, errors_1.isAPIError)(error_1)) {
67
68
  throw error_1;
68
69
  }
@@ -76,11 +77,13 @@ var loadDocOr404 = function (model, id, populatePaths) { return __awaiter(void 0
76
77
  });
77
78
  case 4:
78
79
  if (!!data) return [3 /*break*/, 6];
80
+ idSchemaType = (_a = model.schema) === null || _a === void 0 ? void 0 : _a.path("_id");
81
+ hiddenId = (idSchemaType === null || idSchemaType === void 0 ? void 0 : idSchemaType.instance) === "String" ? id : new mongoose_1.default.Types.ObjectId(id);
79
82
  return [4 /*yield*/, model.collection.findOne({
80
- _id: new mongoose_1.default.Types.ObjectId(id),
83
+ _id: hiddenId,
81
84
  })];
82
85
  case 5:
83
- hiddenDoc = _a.sent();
86
+ hiddenDoc = _b.sent();
84
87
  notFoundDetail = "Document ".concat(id, " not found for model ").concat(model.modelName);
85
88
  if (!hiddenDoc) {
86
89
  throw new errors_1.NotFoundError({
package/dist/errors.d.ts CHANGED
@@ -159,6 +159,19 @@ export declare const apiUnauthorizedMiddleware: (err: Error, _req: Request, res:
159
159
  * Converts Mongoose validation/cast errors into client-friendly APIErrors.
160
160
  */
161
161
  export declare const mongooseErrorToAPIError: (err: Error) => APIError | null;
162
+ /**
163
+ * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
164
+ * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
165
+ * anything else is wrapped in the given framework error. `wrapper` may override any field,
166
+ * including `detail`, which defaults to the caught error's text.
167
+ */
168
+ export declare const passthroughOrWrap: (error: unknown, wrapper: APIErrorOptions) => APIError;
169
+ /**
170
+ * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
171
+ * errors are converted first so their per-field messages survive as `meta.fields` instead of being
172
+ * flattened into the wrapper's `detail`.
173
+ */
174
+ export declare const passthroughOrWrapWrite: (error: unknown, wrapper: APIErrorOptions) => APIError;
162
175
  export declare const apiErrorMiddleware: (err: Error, _req: Request, res: Response, next: NextFunction) => void;
163
176
  /**
164
177
  * Final Express error handler for unexpected errors. Always returns JSON so
package/dist/errors.js CHANGED
@@ -86,7 +86,7 @@ var __read = (this && this.__read) || function (o, n) {
86
86
  return ar;
87
87
  };
88
88
  Object.defineProperty(exports, "__esModule", { value: true });
89
- exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
89
+ exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
90
90
  // https://jsonapi.org/format/#errors
91
91
  var Sentry = __importStar(require("@sentry/bun"));
92
92
  var mongoose_1 = __importStar(require("mongoose"));
@@ -494,6 +494,34 @@ var mongooseErrorToAPIError = function (err) {
494
494
  return null;
495
495
  };
496
496
  exports.mongooseErrorToAPIError = mongooseErrorToAPIError;
497
+ /**
498
+ * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
499
+ * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
500
+ * anything else is wrapped in the given framework error. `wrapper` may override any field,
501
+ * including `detail`, which defaults to the caught error's text.
502
+ */
503
+ var passthroughOrWrap = function (error, wrapper) {
504
+ if ((0, exports.isAPIError)(error)) {
505
+ return error;
506
+ }
507
+ return new APIError(__assign({ cause: error, detail: (0, exports.errorDetail)(error), disableExternalErrorTracking: (0, exports.getDisableExternalErrorTracking)(error) }, wrapper));
508
+ };
509
+ exports.passthroughOrWrap = passthroughOrWrap;
510
+ /**
511
+ * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
512
+ * errors are converted first so their per-field messages survive as `meta.fields` instead of being
513
+ * flattened into the wrapper's `detail`.
514
+ */
515
+ var passthroughOrWrapWrite = function (error, wrapper) {
516
+ if (!(0, exports.isAPIError)(error) && error instanceof Error) {
517
+ var converted = (0, exports.mongooseErrorToAPIError)(error);
518
+ if (converted) {
519
+ return converted;
520
+ }
521
+ }
522
+ return (0, exports.passthroughOrWrap)(error, wrapper);
523
+ };
524
+ exports.passthroughOrWrapWrite = passthroughOrWrapWrite;
497
525
  // Logs the error (warn for 4xx client errors, error for 5xx server errors) and captures it with
498
526
  // Sentry unless external tracking is disabled. Fingerprints on the logical error type
499
527
  // (name + code/title + status) so unrelated errors constructed at the same framework lines don't
package/dist/index.d.ts CHANGED
@@ -28,15 +28,31 @@ export * from "./openApiValidator";
28
28
  export * from "./permissions";
29
29
  export * from "./plugins";
30
30
  export * from "./populate";
31
- export { startChangeStreamWatcher, stopChangeStreamWatcher, } from "./realtime/changeStreamWatcher";
31
+ export { type AuthorizedEmitEntry, emitPayloadToAuthorizedRoom, emitSyncDeltaForChange, startChangeStreamWatcher, stopChangeStreamWatcher, } from "./realtime/changeStreamWatcher";
32
32
  export { matchesQuery } from "./realtime/queryMatcher";
33
33
  export { addQuerySubscription, clearQueryStore, computeQueryId, getQuerySubscriptionsForCollection, removeAllSocketQueries, removeQuerySubscription, } from "./realtime/queryStore";
34
34
  export { installRealtimeSocketHandlers, MAX_DOCUMENT_SUBSCRIPTIONS, MAX_MODEL_SUBSCRIPTIONS, MAX_QUERY_SUBSCRIPTIONS, RealtimeApp, type RealtimeSocketLike, } from "./realtime/realtimeApp";
35
35
  export { clearRealtimeRegistry, findRegistryEntryByCollection, findRegistryEntryByRoutePath, getRealtimeRegistry, type RealtimeRegistryEntry, registerRealtime, } from "./realtime/registry";
36
+ export { DEFAULT_SESSION_REVALIDATION_INTERVAL_MS, loadFullUserForSocket, type RevalidatableSocket, type RevalidationOutcome, reresolveSyncRoomsForSocket, revalidateSocketSession, runSessionRevalidationSweep, type SessionRevalidationHandle, type SessionRevalidationOptions, startSessionRevalidationSweep, } from "./realtime/sessionRevalidation";
37
+ export { type AuthenticatableSocket, type BetterAuthSocketOptions, createBetterAuthValidator, createLegacyJwtValidator, createSocketAuthMiddleware, type SocketAuthValidator, } from "./realtime/socketAuth";
38
+ export { type DecodedRealtimeToken, getSocketUser, type SocketDataBag, type SocketWithDecodedToken, } from "./realtime/socketUser";
36
39
  export type { ChangeStreamConfig, DocumentSubscription, QuerySubscription, RealtimeAppOptions, RealtimeConfig, RealtimeEvent, } from "./realtime/types";
37
40
  export * from "./requestContext";
38
41
  export * from "./scriptRunner";
39
42
  export * from "./secretProviders";
43
+ export * from "./sync/executors";
44
+ export * from "./sync/models";
45
+ export * from "./sync/mutationHandler";
46
+ export * from "./sync/registry";
47
+ export * from "./sync/routes";
48
+ export * from "./sync/scripts/compactTombstones";
49
+ export * from "./sync/serialize";
50
+ export * from "./sync/socketHandlers";
51
+ export * from "./sync/streams";
52
+ export * from "./sync/syncApp";
53
+ export * from "./sync/syncBatch";
54
+ export * from "./sync/syncSeqPlugin";
55
+ export * from "./sync/types";
40
56
  export * from "./syncConsents";
41
57
  export * from "./terrenoApp";
42
58
  export * from "./terrenoPlugin";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.z = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = void 0;
17
+ exports.z = exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = void 0;
18
18
  __exportStar(require("./actions"), exports);
19
19
  __exportStar(require("./api"), exports);
20
20
  __exportStar(require("./auth"), exports);
@@ -46,6 +46,8 @@ __exportStar(require("./permissions"), exports);
46
46
  __exportStar(require("./plugins"), exports);
47
47
  __exportStar(require("./populate"), exports);
48
48
  var changeStreamWatcher_1 = require("./realtime/changeStreamWatcher");
49
+ Object.defineProperty(exports, "emitPayloadToAuthorizedRoom", { enumerable: true, get: function () { return changeStreamWatcher_1.emitPayloadToAuthorizedRoom; } });
50
+ Object.defineProperty(exports, "emitSyncDeltaForChange", { enumerable: true, get: function () { return changeStreamWatcher_1.emitSyncDeltaForChange; } });
49
51
  Object.defineProperty(exports, "startChangeStreamWatcher", { enumerable: true, get: function () { return changeStreamWatcher_1.startChangeStreamWatcher; } });
50
52
  Object.defineProperty(exports, "stopChangeStreamWatcher", { enumerable: true, get: function () { return changeStreamWatcher_1.stopChangeStreamWatcher; } });
51
53
  var queryMatcher_1 = require("./realtime/queryMatcher");
@@ -69,9 +71,35 @@ Object.defineProperty(exports, "findRegistryEntryByCollection", { enumerable: tr
69
71
  Object.defineProperty(exports, "findRegistryEntryByRoutePath", { enumerable: true, get: function () { return registry_1.findRegistryEntryByRoutePath; } });
70
72
  Object.defineProperty(exports, "getRealtimeRegistry", { enumerable: true, get: function () { return registry_1.getRealtimeRegistry; } });
71
73
  Object.defineProperty(exports, "registerRealtime", { enumerable: true, get: function () { return registry_1.registerRealtime; } });
74
+ var sessionRevalidation_1 = require("./realtime/sessionRevalidation");
75
+ Object.defineProperty(exports, "DEFAULT_SESSION_REVALIDATION_INTERVAL_MS", { enumerable: true, get: function () { return sessionRevalidation_1.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS; } });
76
+ Object.defineProperty(exports, "loadFullUserForSocket", { enumerable: true, get: function () { return sessionRevalidation_1.loadFullUserForSocket; } });
77
+ Object.defineProperty(exports, "reresolveSyncRoomsForSocket", { enumerable: true, get: function () { return sessionRevalidation_1.reresolveSyncRoomsForSocket; } });
78
+ Object.defineProperty(exports, "revalidateSocketSession", { enumerable: true, get: function () { return sessionRevalidation_1.revalidateSocketSession; } });
79
+ Object.defineProperty(exports, "runSessionRevalidationSweep", { enumerable: true, get: function () { return sessionRevalidation_1.runSessionRevalidationSweep; } });
80
+ Object.defineProperty(exports, "startSessionRevalidationSweep", { enumerable: true, get: function () { return sessionRevalidation_1.startSessionRevalidationSweep; } });
81
+ var socketAuth_1 = require("./realtime/socketAuth");
82
+ Object.defineProperty(exports, "createBetterAuthValidator", { enumerable: true, get: function () { return socketAuth_1.createBetterAuthValidator; } });
83
+ Object.defineProperty(exports, "createLegacyJwtValidator", { enumerable: true, get: function () { return socketAuth_1.createLegacyJwtValidator; } });
84
+ Object.defineProperty(exports, "createSocketAuthMiddleware", { enumerable: true, get: function () { return socketAuth_1.createSocketAuthMiddleware; } });
85
+ var socketUser_1 = require("./realtime/socketUser");
86
+ Object.defineProperty(exports, "getSocketUser", { enumerable: true, get: function () { return socketUser_1.getSocketUser; } });
72
87
  __exportStar(require("./requestContext"), exports);
73
88
  __exportStar(require("./scriptRunner"), exports);
74
89
  __exportStar(require("./secretProviders"), exports);
90
+ __exportStar(require("./sync/executors"), exports);
91
+ __exportStar(require("./sync/models"), exports);
92
+ __exportStar(require("./sync/mutationHandler"), exports);
93
+ __exportStar(require("./sync/registry"), exports);
94
+ __exportStar(require("./sync/routes"), exports);
95
+ __exportStar(require("./sync/scripts/compactTombstones"), exports);
96
+ __exportStar(require("./sync/serialize"), exports);
97
+ __exportStar(require("./sync/socketHandlers"), exports);
98
+ __exportStar(require("./sync/streams"), exports);
99
+ __exportStar(require("./sync/syncApp"), exports);
100
+ __exportStar(require("./sync/syncBatch"), exports);
101
+ __exportStar(require("./sync/syncSeqPlugin"), exports);
102
+ __exportStar(require("./sync/types"), exports);
75
103
  __exportStar(require("./syncConsents"), exports);
76
104
  __exportStar(require("./terrenoApp"), exports);
77
105
  __exportStar(require("./terrenoPlugin"), exports);
@@ -1,4 +1,11 @@
1
1
  import type { NextFunction, Request, Response } from "express";
2
+ /**
3
+ * Express middleware that rejects the request with a 403 unless the authenticated user is an admin
4
+ * (`req.user.admin === true`). Run it after {@link authenticateMiddleware} so `req.user` is
5
+ * populated, e.g. `[authenticateMiddleware(), requireAdminMiddleware]`. Use this for admin-only
6
+ * custom routes instead of hand-rolling an inline admin guard.
7
+ */
8
+ export declare const requireAdminMiddleware: (req: Request, _res: Response, next: NextFunction) => void;
2
9
  /**
3
10
  * Express middleware that captures the app version from the request header
4
11
  * and adds it as a tag to the current Sentry scope.
@@ -44,9 +44,24 @@ var __importStar = (this && this.__importStar) || (function () {
44
44
  };
45
45
  })();
46
46
  Object.defineProperty(exports, "__esModule", { value: true });
47
- exports.jsonResponseRequestIdMiddleware = exports.sentryAppVersionMiddleware = void 0;
47
+ exports.jsonResponseRequestIdMiddleware = exports.sentryAppVersionMiddleware = exports.requireAdminMiddleware = void 0;
48
48
  var Sentry = __importStar(require("@sentry/bun"));
49
+ var errors_1 = require("./errors");
49
50
  var requestContext_1 = require("./requestContext");
51
+ /**
52
+ * Express middleware that rejects the request with a 403 unless the authenticated user is an admin
53
+ * (`req.user.admin === true`). Run it after {@link authenticateMiddleware} so `req.user` is
54
+ * populated, e.g. `[authenticateMiddleware(), requireAdminMiddleware]`. Use this for admin-only
55
+ * custom routes instead of hand-rolling an inline admin guard.
56
+ */
57
+ var requireAdminMiddleware = function (req, _res, next) {
58
+ var user = req.user;
59
+ if (!(user === null || user === void 0 ? void 0 : user.admin)) {
60
+ throw new errors_1.APIError({ status: 403, title: "Admin access required" });
61
+ }
62
+ next();
63
+ };
64
+ exports.requireAdminMiddleware = requireAdminMiddleware;
50
65
  /**
51
66
  * Express middleware that captures the app version from the request header
52
67
  * and adds it as a tag to the current Sentry scope.
@@ -8,7 +8,16 @@
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 { type Application, type NextFunction, type Request, type Response } from "express";
12
+ /**
13
+ * Patches `express.Router().use` so nested mounts (e.g. `router.use("/gpt/histories", ...)`)
14
+ * record `__openApiMountPath` the same way `app.use` does. Without this, nested
15
+ * modelRouter OpenAPI paths are omitted from `/openapi.json`.
16
+ *
17
+ * Express 5's Router puts `use` a few prototypes up from the instance, so we walk
18
+ * the chain until we find the own `use` descriptor.
19
+ */
20
+ export declare const patchExpressRouterUse: () => void;
12
21
  /**
13
22
  * Wraps an Express app's `use` method to record the mount path on each
14
23
  * layer added to the router stack. This runs at setup time so that