@terreno/api 57.4.0 → 57.6.1

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 (210) 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 +617 -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/api.arrayOperations.test.ts +44 -0
  173. package/src/api.ts +64 -39
  174. package/src/audit/auditApp.test.ts +5 -5
  175. package/src/audit/auditEventModel.ts +7 -3
  176. package/src/audit/auditRouter.test.ts +5 -5
  177. package/src/audit/rbacSink.test.ts +2 -2
  178. package/src/audit/record.test.ts +2 -2
  179. package/src/audit/record.ts +3 -2
  180. package/src/auth.ts +1 -1
  181. package/src/authRecovery.test.ts +43 -0
  182. package/src/authRecovery.ts +16 -10
  183. package/src/authTokens.ts +6 -2
  184. package/src/authVerification.test.ts +22 -0
  185. package/src/browserLogsRoute.ts +110 -0
  186. package/src/configurationPlugin.test.ts +1 -11
  187. package/src/expressServer.ts +10 -0
  188. package/src/frameworkModelNames.test.ts +62 -0
  189. package/src/frameworkModelNames.ts +33 -0
  190. package/src/index.ts +7 -0
  191. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  192. package/src/mcp/auth.test.ts +34 -1
  193. package/src/migrations/cli.test.ts +0 -23
  194. package/src/models/mcpServiceToken.ts +4 -3
  195. package/src/models/notification.ts +3 -2
  196. package/src/models/notificationPreference.ts +1 -1
  197. package/src/notifications/notificationsApp.test.ts +24 -1
  198. package/src/notifiers/slackNotifier.test.ts +186 -1
  199. package/src/notifiers/slackNotifier.ts +167 -8
  200. package/src/orgs/orgPlugin.ts +1 -1
  201. package/src/orgs/organizationModel.ts +11 -6
  202. package/src/plugins.test.ts +5 -0
  203. package/src/plugins.ts +3 -0
  204. package/src/realtime/realtimeApp.ts +1 -1
  205. package/src/sync/integration.test.ts +2 -2
  206. package/src/terrenoApp.ts +3 -0
  207. package/src/types.d.ts +1 -0
  208. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  209. package/tsconfig.json +13 -54
  210. package/tsconfig.typedoc.json +2 -0
