@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
@@ -63,6 +63,7 @@ notificationSchema.plugin(findOneOrNone);
63
63
  notificationSchema.plugin(syncPlugin);
64
64
 
65
65
  export const Notification = mongoose.model<NotificationDocument, NotificationModel>(
66
- "Notification",
67
- notificationSchema
66
+ "TerrenoInboxNotification",
67
+ notificationSchema,
68
+ "notifications"
68
69
  );
@@ -59,4 +59,4 @@ notificationPreferenceSchema.index(
59
59
  export const NotificationPreference = mongoose.model<
60
60
  NotificationPreferenceDocument,
61
61
  NotificationPreferenceModel
62
- >("NotificationPreference", notificationPreferenceSchema);
62
+ >("TerrenoNotificationPreference", notificationPreferenceSchema, "notificationpreferences");
@@ -15,7 +15,10 @@ import {TerrenoApp} from "../terrenoApp";
15
15
  import {authAsUser, setupDb, UserModel} from "../tests";
16
16
  import {configureNotificationService, getNotificationService} from "./notificationService";
17
17
  import {NotificationsApp} from "./notificationsApp";
18
- import {notificationsBeforeSend} from "./notificationsBeforeSend";
18
+ import {
19
+ type NotificationsBeforeSendChannel,
20
+ notificationsBeforeSend,
21
+ } from "./notificationsBeforeSend";
19
22
 
20
23
  interface FakeComms {
21
24
  mailCalls: Array<{html?: string; subject: string; to: string}>;
@@ -339,6 +342,26 @@ describe("NotificationsApp", () => {
339
342
  assert.isUndefined(result);
340
343
  });
341
344
 
345
+ it("notificationsBeforeSend does not cancel when userId is missing", async () => {
346
+ const result = await notificationsBeforeSend({channel: "mail"});
347
+ assert.isUndefined(result);
348
+ });
349
+
350
+ it("notificationsBeforeSend does not cancel for channels without a preference field", async () => {
351
+ await NotificationPreference.create({
352
+ inapp: false,
353
+ mail: false,
354
+ ownerId: userId,
355
+ push: false,
356
+ sms: false,
357
+ });
358
+ const result = await notificationsBeforeSend({
359
+ channel: "inapp" as unknown as NotificationsBeforeSendChannel,
360
+ userId,
361
+ });
362
+ assert.isUndefined(result);
363
+ });
364
+
342
365
  it("fan-out calls mail when pref on and email present", async () => {
343
366
  const {comms, getComms} = buildFakeComms();
344
367
  configureNotificationService({getComms, userModel: UserModel});
@@ -3,7 +3,12 @@ import * as Sentry from "@sentry/bun";
3
3
  import axios from "axios";
4
4
 
5
5
  import {APIError, isAPIError} from "../errors";
6
- import {sendToSlack} from "./slackNotifier";
6
+ import {
7
+ formatSlackUserMention,
8
+ lookupSlackUserIdByEmail,
9
+ normalizeSlackUserId,
10
+ sendToSlack,
11
+ } from "./slackNotifier";
7
12
 
8
13
  describe("sendToSlack", () => {
9
14
  let mockAxiosPost: Mock<typeof axios.post>;
@@ -136,4 +141,184 @@ describe("sendToSlack", () => {
136
141
  await sendToSlack("err", {shouldThrow: false});
137
142
  expect(mockAxiosPost.mock.calls.length).toBe(1);
138
143
  });
144
+
145
+ it("prepends Slack member-id mentions so incoming webhooks notify those users", async () => {
146
+ await sendToSlack("needs review", {
147
+ mentionUserIds: ["U012ABCDEF", "<@W0ENTERPR1>"],
148
+ url: "https://direct.example/hook",
149
+ });
150
+ const [, payload] = mockAxiosPost.mock.calls[0];
151
+ expect(payload).toEqual({text: "<@U012ABCDEF> <@W0ENTERPR1> needs review"});
152
+ });
153
+
154
+ it("dedupes mention ids and skips names or emails that cannot mention anyone", async () => {
155
+ await sendToSlack("ping", {
156
+ mentionUserIds: ["U012ABCDEF", "u012abcdef", "jane@example.com", "Jane Doe", ""],
157
+ url: "https://direct.example/hook",
158
+ });
159
+ const [, payload] = mockAxiosPost.mock.calls[0];
160
+ expect(payload).toEqual({text: "<@U012ABCDEF> ping"});
161
+ });
162
+
163
+ it("applies env prefix after mention tokens", async () => {
164
+ await sendToSlack("deployed", {
165
+ env: "prd",
166
+ mentionUserIds: ["U012ABCDEF"],
167
+ url: "https://direct.example/hook",
168
+ });
169
+ const [, payload] = mockAxiosPost.mock.calls[0];
170
+ expect(payload).toEqual({text: "[PRD] <@U012ABCDEF> deployed"});
171
+ });
172
+
173
+ it("sends mention tokens alone when the message text is empty", async () => {
174
+ await sendToSlack("", {
175
+ mentionUserIds: ["U012ABCDEF"],
176
+ url: "https://direct.example/hook",
177
+ });
178
+ const [, payload] = mockAxiosPost.mock.calls[0];
179
+ expect(payload).toEqual({text: "<@U012ABCDEF>"});
180
+ });
181
+ });
182
+
183
+ describe("normalizeSlackUserId / formatSlackUserMention", () => {
184
+ it("accepts bare ids and already-wrapped mention tokens", () => {
185
+ expect(normalizeSlackUserId("U012ABCDEF")).toBe("U012ABCDEF");
186
+ expect(normalizeSlackUserId("<@u012abcdef>")).toBe("U012ABCDEF");
187
+ expect(normalizeSlackUserId("W0ENTERPR1")).toBe("W0ENTERPR1");
188
+ });
189
+
190
+ it("rejects display names and emails", () => {
191
+ expect(normalizeSlackUserId("Jane Doe")).toBeUndefined();
192
+ expect(normalizeSlackUserId("jane@example.com")).toBeUndefined();
193
+ expect(normalizeSlackUserId("@jane")).toBeUndefined();
194
+ });
195
+
196
+ it("formats a valid member id as a Slack mention token", () => {
197
+ expect(formatSlackUserMention("U012ABCDEF")).toBe("<@U012ABCDEF>");
198
+ });
199
+
200
+ it("throws APIError for values that are not Slack member ids", () => {
201
+ try {
202
+ formatSlackUserMention("jane@example.com");
203
+ throw new Error("Expected formatSlackUserMention to throw");
204
+ } catch (error) {
205
+ expect(isAPIError(error)).toBe(true);
206
+ expect((error as APIError).title).toBe("Invalid Slack user id");
207
+ }
208
+ });
209
+ });
210
+
211
+ describe("lookupSlackUserIdByEmail", () => {
212
+ let mockAxiosGet: Mock<typeof axios.get>;
213
+
214
+ beforeEach(() => {
215
+ mockAxiosGet = spyOn(axios, "get").mockResolvedValue({
216
+ data: {ok: true, user: {id: "U012ABCDEF"}},
217
+ status: 200,
218
+ });
219
+ Reflect.deleteProperty(process.env, "SLACK_BOT_TOKEN");
220
+ (Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
221
+ });
222
+
223
+ afterEach(() => {
224
+ mockAxiosGet.mockRestore();
225
+ });
226
+
227
+ it("returns the member id from users.lookupByEmail", async () => {
228
+ const id = await lookupSlackUserIdByEmail({
229
+ email: "jane@example.com",
230
+ token: "xoxb-test",
231
+ });
232
+ expect(id).toBe("U012ABCDEF");
233
+ expect(mockAxiosGet.mock.calls.length).toBe(1);
234
+ const [url, config] = mockAxiosGet.mock.calls[0];
235
+ expect(url).toBe("https://slack.com/api/users.lookupByEmail");
236
+ expect(config).toEqual({
237
+ headers: {Authorization: "Bearer xoxb-test"},
238
+ params: {email: "jane@example.com"},
239
+ });
240
+ });
241
+
242
+ it("returns undefined when no bot token is configured", async () => {
243
+ const id = await lookupSlackUserIdByEmail({email: "jane@example.com"});
244
+ expect(id).toBeUndefined();
245
+ expect(mockAxiosGet.mock.calls.length).toBe(0);
246
+ });
247
+
248
+ it("returns undefined when email is empty and shouldThrow is false", async () => {
249
+ const id = await lookupSlackUserIdByEmail({email: " ", token: "xoxb-test"});
250
+ expect(id).toBeUndefined();
251
+ expect(mockAxiosGet.mock.calls.length).toBe(0);
252
+ });
253
+
254
+ it("returns undefined when Slack reports the user was not found", async () => {
255
+ mockAxiosGet.mockResolvedValue({data: {error: "users_not_found", ok: false}, status: 200});
256
+ const id = await lookupSlackUserIdByEmail({
257
+ email: "missing@example.com",
258
+ token: "xoxb-test",
259
+ });
260
+ expect(id).toBeUndefined();
261
+ });
262
+
263
+ it("throws when shouldThrow is true and Slack returns an error", async () => {
264
+ mockAxiosGet.mockResolvedValue({data: {error: "missing_scope", ok: false}, status: 200});
265
+ try {
266
+ await lookupSlackUserIdByEmail({
267
+ email: "jane@example.com",
268
+ shouldThrow: true,
269
+ token: "xoxb-test",
270
+ });
271
+ throw new Error("Expected lookupSlackUserIdByEmail to throw");
272
+ } catch (error) {
273
+ expect(isAPIError(error)).toBe(true);
274
+ expect((error as APIError).title).toBe("Slack user lookup failed");
275
+ expect((error as APIError).detail).toBe("missing_scope");
276
+ }
277
+ });
278
+
279
+ it("throws when shouldThrow is true and email is empty", async () => {
280
+ try {
281
+ await lookupSlackUserIdByEmail({email: " ", shouldThrow: true, token: "xoxb-test"});
282
+ throw new Error("Expected lookupSlackUserIdByEmail to throw");
283
+ } catch (error) {
284
+ expect(isAPIError(error)).toBe(true);
285
+ expect((error as APIError).title).toBe("Email is required to look up a Slack user");
286
+ }
287
+ expect(mockAxiosGet.mock.calls.length).toBe(0);
288
+ });
289
+
290
+ it("throws when shouldThrow is true and no bot token is set", async () => {
291
+ try {
292
+ await lookupSlackUserIdByEmail({email: "jane@example.com", shouldThrow: true});
293
+ throw new Error("Expected lookupSlackUserIdByEmail to throw");
294
+ } catch (error) {
295
+ expect(isAPIError(error)).toBe(true);
296
+ expect((error as APIError).title).toContain("SLACK_BOT_TOKEN");
297
+ }
298
+ expect(mockAxiosGet.mock.calls.length).toBe(0);
299
+ });
300
+
301
+ it("throws when shouldThrow is true and the Slack HTTP call fails", async () => {
302
+ mockAxiosGet.mockRejectedValue(new Error("network down"));
303
+ try {
304
+ await lookupSlackUserIdByEmail({
305
+ email: "jane@example.com",
306
+ shouldThrow: true,
307
+ token: "xoxb-test",
308
+ });
309
+ throw new Error("Expected lookupSlackUserIdByEmail to throw");
310
+ } catch (error) {
311
+ expect(isAPIError(error)).toBe(true);
312
+ expect((error as APIError).title).toMatch(/Error looking up Slack user by email/i);
313
+ }
314
+ });
315
+
316
+ it("returns undefined when the Slack HTTP call fails and shouldThrow is false", async () => {
317
+ mockAxiosGet.mockRejectedValue(new Error("network down"));
318
+ const id = await lookupSlackUserIdByEmail({
319
+ email: "jane@example.com",
320
+ token: "xoxb-test",
321
+ });
322
+ expect(id).toBeUndefined();
323
+ });
139
324
  });
@@ -3,18 +3,177 @@ import axios from "axios";
3
3
 
4
4
  import {APIError, errorMessage} from "../errors";
5
5
  import {logger} from "../logger";
6
+
7
+ /** Slack member IDs are `U…` (users) or `W…` (Enterprise Grid). */
8
+ const SLACK_USER_ID_PATTERN = /^[UW][A-Z0-9]{8,}$/i;
9
+
10
+ const SLACK_LOOKUP_BY_EMAIL_URL = "https://slack.com/api/users.lookupByEmail";
11
+
12
+ export interface SendToSlackOptions {
13
+ slackChannel?: string;
14
+ shouldThrow?: boolean;
15
+ env?: string;
16
+ url?: string;
17
+ /**
18
+ * Slack member IDs to @-mention. Incoming webhooks only notify when the
19
+ * payload contains `<@U123…>` (or `<@W123…>`). Display names and emails in
20
+ * the message text do not mention anyone.
21
+ */
22
+ mentionUserIds?: string[];
23
+ }
24
+
25
+ export interface LookupSlackUserIdByEmailOptions {
26
+ email: string;
27
+ /** Slack bot token (`xoxb-…`) with `users:read.email`. Defaults to `SLACK_BOT_TOKEN`. */
28
+ token?: string;
29
+ shouldThrow?: boolean;
30
+ }
31
+
32
+ /**
33
+ * Normalize a Slack member ID. Accepts a bare id (`U012ABCDEF`) or a mention
34
+ * token (`<@U012ABCDEF>`). Returns undefined when the value is not a Slack
35
+ * member ID — names and emails cannot be used for mentions.
36
+ */
37
+ export const normalizeSlackUserId = (value: string): string | undefined => {
38
+ const trimmed = value.trim();
39
+ if (!trimmed) {
40
+ return undefined;
41
+ }
42
+ const unwrapped =
43
+ trimmed.startsWith("<@") && trimmed.endsWith(">") ? trimmed.slice(2, -1) : trimmed;
44
+ if (!SLACK_USER_ID_PATTERN.test(unwrapped)) {
45
+ return undefined;
46
+ }
47
+ return unwrapped.toUpperCase();
48
+ };
49
+
50
+ /** Format a Slack member ID as an incoming-webhook mention token. */
51
+ export const formatSlackUserMention = (slackUserId: string): string => {
52
+ const id = normalizeSlackUserId(slackUserId);
53
+ if (!id) {
54
+ throw new APIError({
55
+ detail: slackUserId,
56
+ status: 400,
57
+ title: "Invalid Slack user id",
58
+ });
59
+ }
60
+ return `<@${id}>`;
61
+ };
62
+
63
+ const uniqueMentionTokens = (mentionUserIds: string[] | undefined): string[] => {
64
+ if (!mentionUserIds?.length) {
65
+ return [];
66
+ }
67
+ const seen = new Set<string>();
68
+ const tokens: string[] = [];
69
+ for (const rawId of mentionUserIds) {
70
+ const id = normalizeSlackUserId(rawId);
71
+ if (!id) {
72
+ logger.warn("Skipping Slack mention; value is not a Slack member id", {value: rawId});
73
+ continue;
74
+ }
75
+ if (seen.has(id)) {
76
+ continue;
77
+ }
78
+ seen.add(id);
79
+ tokens.push(`<@${id}>`);
80
+ }
81
+ return tokens;
82
+ };
83
+
84
+ const applyMentions = (text: string, mentionUserIds: string[] | undefined): string => {
85
+ const tokens = uniqueMentionTokens(mentionUserIds);
86
+ if (tokens.length === 0) {
87
+ return text;
88
+ }
89
+ if (!text) {
90
+ return tokens.join(" ");
91
+ }
92
+ return `${tokens.join(" ")} ${text}`;
93
+ };
94
+
95
+ /**
96
+ * Resolve a workspace member's Slack user id from their email.
97
+ *
98
+ * Incoming webhooks cannot look users up. This calls `users.lookupByEmail` and
99
+ * needs a bot token with the `users:read.email` scope. Store the returned id on
100
+ * the staff/user record and pass it to `sendToSlack({mentionUserIds})`.
101
+ */
102
+ export const lookupSlackUserIdByEmail = async ({
103
+ email,
104
+ token,
105
+ shouldThrow = false,
106
+ }: LookupSlackUserIdByEmailOptions): Promise<string | undefined> => {
107
+ const trimmedEmail = email.trim();
108
+ if (!trimmedEmail) {
109
+ if (shouldThrow) {
110
+ throw new APIError({status: 400, title: "Email is required to look up a Slack user"});
111
+ }
112
+ logger.debug("lookupSlackUserIdByEmail skipped: empty email");
113
+ return undefined;
114
+ }
115
+
116
+ const botToken = token ?? process.env.SLACK_BOT_TOKEN;
117
+ if (!botToken) {
118
+ if (shouldThrow) {
119
+ throw new APIError({
120
+ status: 500,
121
+ title: "SLACK_BOT_TOKEN is not set; cannot look up Slack user ids",
122
+ });
123
+ }
124
+ logger.debug("lookupSlackUserIdByEmail skipped: no Slack bot token");
125
+ return undefined;
126
+ }
127
+
128
+ try {
129
+ const response = await axios.get<{ok: boolean; error?: string; user?: {id?: string}}>(
130
+ SLACK_LOOKUP_BY_EMAIL_URL,
131
+ {
132
+ headers: {Authorization: `Bearer ${botToken}`},
133
+ params: {email: trimmedEmail},
134
+ }
135
+ );
136
+ const payload = response.data;
137
+ if (!payload?.ok || !payload.user?.id) {
138
+ const slackError = payload?.error ?? "unknown_error";
139
+ logger.warn("Slack users.lookupByEmail did not return a user id", {
140
+ email: trimmedEmail,
141
+ slackError,
142
+ });
143
+ if (shouldThrow) {
144
+ throw new APIError({
145
+ detail: slackError,
146
+ status: 502,
147
+ title: "Slack user lookup failed",
148
+ });
149
+ }
150
+ return undefined;
151
+ }
152
+ return normalizeSlackUserId(payload.user.id);
153
+ } catch (error: unknown) {
154
+ if (error instanceof APIError) {
155
+ throw error;
156
+ }
157
+ const message = errorMessage(error);
158
+ logger.error(`Error looking up Slack user by email: ${message}`);
159
+ Sentry.captureException(error);
160
+ if (shouldThrow) {
161
+ throw new APIError({
162
+ status: 500,
163
+ title: `Error looking up Slack user by email: ${message}`,
164
+ });
165
+ }
166
+ return undefined;
167
+ }
168
+ };
169
+
6
170
  // Convenience method to send data to a Slack webhook.
7
171
  // If `url` is provided, it will be used directly instead of looking up from environment.
8
172
  // DEPRECATED: Looking up webhook URLs from the SLACK_WEBHOOKS environment variable by channel name
9
173
  // is deprecated and will be removed in a future version. Please pass the `url` parameter directly.
10
174
  export const sendToSlack = async (
11
175
  text: string,
12
- {
13
- slackChannel,
14
- shouldThrow = false,
15
- env,
16
- url,
17
- }: {slackChannel?: string; shouldThrow?: boolean; env?: string; url?: string} = {}
176
+ {slackChannel, shouldThrow = false, env, url, mentionUserIds}: SendToSlackOptions = {}
18
177
  ): Promise<void> => {
19
178
  let slackWebhookUrl = url;
20
179
 
@@ -46,9 +205,9 @@ export const sendToSlack = async (
46
205
  }
47
206
  }
48
207
 
49
- let formattedText = text;
208
+ let formattedText = applyMentions(text, mentionUserIds);
50
209
  if (env) {
51
- formattedText = `[${env.toUpperCase()}] ${text}`;
210
+ formattedText = `[${env.toUpperCase()}] ${formattedText}`;
52
211
  }
53
212
 
54
213
  try {
@@ -61,7 +61,7 @@ export const orgScopedPlugin = (schema: Schema): void => {
61
61
  organizationId: {
62
62
  description: "Organization this document belongs to",
63
63
  index: true,
64
- ref: "Organization",
64
+ ref: "TerrenoOrganization",
65
65
  required: true,
66
66
  type: mongoose.Schema.Types.ObjectId,
67
67
  },
@@ -121,7 +121,7 @@ const membershipSchema = new mongoose.Schema<MembershipDocument, MembershipModel
121
121
  organizationId: {
122
122
  description: "Organization this membership belongs to",
123
123
  index: true,
124
- ref: "Organization",
124
+ ref: "TerrenoOrganization",
125
125
  required: true,
126
126
  type: mongoose.Schema.Types.ObjectId,
127
127
  },
@@ -196,22 +196,27 @@ membershipSchema.statics = {
196
196
  };
197
197
 
198
198
  export const getOrganizationModel = (): OrganizationModel => {
199
- const existing = mongoose.models.Organization as OrganizationModel | undefined;
199
+ const existing = mongoose.models.TerrenoOrganization as OrganizationModel | undefined;
200
200
  if (existing) {
201
201
  return existing;
202
202
  }
203
203
  return mongoose.model<OrganizationDocument, OrganizationModel>(
204
- "Organization",
205
- organizationSchema
204
+ "TerrenoOrganization",
205
+ organizationSchema,
206
+ "organizations"
206
207
  );
207
208
  };
208
209
 
209
210
  export const getMembershipModel = (): MembershipModel => {
210
- const existing = mongoose.models.Membership as MembershipModel | undefined;
211
+ const existing = mongoose.models.TerrenoMembership as MembershipModel | undefined;
211
212
  if (existing) {
212
213
  return existing;
213
214
  }
214
- return mongoose.model<MembershipDocument, MembershipModel>("Membership", membershipSchema);
215
+ return mongoose.model<MembershipDocument, MembershipModel>(
216
+ "TerrenoMembership",
217
+ membershipSchema,
218
+ "memberships"
219
+ );
215
220
  };
216
221
 
217
222
  const createLazyModel = <T extends mongoose.Model<unknown>>(getModel: () => T): T => {
@@ -172,6 +172,11 @@ describe("isDeleted", () => {
172
172
  stuff = await StuffModel.findOne({deleted: true});
173
173
  expect(stuff?.name).toBe("Things");
174
174
  });
175
+
176
+ it('filters out deleted documents from "countDocuments" unless deleted is explicit', async () => {
177
+ expect(await StuffModel.countDocuments({})).toBe(1);
178
+ expect(await StuffModel.countDocuments({deleted: true})).toBe(1);
179
+ });
175
180
  });
176
181
 
177
182
  describe("findOneOrNone", () => {
package/src/plugins.ts CHANGED
@@ -93,6 +93,9 @@ export const isDeletedPlugin = (schema: Schema<any, any, any, any>, defaultValue
93
93
  schema.pre("findOne", function () {
94
94
  applyDeleteFilter(this);
95
95
  });
96
+ schema.pre("countDocuments", function () {
97
+ applyDeleteFilter(this);
98
+ });
96
99
  };
97
100
 
98
101
  export const isDisabledPlugin = (
@@ -417,7 +417,7 @@ export class RealtimeApp implements TerrenoPlugin {
417
417
  createSocketAuthMiddleware({
418
418
  betterAuth: this.config.betterAuth,
419
419
  issuer: resolveTokenIssuer,
420
- ...(tokenSecret ? {tokenSecret} : {}),
420
+ tokenSecret,
421
421
  })
422
422
  );
423
423
 
@@ -445,7 +445,7 @@ describe("syncdb end-to-end integration", () => {
445
445
  expect(entity?.seq).toBe(baseSeq + 1);
446
446
  expect(entity?.pendingMutationId).toBeUndefined();
447
447
  await waitFor(() => a.client.getSyncStatus().conflictCount === 0, {
448
- label: "conflict cleared after persistence flush",
448
+ label: "useServer conflict resolution persisted",
449
449
  });
450
450
  // The server kept its own write.
451
451
  const settled = await IntTodoModel.findById(conflictDocId);
@@ -488,7 +488,7 @@ describe("syncdb end-to-end integration", () => {
488
488
  // a replay immediately, so the retry drains without waiting for another trigger.
489
489
  a.client.resolveConflict({mutationId, strategy: "keepMine"});
490
490
  await waitFor(() => a.client.getSyncStatus().conflictCount === 0, {
491
- label: "conflict cleared after persistence flush",
491
+ label: "keepMine conflict resolution persisted",
492
492
  });
493
493
  expect(a.client.outbox.getMutation({mutationId})).toBeUndefined();
494
494
 
package/src/terrenoApp.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  type BetterAuthInstance,
14
14
  createBetterAuthSessionMiddleware,
15
15
  } from "./betterAuthSetup";
16
+ import {addTerrenoDevBrowserLogsRoute} from "./browserLogsRoute";
16
17
  import {
17
18
  ConfigurationApp,
18
19
  type ConfigurationAppOptions,
@@ -425,6 +426,8 @@ export class TerrenoApp {
425
426
  app.use(createRateLimitMiddleware(store, rateLimit));
426
427
  }
427
428
 
429
+ addTerrenoDevBrowserLogsRoute(app);
430
+
428
431
  if (!options.authOptions) {
429
432
  options.authOptions = {};
430
433
  }
package/src/types.d.ts CHANGED
@@ -6,6 +6,7 @@ declare namespace NodeJS {
6
6
  SENTRY_TRACES_SAMPLE_RATE: string;
7
7
  SENTRY_PROFILES_SAMPLE_RATE: string;
8
8
  SLACK_WEBHOOKS?: string;
9
+ SLACK_BOT_TOKEN?: string;
9
10
  GOOGLE_CHAT_WEBHOOKS?: string;
10
11
  SESSION_SECRET: string;
11
12
  TOKEN_ISSUER: string;
@@ -58,10 +58,11 @@ webhookReceiptSchema.plugin(findExactlyOne);
58
58
 
59
59
  export const getWebhookReceiptModel = (): WebhookReceiptModel => {
60
60
  return (
61
- (mongoose.models.WebhookReceipt as WebhookReceiptModel | undefined) ??
61
+ (mongoose.models.TerrenoWebhookReceipt as WebhookReceiptModel | undefined) ??
62
62
  mongoose.model<WebhookReceiptDocument, WebhookReceiptModel>(
63
- "WebhookReceipt",
64
- webhookReceiptSchema
63
+ "TerrenoWebhookReceipt",
64
+ webhookReceiptSchema,
65
+ WEBHOOK_RECEIPTS_COLLECTION
65
66
  )
66
67
  );
67
68
  };
package/tsconfig.json CHANGED
@@ -1,60 +1,19 @@
1
1
  {
2
2
  "compilerOptions": {
3
- // "lib": [], /* Specify library files to be included in the compilation. */
4
- "allowJs": true /* Allow javascript files to be compiled. */,
5
- "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
6
- "downlevelIteration": true,
7
- "declaration": true /* Generates corresponding '.d.ts' file. */,
8
- "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
9
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
10
- /* Source Map Options */
11
- // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
12
- // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
13
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
14
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
15
- /* Experimental Options */
16
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
17
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
18
- "forceConsistentCasingInFileNames": true,
19
- "ignoreDeprecations": "6.0",
20
- // "checkJs": true, /* Report errors in .js files. */
21
- "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
22
- "lib": ["es2017", "dom", "es2017.object", "es2022.error"],
23
- "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
24
-
25
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
26
- /* Module Resolution Options */
27
- "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
28
- "rootDir": "./src",
29
- // "removeComments": true, /* Do not emit comments to output. */
30
- "noEmit": false /* Do not emit outputs. */,
31
- "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,
3
+ "allowJs": true,
4
+ "declaration": true,
5
+ "isolatedModules": true,
6
+ "lib": ["es2023"],
7
+ "module": "nodenext",
8
+ "noImplicitAny": false,
32
9
  "noImplicitReturns": true,
33
- "noImplicitThis": true,
34
- // "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
35
- "noUnusedLocals": false,
36
- "noUnusedParameters": false,
37
- // "sourceMap": true, /* Generates corresponding '.map' file. */
38
- // "outFile": "./", /* Concatenate and emit output to single file. */
39
- "outDir": "./dist" /* Redirect output structure to the directory. */,
40
- "preserveConstEnums": true,
41
- "removeComments": false,
42
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44
- // "typeRoots": [], /* List of folders to include type definitions from. */
45
- "types": ["bun", "node"] /* Type declaration files to be included in compilation. */,
10
+ "outDir": "./dist",
11
+ "rootDir": "./src",
46
12
  "skipLibCheck": true,
47
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
48
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
49
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
50
- /* Strict Type-Checking Options */
51
- "strict": true /* Enable all strict type-checking options. */,
52
- "strictFunctionTypes": true /* Enable strict checking of function types. */,
53
- "strictNullChecks": true /* Enable strict null checks. */,
54
- // "paths": {"*": ["types/*"]},
55
- /* Basic Options */
56
- "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
13
+ "strict": true,
14
+ "target": "es2023",
15
+ "types": ["bun", "node"]
57
16
  },
58
- "exclude": ["node_modules", "**/*.test.ts", "src/tests", "src/migrations/cli.ts"],
59
- "include": ["src/**/*.ts*", "src/*.ts", "src/**/*.js", "src/**/*.d.ts"]
17
+ "exclude": ["node_modules", "**/*.test.ts", "**/*.isolated.ts", "src/isolated", "src/tests", "src/migrations/cli.ts"],
18
+ "include": ["src"]
60
19
  }