@terreno/api 57.4.0 → 57.6.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 (208) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +598 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. package/tsconfig.typedoc.json +2 -0
@@ -1,109 +1,58 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
3
  exports.createRateLimitMiddleware = void 0;
40
- var luxon_1 = require("luxon");
41
- var errors_1 = require("../errors");
42
- var policies_1 = require("./policies");
43
- var types_1 = require("./types");
44
- var secondsUntil = function (resetAt, now) {
4
+ const luxon_1 = require("luxon");
5
+ const errors_1 = require("../errors");
6
+ const policies_1 = require("./policies");
7
+ const types_1 = require("./types");
8
+ const secondsUntil = (resetAt, now) => {
45
9
  return Math.max(1, Math.ceil((resetAt - now) / 1000));
46
10
  };
47
- var setRateLimitExceededHeaders = function (_a) {
48
- var max = _a.max, remaining = _a.remaining, resetAt = _a.resetAt, now = _a.now, windowMs = _a.windowMs, res = _a.res;
49
- var retryAfter = secondsUntil(resetAt, now);
50
- var windowSec = Math.max(1, Math.ceil(windowMs / 1000));
11
+ const setRateLimitExceededHeaders = ({ max, remaining, resetAt, now, windowMs, res, }) => {
12
+ const retryAfter = secondsUntil(resetAt, now);
13
+ const windowSec = Math.max(1, Math.ceil(windowMs / 1000));
51
14
  res.setHeader("Retry-After", String(retryAfter));
52
- res.setHeader("RateLimit", "limit=".concat(max, ", remaining=").concat(remaining, ", reset=").concat(retryAfter));
53
- res.setHeader("RateLimit-Policy", "".concat(max, ";w=").concat(windowSec));
15
+ res.setHeader("RateLimit", `limit=${max}, remaining=${remaining}, reset=${retryAfter}`);
16
+ res.setHeader("RateLimit-Policy", `${max};w=${windowSec}`);
54
17
  };
55
- var createRateLimitMiddleware = function (store, options) {
56
- var _a, _b, _c, _d, _e, _f, _g;
57
- if (options === void 0) { options = {}; }
58
- var windowMs = (_b = (_a = options.limits) === null || _a === void 0 ? void 0 : _a.windowMs) !== null && _b !== void 0 ? _b : types_1.DEFAULT_WINDOW_MS;
59
- var authMax = (_d = (_c = options.limits) === null || _c === void 0 ? void 0 : _c.authMax) !== null && _d !== void 0 ? _d : types_1.DEFAULT_AUTH_MAX;
60
- var apiMax = (_f = (_e = options.limits) === null || _e === void 0 ? void 0 : _e.apiMax) !== null && _f !== void 0 ? _f : types_1.DEFAULT_API_MAX;
61
- var betterAuthBasePath = options.betterAuthBasePath;
62
- var nowFn = (_g = options.now) !== null && _g !== void 0 ? _g : (function () { return luxon_1.DateTime.now().toMillis(); });
63
- return function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
64
- var policy, max, key, now, result, error_1;
65
- return __generator(this, function (_a) {
66
- switch (_a.label) {
67
- case 0:
68
- if ((0, policies_1.shouldSkipRateLimit)(req, options.skip)) {
69
- next();
70
- return [2 /*return*/];
71
- }
72
- policy = (0, policies_1.classifyRateLimitPolicy)(req, betterAuthBasePath);
73
- max = policy === "auth" ? authMax : apiMax;
74
- key = "".concat(policy, ":").concat((0, policies_1.rateLimitKey)(req, policy));
75
- now = nowFn();
76
- _a.label = 1;
77
- case 1:
78
- _a.trys.push([1, 3, , 4]);
79
- return [4 /*yield*/, store.consume({ key: key, max: max, now: now, windowMs: windowMs })];
80
- case 2:
81
- result = _a.sent();
82
- if (result.allowed) {
83
- next();
84
- return [2 /*return*/];
85
- }
86
- setRateLimitExceededHeaders({
87
- max: max,
88
- now: now,
89
- remaining: result.remaining,
90
- res: res,
91
- resetAt: result.resetAt,
92
- windowMs: windowMs,
93
- });
94
- next(new errors_1.APIError({
95
- code: "rate-limit-exceeded",
96
- status: 429,
97
- title: "Too many requests",
98
- }));
99
- return [3 /*break*/, 4];
100
- case 3:
101
- error_1 = _a.sent();
102
- next(error_1);
103
- return [3 /*break*/, 4];
104
- case 4: return [2 /*return*/];
18
+ const createRateLimitMiddleware = (store, options = {}) => {
19
+ const windowMs = options.limits?.windowMs ?? types_1.DEFAULT_WINDOW_MS;
20
+ const authMax = options.limits?.authMax ?? types_1.DEFAULT_AUTH_MAX;
21
+ const apiMax = options.limits?.apiMax ?? types_1.DEFAULT_API_MAX;
22
+ const betterAuthBasePath = options.betterAuthBasePath;
23
+ const nowFn = options.now ?? (() => luxon_1.DateTime.now().toMillis());
24
+ return async (req, res, next) => {
25
+ if ((0, policies_1.shouldSkipRateLimit)(req, options.skip)) {
26
+ next();
27
+ return;
28
+ }
29
+ const policy = (0, policies_1.classifyRateLimitPolicy)(req, betterAuthBasePath);
30
+ const max = policy === "auth" ? authMax : apiMax;
31
+ const key = `${policy}:${(0, policies_1.rateLimitKey)(req, policy)}`;
32
+ const now = nowFn();
33
+ try {
34
+ const result = await store.consume({ key, max, now, windowMs });
35
+ if (result.allowed) {
36
+ next();
37
+ return;
105
38
  }
106
- });
107
- }); };
39
+ setRateLimitExceededHeaders({
40
+ max,
41
+ now,
42
+ remaining: result.remaining,
43
+ res,
44
+ resetAt: result.resetAt,
45
+ windowMs,
46
+ });
47
+ next(new errors_1.APIError({
48
+ code: "rate-limit-exceeded",
49
+ status: 429,
50
+ title: "Too many requests",
51
+ }));
52
+ }
53
+ catch (error) {
54
+ next(error);
55
+ }
56
+ };
108
57
  };
109
58
  exports.createRateLimitMiddleware = createRateLimitMiddleware;
@@ -1,123 +1,65 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
39
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
4
  };