@@ -0,0 +1,62 @@
1
+ import {afterAll, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import mongoose from "mongoose";
4
+
5
+ import {createAuditEventModel} from "./audit/auditEventModel";
6
+ import {AuthToken} from "./authTokens";
7
+ import {FRAMEWORK_MODEL_PUBLIC_NAMES, publicFrameworkModelName} from "./frameworkModelNames";
8
+ import {McpServiceToken} from "./models/mcpServiceToken";
9
+ import {Notification} from "./models/notification";
10
+ import {NotificationPreference} from "./models/notificationPreference";
11
+ import {getMembershipModel, getOrganizationModel} from "./orgs/organizationModel";
12
+ import {getWebhookReceiptModel} from "./webhooks/idempotency/webhookReceipt";
13
+
14
+ const CONSUMER_MODEL_NAMES = [
15
+ "AuditEvent",
16
+ "AuthToken",
17
+ "McpServiceToken",
18
+ "Membership",
19
+ "Notification",
20
+ "NotificationPreference",
21
+ "Organization",
22
+ "WebhookReceipt",
23
+ ] as const;
24
+
25
+ afterAll(() => {
26
+ for (const modelName of CONSUMER_MODEL_NAMES) {
27
+ if (mongoose.models[modelName]) {
28
+ mongoose.deleteModel(modelName);
29
+ }
30
+ }
31
+ });
32
+
33
+ describe("framework model names", () => {
34
+ it("uses Terreno-specific names without changing existing collection names", () => {
35
+ const models = [
36
+ [createAuditEventModel(mongoose.connection), "TerrenoAuditEvent", "auditevents"],
37
+ [AuthToken, "TerrenoAuthToken", "authtokens"],
38
+ [McpServiceToken, "TerrenoMcpServiceToken", "mcpservicetokens"],
39
+ [getMembershipModel(), "TerrenoMembership", "memberships"],
40
+ [Notification, "TerrenoInboxNotification", "notifications"],
41
+ [NotificationPreference, "TerrenoNotificationPreference", "notificationpreferences"],
42
+ [getOrganizationModel(), "TerrenoOrganization", "organizations"],
43
+ [getWebhookReceiptModel(), "TerrenoWebhookReceipt", "webhookReceipts"],
44
+ ] as const;
45
+
46
+ for (const [model, modelName, collectionName] of models) {
47
+ assert.equal(model.modelName, modelName);
48
+ assert.equal(model.collection.collectionName, collectionName);
49
+ assert.equal(publicFrameworkModelName(modelName), FRAMEWORK_MODEL_PUBLIC_NAMES[modelName]);
50
+ }
51
+ assert.equal(publicFrameworkModelName("Todo"), "Todo");
52
+ assert.equal(publicFrameworkModelName("TerrenoInboxNotification"), "Notification");
53
+ assert.equal(publicFrameworkModelName("TerrenoAnnouncement"), "Announcement");
54
+ assert.equal(publicFrameworkModelName("TerrenoJob"), "Job");
55
+ });
56
+
57
+ it("allows consumers to register the former generic model names", () => {
58
+ for (const modelName of CONSUMER_MODEL_NAMES) {
59
+ assert.doesNotThrow(() => mongoose.model(modelName, new mongoose.Schema({})));
60
+ }
61
+ });
62
+ });
@@ -0,0 +1,33 @@
1
+ /** Mongoose compiled names for framework models that used to be generic. */
2
+ export const FRAMEWORK_MODEL_PUBLIC_NAMES = {
3
+ TerrenoAnnouncement: "Announcement",
4
+ TerrenoAnnouncementAcknowledgement: "AnnouncementAcknowledgement",
5
+ TerrenoAnnouncementClickEvent: "AnnouncementClickEvent",
6
+ TerrenoAnnouncementImpression: "AnnouncementImpression",
7
+ TerrenoAuditEvent: "AuditEvent",
8
+ TerrenoAuthToken: "AuthToken",
9
+ TerrenoInboxNotification: "Notification",
10
+ TerrenoJob: "Job",
11
+ TerrenoJobSchedule: "JobSchedule",
12
+ TerrenoMcpServiceToken: "McpServiceToken",
13
+ TerrenoMembership: "Membership",
14
+ TerrenoNotificationPreference: "NotificationPreference",
15
+ TerrenoOrganization: "Organization",
16
+ TerrenoWebhookReceipt: "WebhookReceipt",
17
+ } as const;
18
+
19
+ export type FrameworkModelCompiledName = keyof typeof FRAMEWORK_MODEL_PUBLIC_NAMES;
20
+
21
+ export type FrameworkModelPublicName =
22
+ (typeof FRAMEWORK_MODEL_PUBLIC_NAMES)[FrameworkModelCompiledName];
23
+
24
+ /**
25
+ * Admin UI keys and `admin<ModelName>` RBAC resources keep the pre-namespace names so
26
+ * consumer statements and `/admin/AuditEvent` routes stay stable.
27
+ */
28
+ export const publicFrameworkModelName = (modelName: string): string => {
29
+ if (modelName in FRAMEWORK_MODEL_PUBLIC_NAMES) {
30
+ return FRAMEWORK_MODEL_PUBLIC_NAMES[modelName as FrameworkModelCompiledName];
31
+ }
32
+ return modelName;
33
+ };
package/src/index.ts CHANGED
@@ -36,6 +36,7 @@ export * from "./authTokens";
36
36
  export * from "./betterAuth";
37
37
  export * from "./betterAuthApp";
38
38
  export * from "./betterAuthSetup";
39
+ export * from "./browserLogsRoute";
39
40
  export * from "./config";
40
41
  export * from "./configurationApp";
41
42
  export * from "./configurationPlugin";
@@ -43,6 +44,12 @@ export * from "./consentApp";
43
44
  export * from "./envConfigurationPlugin";
44
45
  export * from "./errors";
45
46
  export * from "./expressServer";
47
+ export {
48
+ FRAMEWORK_MODEL_PUBLIC_NAMES,
49
+ type FrameworkModelCompiledName,
50
+ type FrameworkModelPublicName,
51
+ publicFrameworkModelName,
52
+ } from "./frameworkModelNames";
46
53
  export * from "./githubAuth";
47
54
  export * from "./httpClient";
48
55
  export * from "./logger";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Isolated because `runMigrateCli` disconnects the default mongoose connection
3
+ * when it opens Mongo from a URI. Sharing that with the rest of `bun test` races
4
+ * org/notification/MCP suites.
5
+ */
6
+ import {describe, it} from "bun:test";
7
+ import {join} from "node:path";
8
+ import {assert} from "chai";
9
+ import mongoose from "mongoose";
10
+ import {runMigrateCli} from "../migrations/cli";
11
+ import {setupDb} from "../tests";
12
+
13
+ const fixtures = (...parts: string[]): string => {
14
+ return join(import.meta.dir, "..", "migrations", "fixtures", ...parts);
15
+ };
16
+
17
+ describe("runMigrateCli Mongo URI connect", () => {
18
+ it("connects and disconnects itself when given a Mongo URI", async () => {
19
+ await setupDb();
20
+ const {host, name, port} = mongoose.connection;
21
+ const uri = `mongodb://${host}:${port}/${name}`;
22
+ await mongoose.disconnect();
23
+ assert.equal(mongoose.connection.readyState, 0);
24
+
25
+ try {
26
+ const out: string[] = [];
27
+ const err: string[] = [];
28
+ const code = await runMigrateCli({
29
+ argv: ["status", "--dir", fixtures("valid")],
30
+ env: {MONGODB_URI: uri, NODE_ENV: "test"},
31
+ stderr: {
32
+ write: (chunk: string): void => {
33
+ err.push(chunk);
34
+ },
35
+ },
36
+ stdout: {
37
+ write: (chunk: string): void => {
38
+ out.push(chunk);
39
+ },
40
+ },
41
+ });
42
+ assert.equal(code, 0);
43
+ assert.include(out.join(""), "Applied (0)");
44
+ assert.include(out.join(""), "Pending (2)");
45
+ assert.equal(err.join(""), "");
46
+ assert.equal(mongoose.connection.readyState, 0);
47
+ } finally {
48
+ await mongoose.connect(uri);
49
+ }
50
+ });
51
+ });
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, expect, it} from "bun:test";
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import jwt from "jsonwebtoken";
4
4
  import mongoose, {Schema} from "mongoose";
