@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,45 +1,17 @@
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
- var __read = (this && this.__read) || function (o, n) {
14
- var m = typeof Symbol === "function" && o[Symbol.iterator];
15
- if (!m) return o;
16
- var i = m.call(o), r, ar = [], e;
17
- try {
18
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
19
- }
20
- catch (error) { e = { error: error }; }
21
- finally {
22
- try {
23
- if (r && !r.done && (m = i["return"])) m.call(i);
24
- }
25
- finally { if (e) throw e.error; }
26
- }
27
- return ar;
28
- };
29
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
30
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
31
4
  };
32
5
  Object.defineProperty(exports, "__esModule", { value: true });
33
6
  exports.twilioSignature = void 0;
34
- var node_crypto_1 = __importDefault(require("node:crypto"));
35
- var headerValue_1 = require("../headerValue");
36
- var timingSafeEqual_1 = require("../timingSafeEqual");
37
- var isUrlencoded = function (req) {
38
- var _a;
39
- var contentType = (_a = (0, headerValue_1.headerValue)(req, "content-type")) !== null && _a !== void 0 ? _a : "";
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const headerValue_1 = require("../headerValue");
9
+ const timingSafeEqual_1 = require("../timingSafeEqual");
10
+ const isUrlencoded = (req) => {
11
+ const contentType = (0, headerValue_1.headerValue)(req, "content-type") ?? "";
40
12
  return contentType.toLowerCase().includes("application/x-www-form-urlencoded");
41
13
  };
42
- var resolveUrl = function (req, url) {
14
+ const resolveUrl = (req, url) => {
43
15
  if (typeof url === "function") {
44
16
  return url(req);
45
17
  }
@@ -48,65 +20,43 @@ var resolveUrl = function (req, url) {
48
20
  }
49
21
  return undefined;
50
22
  };
51
- var formParams = function (body) {
52
- var e_1, _a;
23
+ const formParams = (body) => {
53
24
  if (!body || typeof body !== "object" || Array.isArray(body)) {
54
25
  return undefined;
55
26
  }
56
- var params = {};
57
- try {
58
- for (var _b = __values(Object.entries(body)), _c = _b.next(); !_c.done; _c = _b.next()) {
59
- var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
60
- if (typeof value !== "string") {
61
- return undefined;
62
- }
63
- params[key] = value;
27
+ const params = {};
28
+ for (const [key, value] of Object.entries(body)) {
29
+ if (typeof value !== "string") {
30
+ return undefined;
64
31
  }
65
- }
66
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
67
- finally {
68
- try {
69
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
70
- }
71
- finally { if (e_1) throw e_1.error; }
32
+ params[key] = value;
72
33
  }
73
34
  return params;
74
35
  };
75
36
  /**
76
37
  * Verifies Twilio `X-Twilio-Signature` (HMAC-SHA1 of callback URL + sorted POST fields).
77
38
  */
78
- var twilioSignature = function (options) {
79
- return function (req) {
80
- var e_2, _a;
39
+ const twilioSignature = (options) => {
40
+ return (req) => {
81
41
  if (!isUrlencoded(req) || !req.rawBody) {
82
42
  return false;
83
43
  }
84
- var provided = (0, headerValue_1.headerValue)(req, "X-Twilio-Signature");
85
- var callbackUrl = resolveUrl(req, options.url);
86
- var params = formParams(req.body);
44
+ const provided = (0, headerValue_1.headerValue)(req, "X-Twilio-Signature");
45
+ const callbackUrl = resolveUrl(req, options.url);
46
+ const params = formParams(req.body);
87
47
  if (!provided || !callbackUrl || !params) {
88
48
  return false;
89
49
  }
90
- var keys = Object.keys(params).sort();
91
- var data = callbackUrl;
92
- try {
93
- for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
94
- var key = keys_1_1.value;
95
- data += key + params[key];
96
- }
97
- }
98
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
99
- finally {
100
- try {
101
- if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
102
- }
103
- finally { if (e_2) throw e_2.error; }
50
+ const keys = Object.keys(params).sort();
51
+ let data = callbackUrl;
52
+ for (const key of keys) {
53
+ data += key + params[key];
104
54
  }
105
- var expected = node_crypto_1.default
55
+ const expected = node_crypto_1.default
106
56
  .createHmac("sha1", options.authToken)
107
57
  .update(data, "utf8")
108
58
  .digest("base64");
109
- return (0, timingSafeEqual_1.timingSafeEqualUtf8)({ expected: expected, provided: provided });
59
+ return (0, timingSafeEqual_1.timingSafeEqualUtf8)({ expected, provided });
110
60
  };
111
61
  };
112
62
  exports.twilioSignature = twilioSignature;
@@ -1,195 +1,96 @@
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
- var __values = (this && this.__values) || function(o) {
39
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
- if (m) return m.call(o);
41
- if (o && typeof o.length === "number") return {
42
- next: function () {
43
- if (o && i >= o.length) o = void 0;
44
- return { value: o && o[i++], done: !o };
45
- }
46
- };
47
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
- };
49
2
  Object.defineProperty(exports, "__esModule", { value: true });
50
3
  exports.WebhooksApp = void 0;
51
- var api_1 = require("../api");
52
- var errors_1 = require("../errors");
53
- var logger_1 = require("../logger");
54
- var memoryStore_1 = require("./idempotency/memoryStore");
55
- var mongoStore_1 = require("./idempotency/mongoStore");
56
- var WebhooksApp = /** @class */ (function () {
57
- function WebhooksApp(options) {
58
- if (options === void 0) { options = {}; }
59
- var _this = this;
60
- var _a, _b, _c;
61
- this.routes = [];
62
- this.claim = function (args) { return __awaiter(_this, void 0, void 0, function () {
63
- return __generator(this, function (_a) {
64
- return [2 /*return*/, this.store.claim(args)];
65
- });
66
- }); };
67
- this.release = function (args) { return __awaiter(_this, void 0, void 0, function () {
68
- return __generator(this, function (_a) {
69
- switch (_a.label) {
70
- case 0: return [4 /*yield*/, this.store.release(args)];
71
- case 1:
72
- _a.sent();
73
- return [2 /*return*/];
74
- }
75
- });
76
- }); };
77
- this.dispatch = function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
78
- var isValid, eventId, log, claimResult, error_1;
79
- var req = _b.req, res = _b.res, route = _b.route;
80
- return __generator(this, function (_c) {
81
- switch (_c.label) {
82
- case 0:
83
- if (!req.rawBody) {
84
- throw new errors_1.APIError({
85
- code: "webhook-body-missing",
86
- disableExternalErrorTracking: true,
87
- status: 400,
88
- title: "Missing webhook body",
89
- });
90
- }
91
- return [4 /*yield*/, route.verify(req)];
92
- case 1:
93
- isValid = _c.sent();
94
- if (!isValid) {
95
- throw new errors_1.APIError({
96
- code: "webhook-signature-invalid",
97
- disableExternalErrorTracking: true,
98
- status: 401,
99
- title: "Invalid webhook signature",
100
- });
101
- }
102
- eventId = route.eventId ? route.eventId(req) : "";
103
- log = (0, logger_1.createScopedLogger)({
104
- labels: { eventId: eventId || "none", source: route.source },
105
- prefix: "[Webhook]",
106
- });
107
- if (!!eventId) return [3 /*break*/, 2];
108
- log.warn("Empty eventId; skipping idempotency claim");
109
- return [3 /*break*/, 4];
110
- case 2: return [4 /*yield*/, this.claim({ eventId: eventId, source: route.source })];
111
- case 3:
112
- claimResult = _c.sent();
113
- if (claimResult === "duplicate") {
114
- log.info("Duplicate webhook event");
115
- res.status(200).json({ duplicate: true, received: true });
116
- return [2 /*return*/];
117
- }
118
- _c.label = 4;
119
- case 4:
120
- _c.trys.push([4, 6, , 9]);
121
- return [4 /*yield*/, route.handler({
122
- body: req.body,
123
- eventId: eventId,
124
- headers: req.headers,
125
- rawBody: req.rawBody,
126
- })];
127
- case 5:
128
- _c.sent();
129
- return [3 /*break*/, 9];
130
- case 6:
131
- error_1 = _c.sent();
132
- if (!eventId) return [3 /*break*/, 8];
133
- return [4 /*yield*/, this.release({ eventId: eventId, source: route.source })];
134
- case 7:
135
- _c.sent();
136
- _c.label = 8;
137
- case 8:
138
- if ((0, errors_1.isAPIError)(error_1)) {
139
- throw error_1;
140
- }
141
- throw new errors_1.APIError({
142
- cause: error_1,
143
- status: 500,
144
- title: "Webhook handler failed",
145
- });
146
- case 9:
147
- res.status(200).json({ received: true });
148
- return [2 /*return*/];
149
- }
150
- });
151
- }); };
152
- var storeKind = (_b = (_a = options.idempotency) === null || _a === void 0 ? void 0 : _a.store) !== null && _b !== void 0 ? _b : "memory";
4
+ const api_1 = require("../api");
5
+ const errors_1 = require("../errors");
6
+ const logger_1 = require("../logger");
7
+ const memoryStore_1 = require("./idempotency/memoryStore");
8
+ const mongoStore_1 = require("./idempotency/mongoStore");
9
+ class WebhooksApp {
10
+ routes = [];
11
+ store;
12
+ constructor(options = {}) {
13
+ const storeKind = options.idempotency?.store ?? "memory";
153
14
  if (storeKind === "mongo") {
154
- this.store = (0, mongoStore_1.createMongoIdempotencyStore)({ ttlDays: (_c = options.idempotency) === null || _c === void 0 ? void 0 : _c.ttlDays });
15
+ this.store = (0, mongoStore_1.createMongoIdempotencyStore)({ ttlDays: options.idempotency?.ttlDays });
155
16
  }
156
17
  else {
157
18
  this.store = (0, memoryStore_1.createMemoryIdempotencyStore)();
158
19
  }
159
20
  }
160
- WebhooksApp.prototype.route = function (options) {
21
+ route(options) {
161
22
  this.routes.push(options);
162
23
  return this;
24
+ }
25
+ claim = async (args) => {
26
+ return this.store.claim(args);
163
27
  };
164
- WebhooksApp.prototype.register = function (app) {
165
- var e_1, _a;
166
- var _this = this;
167
- var _loop_1 = function (route) {
168
- app.post(route.path, (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
169
- return __generator(this, function (_a) {
170
- switch (_a.label) {
171
- case 0: return [4 /*yield*/, this.dispatch({ req: req, res: res, route: route })];
172
- case 1:
173
- _a.sent();
174
- return [2 /*return*/];
175
- }
176
- });
177
- }); }));
178
- };
179
- try {
180
- for (var _b = __values(this.routes), _c = _b.next(); !_c.done; _c = _b.next()) {
181
- var route = _c.value;
182
- _loop_1(route);
28
+ release = async (args) => {
29
+ await this.store.release(args);
30
+ };
31
+ register(app) {
32
+ for (const route of this.routes) {
33
+ app.post(route.path, (0, api_1.asyncHandler)(async (req, res) => {
34
+ await this.dispatch({ req, res, route });
35
+ }));
36
+ }
37
+ }
38
+ dispatch = async ({ req, res, route, }) => {
39
+ if (!req.rawBody) {
40
+ throw new errors_1.APIError({
41
+ code: "webhook-body-missing",
42
+ disableExternalErrorTracking: true,
43
+ status: 400,
44
+ title: "Missing webhook body",
45
+ });
46
+ }
47
+ const isValid = await route.verify(req);
48
+ if (!isValid) {
49
+ throw new errors_1.APIError({
50
+ code: "webhook-signature-invalid",
51
+ disableExternalErrorTracking: true,
52
+ status: 401,
53
+ title: "Invalid webhook signature",
54
+ });
55
+ }
56
+ const eventId = route.eventId ? route.eventId(req) : "";
57
+ const log = (0, logger_1.createScopedLogger)({
58
+ labels: { eventId: eventId || "none", source: route.source },
59
+ prefix: "[Webhook]",
60
+ });
61
+ if (!eventId) {
62
+ log.warn("Empty eventId; skipping idempotency claim");
63
+ }
64
+ else {
65
+ const claimResult = await this.claim({ eventId, source: route.source });
66
+ if (claimResult === "duplicate") {
67
+ log.info("Duplicate webhook event");
68
+ res.status(200).json({ duplicate: true, received: true });
69
+ return;
183
70
  }
184
71
  }
185
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
186
- finally {
187
- try {
188
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
72
+ try {
73
+ await route.handler({
74
+ body: req.body,
75
+ eventId,
76
+ headers: req.headers,
77
+ rawBody: req.rawBody,
78
+ });
79
+ }
80
+ catch (error) {
81
+ if (eventId) {
82
+ await this.release({ eventId, source: route.source });
189
83
  }
190
- finally { if (e_1) throw e_1.error; }
84
+ if ((0, errors_1.isAPIError)(error)) {
85
+ throw error;
86
+ }
87
+ throw new errors_1.APIError({
88
+ cause: error,
89
+ status: 500,
90
+ title: "Webhook handler failed",
91
+ });
191
92
  }
93
+ res.status(200).json({ received: true });
192
94
  };
193
- return WebhooksApp;
194
- }());
95
+ }
195
96
  exports.WebhooksApp = WebhooksApp;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.z = void 0;
4
- var zod_to_openapi_1 = require("@asteasolutions/zod-to-openapi");
5
- var zod_1 = require("zod");
4
+ const zod_to_openapi_1 = require("@asteasolutions/zod-to-openapi");
5
+ const zod_1 = require("zod");
6
6
  Object.defineProperty(exports, "z", { enumerable: true, get: function () { return zod_1.z; } });
7
7
  (0, zod_to_openapi_1.extendZodWithOpenApi)(zod_1.z);
package/package.json CHANGED
@@ -4,14 +4,14 @@
4
4
  "terreno-migrate": "./src/migrations/cli.ts"
5
5
  },
6
6
  "bugs": {
7
- "url": "https://github.com/FlourishHealth/terreno/issues"
7
+ "url": "https://github.com/TerrenoLabs/terreno/issues"
8
8
  },
9
9
  "dependencies": {
10
10
  "@asteasolutions/zod-to-openapi": "^8.5.0",
11
11
  "@modelcontextprotocol/node": "^2.0.0",
12
12
  "@modelcontextprotocol/server": "^2.0.0",
13
13
  "@sentry/bun": "^10.39.0",
14
- "@terreno/test": "57.4.0",
14
+ "@terreno/test": "57.6.0",
15
15
  "@thream/socketio-jwt": "^3.1.4",
16
16
  "@types/qs": "^6.14.0",
17
17
  "ajv": "8.20.0",
@@ -48,7 +48,7 @@
48
48
  "devDependencies": {
49
49
  "@biomejs/biome": "^2.3.6",
50
50
  "@modelcontextprotocol/client": "^2.0.0",
51
- "@terreno/syncdb": "57.4.0",
51
+ "@terreno/syncdb": "57.6.0",
52
52
  "@types/bun": "^1.4.0",
53
53
  "@types/cors": "^2.8.17",
54
54
  "@types/express": "^5.0.6",
@@ -79,7 +79,7 @@
79
79
  "types": "./dist/tests.d.ts"
80
80
  }
81
81
  },
82
- "homepage": "https://github.com/FlourishHealth/terreno#readme",
82
+ "homepage": "https://github.com/TerrenoLabs/terreno#readme",
83
83
  "keywords": [
84
84
  "rest",
85
85
  "api",
@@ -108,7 +108,7 @@
108
108
  },
109
109
  "repository": {
110
110
  "type": "git",
111
- "url": "git+ssh://git@github.com/FlourishHealth/terreno.git"
111
+ "url": "git+ssh://git@github.com/TerrenoLabs/terreno.git"
112
112
  },
113
113
  "resolutions": {
114
114
  "json5": "2.2.3"
@@ -132,5 +132,5 @@
132
132
  "updateSnapshot": "bun test --update-snapshots"
133
133
  },
134
134
  "types": "dist/index.d.ts",
135
- "version": "57.4.0"
135
+ "version": "57.6.0"
136
136
  }
@@ -0,0 +1,165 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
+ import {mkdtempSync, readFileSync, rmSync, statSync, writeFileSync} from "node:fs";
3
+ import {tmpdir} from "node:os";
4
+ import {join} from "node:path";
5
+ import {assert} from "chai";
6
+ import express from "express";
7
+ import supertest from "supertest";
8
+ import {addTerrenoDevBrowserLogsRoute} from "../browserLogsRoute";
9
+
10
+ describe("Terreno dev browser logs route", () => {
11
+ let dir: string;
12
+ let prevBrowserLogs: string | undefined;
13
+ let prevEnv: NodeJS.ProcessEnv["NODE_ENV"] | undefined;
14
+ let prevCwd: string;
15
+
16
+ beforeEach(() => {
17
+ prevCwd = process.cwd();
18
+ prevEnv = process.env.NODE_ENV;
19
+ prevBrowserLogs = process.env.TERRENO_BROWSER_LOGS;
20
+ dir = mkdtempSync(join(tmpdir(), "terreno-browser-logs-"));
21
+ process.chdir(dir);
22
+ });
23
+
24
+ afterEach(() => {
25
+ process.chdir(prevCwd);
26
+ process.env.NODE_ENV = prevEnv ?? "test";
27
+ if (prevBrowserLogs === undefined) {
28
+ Reflect.deleteProperty(process.env, "TERRENO_BROWSER_LOGS");
29
+ } else {
30
+ process.env.TERRENO_BROWSER_LOGS = prevBrowserLogs;
31
+ }
32
+ rmSync(dir, {force: true, recursive: true});
33
+ });
34
+
35
+ it("accepts POST batches in development and appends JSONL", async () => {
36
+ process.env.NODE_ENV = "development";
37
+
38
+ const app = express();
39
+ addTerrenoDevBrowserLogsRoute(app);
40
+
41
+ const res = await supertest(app)
42
+ .post("/__terreno/browser-logs")
43
+ .send({entries: [{level: "error", message: "from client"}]});
44
+
45
+ expect(res.status).toBe(204);
46
+ const p = join(dir, ".terreno", "logs", "browser.log");
47
+ const txt = readFileSync(p, "utf-8");
48
+ expect(txt).toContain("from client");
49
+ });
50
+
51
+ it("rejects batches over the entry cap", async () => {
52
+ process.env.NODE_ENV = "development";
53
+
54
+ const app = express();
55
+ addTerrenoDevBrowserLogsRoute(app);
56
+
57
+ const res = await supertest(app)
58
+ .post("/__terreno/browser-logs")
59
+ .send({entries: Array.from({length: 101}, () => ({level: "error", message: "x"}))});
60
+
61
+ expect(res.status).toBe(413);
62
+ });
63
+
64
+ it("enforces the body cap after TerrenoApp's global JSON parser", async () => {
65
+ process.env.NODE_ENV = "development";
66
+
67
+ const app = express();
68
+ app.use(express.json({limit: "1mb"}));
69
+ addTerrenoDevBrowserLogsRoute(app);
70
+
71
+ const response = await supertest(app)
72
+ .post("/__terreno/browser-logs")
73
+ .send({entries: [{level: "error", message: "x".repeat(300 * 1024)}]});
74
+
75
+ assert.equal(response.status, 413);
76
+ assert.include(response.body.error, "256 kB");
77
+ });
78
+
79
+ it("rejects an empty request body", async () => {
80
+ process.env.NODE_ENV = "development";
81
+ const app = express();
82
+ addTerrenoDevBrowserLogsRoute(app);
83
+
84
+ const response = await supertest(app).post("/__terreno/browser-logs");
85
+ expect(response.status).toBe(400);
86
+ });
87
+
88
+ it("rejects unauthenticated remote clients and accepts authenticated ones", async () => {
89
+ process.env.NODE_ENV = "development";
90
+ const remoteAddressMiddleware: express.RequestHandler = (req, _res, next) => {
91
+ Object.defineProperty(req.socket, "remoteAddress", {
92
+ configurable: true,
93
+ value: "10.0.0.5",
94
+ });
95
+ next();
96
+ };
97
+ const remoteApp = express();
98
+ remoteApp.use(remoteAddressMiddleware);
99
+ addTerrenoDevBrowserLogsRoute(remoteApp);
100
+
101
+ const rejected = await supertest(remoteApp)
102
+ .post("/__terreno/browser-logs")
103
+ .send({entries: [{level: "error", message: "remote"}]});
104
+ assert.equal(rejected.status, 403);
105
+
106
+ const authenticatedApp = express();
107
+ authenticatedApp.use(remoteAddressMiddleware);
108
+ authenticatedApp.use((req, _res, next) => {
109
+ Object.assign(req, {user: {_id: "dev-user"}});
110
+ next();
111
+ });
112
+ addTerrenoDevBrowserLogsRoute(authenticatedApp);
113
+ const accepted = await supertest(authenticatedApp)
114
+ .post("/__terreno/browser-logs")
115
+ .send({entries: [{level: "error", message: "authenticated"}]});
116
+ assert.equal(accepted.status, 204);
117
+ });
118
+
119
+ it("restarts the dev log before it exceeds the size cap", async () => {
120
+ process.env.NODE_ENV = "development";
121
+ const logDir = join(dir, ".terreno", "logs");
122
+ const logPath = join(logDir, "browser.log");
123
+ const app = express();
124
+ addTerrenoDevBrowserLogsRoute(app);
125
+ await supertest(app)
126
+ .post("/__terreno/browser-logs")
127
+ .send({entries: [{level: "info", message: "create directory"}]});
128
+ writeFileSync(logPath, Buffer.alloc(5 * 1024 * 1024));
129
+
130
+ const response = await supertest(app)
131
+ .post("/__terreno/browser-logs")
132
+ .send({entries: [{level: "error", message: "after rollover"}]});
133
+
134
+ assert.equal(response.status, 204);
135
+ assert.isBelow(statSync(logPath).size, 1024);
136
+ assert.include(readFileSync(logPath, "utf8"), "after rollover");
137
+ });
138
+
139
+ it("is not mounted outside development unless explicitly enabled", async () => {
140
+ process.env.NODE_ENV = "test";
141
+
142
+ const disabledApp = express();
143
+ addTerrenoDevBrowserLogsRoute(disabledApp);
144
+ const disabledResponse = await supertest(disabledApp)
145
+ .post("/__terreno/browser-logs")
146
+ .send({entries: [{level: "error", message: "x"}]});
147
+ expect(disabledResponse.status).toBe(404);
148
+
149
+ process.env.TERRENO_BROWSER_LOGS = "true";
150
+ const enabledApp = express();
151
+ addTerrenoDevBrowserLogsRoute(enabledApp);
152
+ const enabledResponse = await supertest(enabledApp)
153
+ .post("/__terreno/browser-logs")
154
+ .send({entries: [{level: "error", message: "x"}]});
155
+ expect(enabledResponse.status).toBe(204);
156
+
157
+ process.env.NODE_ENV = "production";
158
+ const productionApp = express();
159
+ addTerrenoDevBrowserLogsRoute(productionApp);
160
+ const productionResponse = await supertest(productionApp)
161
+ .post("/__terreno/browser-logs")
162
+ .send({entries: [{level: "error", message: "x"}]});
163
+ expect(productionResponse.status).toBe(404);
164
+ });
165
+ });
@@ -15,8 +15,8 @@ import {resetAuditRecorderForTests} from "./record";
15
15
  const typedUserModel = UserModel as unknown as AuthUserModel;
16
16
 
17
17
  const deleteAuditEventModel = (): void => {
18
- if (mongoose.connection.models.AuditEvent) {
19
- mongoose.connection.deleteModel("AuditEvent");
18
+ if (mongoose.connection.models.TerrenoAuditEvent) {
19
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
20
20
  }
21
21
  };
22
22
 
@@ -49,7 +49,7 @@ describe("AuditApp", () => {
49
49
  it("does not register AuditEvent on the default connection when @terreno/api is imported", async () => {
50
50
  deleteAuditEventModel();
51
51
  await import("../index");
52
- assert.isUndefined(mongoose.connection.models.AuditEvent);
52
+ assert.isUndefined(mongoose.connection.models.TerrenoAuditEvent);
53
53
  });
54
54
 
55
55
  it("lets an admin list an empty audit log", async () => {
@@ -123,14 +123,14 @@ describe("AuditApp", () => {
123
123
  it("does not add a TTL index by default", () => {
124
124
  deleteAuditEventModel();
125
125
  createAuditEventModel(mongoose.connection);
126
- const indexes = mongoose.connection.models.AuditEvent.schema.indexes();
126
+ const indexes = mongoose.connection.models.TerrenoAuditEvent.schema.indexes();
127
127
  assert.isFalse(indexes.some(([, options]) => options && "expireAfterSeconds" in options));
128
128
  });
129
129
 
130
130
  it("adds a TTL index on created when retentionDays is greater than 0", () => {
131
131
  deleteAuditEventModel();
132
132
  createAuditEventModel(mongoose.connection, {retentionDays: 1});
133
- const indexes = mongoose.connection.models.AuditEvent.schema.indexes();
133
+ const indexes = mongoose.connection.models.TerrenoAuditEvent.schema.indexes();
134
134
  const createdAsc = indexes.filter(
135
135
  ([fields]) => (fields as {created?: number}).created === 1 && Object.keys(fields).length === 1
136
136
  );