41
5
  Object.defineProperty(exports, "__esModule", { value: true });
42
6
  exports.createMongoRateLimitStore = exports.RATE_LIMIT_HITS_COLLECTION = void 0;
43
- var luxon_1 = require("luxon");
44
- var mongoose_1 = __importDefault(require("mongoose"));
45
- var errors_1 = require("../errors");
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const errors_1 = require("../errors");
46
10
  /** @internal */
47
11
  exports.RATE_LIMIT_HITS_COLLECTION = "rateLimitHits";
48
- var ensureIndexes = function (collection) { return __awaiter(void 0, void 0, void 0, function () {
49
- return __generator(this, function (_a) {
50
- switch (_a.label) {
51
- case 0: return [4 /*yield*/, collection.createIndex({ key: 1 }, { unique: true })];
52
- case 1:
53
- _a.sent();
54
- return [4 /*yield*/, collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })];
55
- case 2:
56
- _a.sent();
57
- return [2 /*return*/];
12
+ const ensureIndexes = async (collection) => {
13
+ await collection.createIndex({ key: 1 }, { unique: true });
14
+ await collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
15
+ };
16
+ const createMongoRateLimitStore = () => {
17
+ let indexed = false;
18
+ const consume = async ({ key, max, windowMs, now, }) => {
19
+ const db = mongoose_1.default.connection.db;
20
+ if (!db) {
21
+ throw new errors_1.APIError({
22
+ status: 500,
23
+ title: "Mongo rate limit store requires an open mongoose connection",
24
+ });
25
+ }
26
+ const collection = db.collection(exports.RATE_LIMIT_HITS_COLLECTION);
27
+ if (!indexed) {
28
+ await ensureIndexes(collection);
29
+ indexed = true;
58
30
  }
59
- });
60
- }); };
61
- var createMongoRateLimitStore = function () {
62
- var indexed = false;
63
- var consume = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
64
- var db, collection, nowDate, resetAtDate, updated, hits, expiresAt, resetAt;
65
- var _c;
66
- var key = _b.key, max = _b.max, windowMs = _b.windowMs, now = _b.now;
67
- return __generator(this, function (_d) {
68
- switch (_d.label) {
69
- case 0:
70
- db = mongoose_1.default.connection.db;
71
- if (!db) {
72
- throw new errors_1.APIError({
73
- status: 500,
74
- title: "Mongo rate limit store requires an open mongoose connection",
75
- });
76
- }
77
- collection = db.collection(exports.RATE_LIMIT_HITS_COLLECTION);
78
- if (!!indexed) return [3 /*break*/, 2];
79
- return [4 /*yield*/, ensureIndexes(collection)];
80
- case 1:
81
- _d.sent();
82
- indexed = true;
83
- _d.label = 2;
84
- case 2:
85
- nowDate = luxon_1.DateTime.fromMillis(now).toJSDate();
86
- resetAtDate = luxon_1.DateTime.fromMillis(now + windowMs).toJSDate();
87
- return [4 /*yield*/, collection.findOneAndUpdate({ key: key }, [
88
- {
89
- $set: {
90
- expiresAt: {
91
- $cond: [
92
- { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
93
- "$expiresAt",
94
- resetAtDate,
95
- ],
96
- },
97
- hits: {
98
- $cond: [
99
- { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
100
- { $add: [{ $ifNull: ["$hits", 0] }, 1] },
101
- 1,
102
- ],
103
- },
104
- key: key,
105
- },
106
- },
107
- ], { returnDocument: "after", upsert: true })];
108
- case 3:
109
- updated = _d.sent();
110
- hits = Number((_c = updated === null || updated === void 0 ? void 0 : updated.hits) !== null && _c !== void 0 ? _c : 1);
111
- expiresAt = updated === null || updated === void 0 ? void 0 : updated.expiresAt;
112
- resetAt = expiresAt != null ? luxon_1.DateTime.fromJSDate(expiresAt).toMillis() : now + windowMs;
113
- return [2 /*return*/, {
114
- allowed: hits <= max,
115
- remaining: Math.max(0, max - hits),
116
- resetAt: resetAt,
117
- }];
118
- }
119
- });
120
- }); };
121
- return { consume: consume };
31
+ const nowDate = luxon_1.DateTime.fromMillis(now).toJSDate();
32
+ const resetAtDate = luxon_1.DateTime.fromMillis(now + windowMs).toJSDate();
33
+ const updated = await collection.findOneAndUpdate({ key }, [
34
+ {
35
+ $set: {
36
+ expiresAt: {
37
+ $cond: [
38
+ { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
39
+ "$expiresAt",
40
+ resetAtDate,
41
+ ],
42
+ },
43
+ hits: {
44
+ $cond: [
45
+ { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
46
+ { $add: [{ $ifNull: ["$hits", 0] }, 1] },
47
+ 1,
48
+ ],
49
+ },
50
+ key,
51
+ },
52
+ },
53
+ ], { returnDocument: "after", upsert: true });
54
+ const hits = Number(updated?.hits ?? 1);
55
+ const expiresAt = updated?.expiresAt;
56
+ const resetAt = expiresAt != null ? luxon_1.DateTime.fromJSDate(expiresAt).toMillis() : now + windowMs;
57
+ return {
58
+ allowed: hits <= max,
59
+ remaining: Math.max(0, max - hits),
60
+ resetAt,
61
+ };
62
+ };
63
+ return { consume };
122
64
  };
123
65
  exports.createMongoRateLimitStore = createMongoRateLimitStore;
@@ -1,38 +1,27 @@
1
1
  "use strict";
2
- var __values = (this && this.__values) || function(o) {
3
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
- if (m) return m.call(o);
5
- if (o && typeof o.length === "number") return {
6
- next: function () {
7
- if (o && i >= o.length) o = void 0;
8
- return { value: o && o[i++], done: !o };
9
- }
10
- };
11
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.rateLimitKey = exports.classifyRateLimitPolicy = exports.shouldSkipRateLimit = exports.isJwtCredentialExchangePath = void 0;
15
- var DEFAULT_BETTER_AUTH_BASE_PATH = "/api/auth";
16
- var stripQueryAndFragment = function (url) {
17
- var hash = url.indexOf("#");
18
- var withoutHash = hash === -1 ? url : url.slice(0, hash);
19
- var q = withoutHash.indexOf("?");
4
+ const DEFAULT_BETTER_AUTH_BASE_PATH = "/api/auth";
5
+ const stripQueryAndFragment = (url) => {
6
+ const hash = url.indexOf("#");
7
+ const withoutHash = hash === -1 ? url : url.slice(0, hash);
8
+ const q = withoutHash.indexOf("?");
20
9
  return q === -1 ? withoutHash : withoutHash.slice(0, q);
21
10
  };
22
11
  /** Strip query, fragment, and a trailing slash so `/auth/login/` matches `/auth/login`. */
23
- var normalizeRequestPath = function (url) {
24
- var withoutQuery = stripQueryAndFragment(url);
25
- var withoutSlash = withoutQuery.length > 1 && withoutQuery.endsWith("/")
12
+ const normalizeRequestPath = (url) => {
13
+ const withoutQuery = stripQueryAndFragment(url);
14
+ const withoutSlash = withoutQuery.length > 1 && withoutQuery.endsWith("/")
26
15
  ? withoutQuery.slice(0, -1)
27
16
  : withoutQuery;
28
17
  return withoutSlash.toLowerCase();
29
18
  };
30
19
  /** Prefer Express `req.path` (routing) over the raw request-target. */
31
- var requestPath = function (req) {
32
- var raw = req.path || req.url || req.originalUrl || "";
20
+ const requestPath = (req) => {
21
+ const raw = req.path || req.url || req.originalUrl || "";
33
22
  return normalizeRequestPath(raw);
34
23
  };
35
- var JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
24
+ const JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
36
25
  "/auth/login",
37
26
  "/auth/signup",
38
27
  "/auth/refresh_token",
@@ -45,12 +34,12 @@ var JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
45
34
  * JWT login, signup, and refresh must not 401 on a stale access token.
46
35
  * `setupAuth` runs before those routes so the client can still exchange credentials.
47
36
  */
48
- var isJwtCredentialExchangePath = function (req) {
37
+ const isJwtCredentialExchangePath = (req) => {
49
38
  return JWT_CREDENTIAL_EXCHANGE_EXACT.has(requestPath(req));
50
39
  };
51
40
  exports.isJwtCredentialExchangePath = isJwtCredentialExchangePath;
52
- var shouldSkipRateLimit = function (req, extraSkip) {
53
- var path = requestPath(req);
41
+ const shouldSkipRateLimit = (req, extraSkip) => {
42
+ const path = requestPath(req);
54
43
  if (req.method === "GET" && (path === "/health" || path === "/healthz")) {
55
44
  return true;
56
45
  }
@@ -60,14 +49,14 @@ var shouldSkipRateLimit = function (req, extraSkip) {
60
49
  if (path === "/swagger" || path.startsWith("/swagger/")) {
61
50
  return true;
62
51
  }
63
- if (extraSkip === null || extraSkip === void 0 ? void 0 : extraSkip(req)) {
52
+ if (extraSkip?.(req)) {
64
53
  return true;
65
54
  }
66
55
  return false;
67
56
  };
68
57
  exports.shouldSkipRateLimit = shouldSkipRateLimit;
69
58
  // `requestPath` lowercases, so camelCase routes live here as lowercase.
70
- var AUTH_EXACT = new Set([
59
+ const AUTH_EXACT = new Set([
71
60
  "/auth/login",
72
61
  "/auth/signup",
73
62
  "/auth/refresh_token",
@@ -80,70 +69,47 @@ var AUTH_EXACT = new Set([
80
69
  "/auth/github/callback",
81
70
  "/auth/github/failure",
82
71
  ]);
83
- var AUTH_PREFIXES = ["/auth/github/"];
84
- var betterAuthAuthPrefixes = function (basePath) {
85
- var trimmed = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
86
- var base = trimmed.toLowerCase();
72
+ const AUTH_PREFIXES = ["/auth/github/"];
73
+ const betterAuthAuthPrefixes = (basePath) => {
74
+ const trimmed = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
75
+ const base = trimmed.toLowerCase();
87
76
  return [
88
- "".concat(base, "/sign-in"),
89
- "".concat(base, "/sign-up"),
90
- "".concat(base, "/forget-password"),
91
- "".concat(base, "/request-password-reset"),
92
- "".concat(base, "/reset-password"),
93
- "".concat(base, "/send-verification-email"),
94
- "".concat(base, "/verify-email"),
95
- "".concat(base, "/callback"),
77
+ `${base}/sign-in`,
78
+ `${base}/sign-up`,
79
+ `${base}/forget-password`,
80
+ `${base}/request-password-reset`,
81
+ `${base}/reset-password`,
82
+ `${base}/send-verification-email`,
83
+ `${base}/verify-email`,
84
+ `${base}/callback`,
96
85
  ];
97
86
  };
98
- var classifyRateLimitPolicy = function (req, betterAuthBasePath) {
99
- var e_1, _a, e_2, _b;
100
- if (betterAuthBasePath === void 0) { betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH; }
101
- var path = requestPath(req);
87
+ const classifyRateLimitPolicy = (req, betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH) => {
88
+ const path = requestPath(req);
102
89
  if (AUTH_EXACT.has(path)) {
103
90
  return "auth";
104
91
  }
105
- try {
106
- for (var AUTH_PREFIXES_1 = __values(AUTH_PREFIXES), AUTH_PREFIXES_1_1 = AUTH_PREFIXES_1.next(); !AUTH_PREFIXES_1_1.done; AUTH_PREFIXES_1_1 = AUTH_PREFIXES_1.next()) {
107
- var prefix = AUTH_PREFIXES_1_1.value;
108
- if (path.startsWith(prefix)) {
109
- return "auth";
110
- }
111
- }
112
- }
113
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
114
- finally {
115
- try {
116
- if (AUTH_PREFIXES_1_1 && !AUTH_PREFIXES_1_1.done && (_a = AUTH_PREFIXES_1.return)) _a.call(AUTH_PREFIXES_1);
117
- }
118
- finally { if (e_1) throw e_1.error; }
119
- }
120
- try {
121
- for (var _c = __values(betterAuthAuthPrefixes(betterAuthBasePath)), _d = _c.next(); !_d.done; _d = _c.next()) {
122
- var prefix = _d.value;
123
- if (path === prefix || path.startsWith("".concat(prefix, "/"))) {
124
- return "auth";
125
- }
92
+ for (const prefix of AUTH_PREFIXES) {
93
+ if (path.startsWith(prefix)) {
94
+ return "auth";
126
95
  }
127
96
  }
128
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
129
- finally {
130
- try {
131
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
97
+ for (const prefix of betterAuthAuthPrefixes(betterAuthBasePath)) {
98
+ if (path === prefix || path.startsWith(`${prefix}/`)) {
99
+ return "auth";
132
100
  }
133
- finally { if (e_2) throw e_2.error; }
134
101
  }
135
102
  return "api";
136
103
  };
137
104
  exports.classifyRateLimitPolicy = classifyRateLimitPolicy;
138
- var rateLimitKey = function (req, policy) {
139
- var _a, _b;
105
+ const rateLimitKey = (req, policy) => {
140
106
  if (policy !== "auth") {
141
- var user = req.user;
142
- var userId = (_a = user === null || user === void 0 ? void 0 : user.id) !== null && _a !== void 0 ? _a : ((user === null || user === void 0 ? void 0 : user._id) != null ? String(user._id) : undefined);
107
+ const user = req.user;
108
+ const userId = user?.id ?? (user?._id != null ? String(user._id) : undefined);
143
109
  if (userId) {
144
- return "user:".concat(userId);
110
+ return `user:${userId}`;
145
111
  }
146
112
  }
147
- return "ip:".concat(req.ip || ((_b = req.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) || "unknown");
113
+ return `ip:${req.ip || req.socket?.remoteAddress || "unknown"}`;
148
114
  };
149
115
  exports.rateLimitKey = rateLimitKey;