@@ -234,6 +234,39 @@ describe("extractUserFromHeaders", () => {
234
234
  expect(user).toBeUndefined();
235
235
  });
236
236
 
237
+ it("returns undefined when the JWT references a user that no longer exists", async () => {
238
+ const token = signToken({id: new mongoose.Types.ObjectId().toString()});
239
+
240
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
241
+
242
+ assert.isUndefined(user);
243
+ });
244
+
245
+ it("still resolves the MCP service token owner when the last-used update fails", async () => {
246
+ const created = await UserTestModel.create({email: "last-used-fails@example.com"});
247
+ const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Flaky"});
248
+ const updateSpy = spyOn(McpServiceToken, "updateOne").mockImplementation(
249
+ () =>
250
+ ({
251
+ catch: (handler: (error: unknown) => void) => {
252
+ handler(new Error("write failed"));
253
+ },
254
+ }) as unknown as ReturnType<typeof McpServiceToken.updateOne>
255
+ );
256
+
257
+ try {
258
+ const user = await extractUserFromHeaders(
259
+ {authorization: `Bearer ${issued.token}`},
260
+ {mcpServiceTokens: true, userModel}
261
+ );
262
+
263
+ assert.equal(String((user as unknown as MCPAuthUserFields)?._id), created._id.toString());
264
+ assert.equal(updateSpy.mock.calls.length, 1);
265
+ } finally {
266
+ updateSpy.mockRestore();
267
+ }
268
+ });
269
+
237
270
  it("returns undefined when Better Auth has no session and no JWT is present", async () => {
238
271
  const betterAuth = fakeBetterAuth(async () => null);
239
272
 
@@ -216,29 +216,6 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
216
216
  }
217
217
  });
218
218
 
219
- it("connects and disconnects itself when given a Mongo URI", async () => {
220
- const {host, name, port} = mongoose.connection;
221
- const uri = `mongodb://${host}:${port}/${name}`;
222
- await mongoose.disconnect();
223
- expect(mongoose.connection.readyState).toBe(0);
224
-
225
- try {
226
- const io = capture();
227
- const code = await runMigrateCli({
228
- argv: ["status", "--dir", fixtures("valid")],
229
- env: {MONGODB_URI: uri, NODE_ENV: "test"},
230
- stderr: {write: io.writeErr},
231
- stdout: {write: io.writeOut},
232
- });
233
- expect(code).toBe(0);
234
- expect(io.stdout).toContain("Applied (0)");
235
- expect(io.stdout).toContain("Pending (2)");
236
- expect(mongoose.connection.readyState).toBe(0);
237
- } finally {
238
- await mongoose.connect(uri);
239
- }
240
- });
241
-
242
219
  it("writes help to process stdout when io is omitted", async () => {
243
220
  expect(await runMigrateCli({argv: ["--help"]})).toBe(0);
244
221
  expect(await runMigrateCli({argv: ["nope"]})).toBe(1);
@@ -151,8 +151,9 @@ mcpServiceTokenSchema.statics = {
151
151
  };
152
152
 
153
153
  export const McpServiceToken =
154
- (mongoose.models.McpServiceToken as McpServiceTokenModel | undefined) ??
154
+ (mongoose.models.TerrenoMcpServiceToken as McpServiceTokenModel | undefined) ??
155
155
  mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
156
- "McpServiceToken",
157
- mcpServiceTokenSchema
156
+ "TerrenoMcpServiceToken",
157
+ mcpServiceTokenSchema,
158
+ "mcpservicetokens"
158
159
  );
@@ -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
  });