@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.
- package/README.md +5 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/api.js +617 -852
- package/dist/audit/auditApp.js +48 -89
- package/dist/audit/auditEventModel.js +15 -16
- package/dist/audit/cloudTasksEnqueue.js +56 -149
- package/dist/audit/diff.js +70 -160
- package/dist/audit/processQueue.js +25 -70
- package/dist/audit/rbacSink.js +25 -66
- package/dist/audit/record.js +129 -251
- package/dist/auth.js +432 -681
- package/dist/authRecovery.js +155 -269
- package/dist/authTokens.js +43 -118
- package/dist/betterAuthApp.js +25 -26
- package/dist/betterAuthSetup.js +258 -413
- package/dist/browserLogsRoute.d.ts +6 -0
- package/dist/browserLogsRoute.js +97 -0
- package/dist/collectionRegistry.js +32 -47
- package/dist/config.js +53 -122
- package/dist/configurationApp.js +180 -361
- package/dist/configurationPlugin.js +130 -302
- package/dist/consentApp.js +276 -421
- package/dist/docLoader.js +78 -126
- package/dist/envConfigurationPlugin.js +25 -147
- package/dist/errors.js +151 -247
- package/dist/example.js +28 -34
- package/dist/expressServer.d.ts +10 -0
- package/dist/expressServer.js +109 -255
- package/dist/frameworkModelNames.d.ts +24 -0
- package/dist/frameworkModelNames.js +31 -0
- package/dist/githubAuth.js +152 -216
- package/dist/httpClient.js +176 -264
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -2
- package/dist/logger.js +145 -278
- package/dist/mcp/auth.js +76 -128
- package/dist/mcp/createMCPRequest.js +4 -5
- package/dist/mcp/handlers.js +268 -480
- package/dist/mcp/query.js +56 -150
- package/dist/mcp/registry.js +17 -30
- package/dist/mcp/schemaGenerator.js +95 -181
- package/dist/mcp/server.js +28 -100
- package/dist/mcp/serviceTokens.js +102 -191
- package/dist/mcp/toolGenerator.js +78 -191
- package/dist/middleware.js +15 -27
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
- package/dist/migrations/generate.js +107 -229
- package/dist/migrations/load.js +75 -201
- package/dist/migrations/lock.js +54 -126
- package/dist/migrations/runner.js +192 -446
- package/dist/migrations/schemaCatalog.js +122 -263
- package/dist/models/consentForm.js +6 -6
- package/dist/models/consentResponse.js +5 -5
- package/dist/models/mcpServiceToken.js +66 -156
- package/dist/models/notification.js +6 -6
- package/dist/models/notificationPreference.js +6 -6
- package/dist/models/versionConfig.js +5 -5
- package/dist/notifications/notificationService.js +133 -273
- package/dist/notifications/notificationsApp.js +85 -179
- package/dist/notifications/notificationsBeforeSend.js +19 -64
- package/dist/notifiers/googleChatNotifier.js +36 -117
- package/dist/notifiers/slackNotifier.d.ts +31 -2
- package/dist/notifiers/slackNotifier.js +170 -119
- package/dist/notifiers/zoomNotifier.js +60 -111
- package/dist/openApi.js +107 -122
- package/dist/openApiBuilder.js +117 -159
- package/dist/openApiCompat.js +81 -148
- package/dist/openApiEtag.js +7 -7
- package/dist/openApiValidator.js +177 -286
- package/dist/orgs/orgContext.js +87 -157
- package/dist/orgs/orgPermissions.js +29 -68
- package/dist/orgs/orgPlugin.js +9 -27
- package/dist/orgs/organizationModel.js +65 -166
- package/dist/orgs/organizationSettings.js +29 -36
- package/dist/orgs/orgsApp.js +346 -608
- package/dist/permissions.js +88 -181
- package/dist/plugins.js +125 -218
- package/dist/populate.js +130 -240
- package/dist/rateLimit/applyTrustProxy.js +1 -1
- package/dist/rateLimit/createStore.js +7 -8
- package/dist/rateLimit/memoryStore.js +22 -100
- package/dist/rateLimit/middleware.js +48 -99
- package/dist/rateLimit/mongoStore.js +54 -112
- package/dist/rateLimit/policies.js +41 -75
- package/dist/rateLimit/redisStore.js +39 -133
- package/dist/rbac/access.js +119 -267
- package/dist/rbac/assertAllowed.js +95 -171
- package/dist/rbac/auditModel.js +14 -58
- package/dist/rbac/backfillAdmins.js +24 -130
- package/dist/rbac/fieldViews.js +46 -141
- package/dist/rbac/membershipOrgAdminSource.js +28 -99
- package/dist/rbac/middleware.js +30 -96
- package/dist/rbac/modelRouterAccess.js +130 -307
- package/dist/rbac/permissionUtils.js +40 -179
- package/dist/rbac/realtimeAccess.js +81 -147
- package/dist/rbac/resolve.d.ts +1 -1
- package/dist/rbac/resolve.js +148 -342
- package/dist/rbac/roleManager.js +318 -700
- package/dist/rbac/roleModel.js +44 -171
- package/dist/rbac/routes.js +93 -196
- package/dist/rbac/scopes.js +39 -133
- package/dist/rbac/statements.js +23 -91
- package/dist/rbac/userPlugin.js +3 -29
- package/dist/realtime/changeStreamWatcher.js +489 -800
- package/dist/realtime/deprecation.js +8 -10
- package/dist/realtime/queryMatcher.js +110 -191
- package/dist/realtime/queryStore.js +35 -118
- package/dist/realtime/realtimeApp.js +247 -401
- package/dist/realtime/registry.js +19 -30
- package/dist/realtime/sessionRevalidation.js +132 -358
- package/dist/realtime/socketAuth.js +89 -208
- package/dist/realtime/socketUser.js +10 -56
- package/dist/requestContext.js +93 -139
- package/dist/schemaMetadata.js +179 -274
- package/dist/scriptRunner.js +96 -266
- package/dist/scrubAdminFields.js +36 -108
- package/dist/secretProviders.js +130 -299
- package/dist/seedRunner.js +221 -514
- package/dist/sync/adminBroadcastScope.js +58 -170
- package/dist/sync/adminWindowAccess.js +15 -86
- package/dist/sync/adminWindowMutation.js +110 -181
- package/dist/sync/executors.js +425 -629
- package/dist/sync/loadHarness.js +392 -689
- package/dist/sync/models.js +181 -341
- package/dist/sync/mutationHandler.js +533 -801
- package/dist/sync/registrationSideEffects.js +41 -95
- package/dist/sync/registry.js +29 -49
- package/dist/sync/routes.js +484 -817
- package/dist/sync/scripts/compactTombstones.js +83 -228
- package/dist/sync/serialize.js +18 -58
- package/dist/sync/socketHandlers.js +253 -478
- package/dist/sync/streams.js +49 -117
- package/dist/sync/syncApp.js +12 -15
- package/dist/sync/syncBatch.js +63 -168
- package/dist/sync/syncSeqPlugin.js +430 -702
- package/dist/syncConsents.js +113 -253
- package/dist/terrenoApp.js +166 -276
- package/dist/tests/createTestData.js +146 -256
- package/dist/tests/models.js +14 -54
- package/dist/tests/mongoTestSetup.js +42 -103
- package/dist/tests/testHelper.js +31 -93
- package/dist/tests.js +12 -51
- package/dist/transformers.js +61 -164
- package/dist/utils.js +31 -93
- package/dist/vendor/wesleytodd-openapi/index.js +37 -51
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
- package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
- package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
- package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
- package/dist/versionCheckPlugin.js +52 -100
- package/dist/webhooks/headerValue.js +2 -2
- package/dist/webhooks/idempotency/memoryStore.js +16 -59
- package/dist/webhooks/idempotency/mongoStore.js +55 -130
- package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
- package/dist/webhooks/rawBody.js +1 -1
- package/dist/webhooks/timingSafeEqual.js +4 -5
- package/dist/webhooks/verifiers/hmac.js +17 -18
- package/dist/webhooks/verifiers/sendgrid.js +20 -22
- package/dist/webhooks/verifiers/stripe.js +31 -65
- package/dist/webhooks/verifiers/twilio.js +23 -73
- package/dist/webhooks/webhooksApp.js +78 -177
- package/dist/zodOpenApi.js +2 -2
- package/package.json +6 -6
- package/src/__tests__/browserLogsRoute.test.ts +165 -0
- package/src/api.arrayOperations.test.ts +44 -0
- package/src/api.ts +64 -39
- package/src/audit/auditApp.test.ts +5 -5
- package/src/audit/auditEventModel.ts +7 -3
- package/src/audit/auditRouter.test.ts +5 -5
- package/src/audit/rbacSink.test.ts +2 -2
- package/src/audit/record.test.ts +2 -2
- package/src/audit/record.ts +3 -2
- package/src/auth.ts +1 -1
- package/src/authRecovery.test.ts +43 -0
- package/src/authRecovery.ts +16 -10
- package/src/authTokens.ts +6 -2
- package/src/authVerification.test.ts +22 -0
- package/src/browserLogsRoute.ts +110 -0
- package/src/configurationPlugin.test.ts +1 -11
- package/src/expressServer.ts +10 -0
- package/src/frameworkModelNames.test.ts +62 -0
- package/src/frameworkModelNames.ts +33 -0
- package/src/index.ts +7 -0
- package/src/isolated/migrateCliConnect.isolated.ts +51 -0
- package/src/mcp/auth.test.ts +34 -1
- package/src/migrations/cli.test.ts +0 -23
- package/src/models/mcpServiceToken.ts +4 -3
- package/src/models/notification.ts +3 -2
- package/src/models/notificationPreference.ts +1 -1
- package/src/notifications/notificationsApp.test.ts +24 -1
- package/src/notifiers/slackNotifier.test.ts +186 -1
- package/src/notifiers/slackNotifier.ts +167 -8
- package/src/orgs/orgPlugin.ts +1 -1
- package/src/orgs/organizationModel.ts +11 -6
- package/src/plugins.test.ts +5 -0
- package/src/plugins.ts +3 -0
- package/src/realtime/realtimeApp.ts +1 -1
- package/src/sync/integration.test.ts +2 -2
- package/src/terrenoApp.ts +3 -0
- package/src/types.d.ts +1 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
- package/tsconfig.json +13 -54
- 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
|
+
});
|
package/src/mcp/auth.test.ts
CHANGED
|
@@ -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.
|
|
154
|
+
(mongoose.models.TerrenoMcpServiceToken as McpServiceTokenModel | undefined) ??
|
|
155
155
|
mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
|
|
156
|
-
"
|
|
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
|
-
"
|
|
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
|
-
>("
|
|
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 {
|
|
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 {
|
|
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
|
});
|