@agent-native/dispatch 0.0.0-beta-20260819155526 → 0.0.0-beta-20260819172516
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/dist/actions/ask_app.d.ts +1 -0
- package/dist/actions/ask_app_status.d.ts +1 -0
- package/dist/server/lib/dispatch-integrations.d.ts.map +1 -1
- package/dist/server/lib/dispatch-integrations.js +149 -7
- package/dist/server/lib/dispatch-integrations.js.map +1 -1
- package/dist/server/lib/dispatch-store.d.ts +1 -0
- package/dist/server/lib/dispatch-store.d.ts.map +1 -1
- package/dist/server/lib/dispatch-store.js +4 -0
- package/dist/server/lib/dispatch-store.js.map +1 -1
- package/dist/server/lib/mcp-gateway.d.ts +8 -2
- package/dist/server/lib/mcp-gateway.d.ts.map +1 -1
- package/dist/server/lib/mcp-gateway.js +39 -6
- package/dist/server/lib/mcp-gateway.js.map +1 -1
- package/package.json +4 -4
- package/src/server/lib/dispatch-integrations.spec.ts +578 -7
- package/src/server/lib/dispatch-integrations.ts +186 -9
- package/src/server/lib/dispatch-store.ts +7 -0
- package/src/server/lib/mcp-gateway.spec.ts +328 -17
- package/src/server/lib/mcp-gateway.ts +59 -4
|
@@ -9,6 +9,7 @@ declare const _default: import("@agent-native/core").ActionDefinition<{
|
|
|
9
9
|
taskId: string;
|
|
10
10
|
status: string;
|
|
11
11
|
response?: string;
|
|
12
|
+
receipts?: import("node_modules/@agent-native/core/dist/a2a/artifact-response.js").A2APersistedMutationReceipt[];
|
|
12
13
|
error?: string;
|
|
13
14
|
inputRequired?: string;
|
|
14
15
|
statusRead?: "unavailable";
|
|
@@ -7,6 +7,7 @@ declare const _default: import("@agent-native/core").ActionDefinition<{
|
|
|
7
7
|
taskId: string;
|
|
8
8
|
status: string;
|
|
9
9
|
response?: string;
|
|
10
|
+
receipts?: import("node_modules/@agent-native/core/dist/a2a/artifact-response.js").A2APersistedMutationReceipt[];
|
|
10
11
|
error?: string;
|
|
11
12
|
inputRequired?: string;
|
|
12
13
|
statusRead?: "unavailable";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatch-integrations.d.ts","sourceRoot":"","sources":["../../../src/server/lib/dispatch-integrations.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,2BAA2B,EAC3B,eAAe,EAChB,MAAM,2BAA2B,CAAC;AA2BnC,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,eAAe,GACxB,MAAM,GAAG,IAAI,CAmBf;
|
|
1
|
+
{"version":3,"file":"dispatch-integrations.d.ts","sourceRoot":"","sources":["../../../src/server/lib/dispatch-integrations.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,2BAA2B,EAC3B,eAAe,EAChB,MAAM,2BAA2B,CAAC;AA2BnC,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,eAAe,GACxB,MAAM,GAAG,IAAI,CAmBf;AA+VD,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,CAAC,CA8DjB;AAED;;;;GAIG;AACH,wBAAsB,+BAA+B,CACnD,QAAQ,EAAE,eAAe,GACxB,OAAO,CAAC,2BAA2B,CAAC,CAwHtC;AAED,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAA;CAAE,CAAC,CA0FxE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import { evaluateIntegrationScopePolicy, getActiveIntegrationInstallationByKey, getIntegrationScope, resolveIntegrationTokenBundle, resolveSlackBotTokenForIncoming, saveIntegrationScope, slackInstallationKey, } from "@agent-native/core/integrations";
|
|
3
|
-
import { resolveOrgIdForEmail } from "@agent-native/core/org";
|
|
3
|
+
import { isOrgMember, resolveOrgIdForEmail } from "@agent-native/core/org";
|
|
4
4
|
import { withConfiguredAppBasePath } from "@agent-native/core/server";
|
|
5
5
|
import { handleRemoteCodeCommand } from "./dispatch-remote-commands.js";
|
|
6
6
|
import { dispatchIntegrationRoutingHint, } from "./dispatch-routing.js";
|
|
@@ -82,14 +82,30 @@ async function resolveManagedSlackInstallation(incoming) {
|
|
|
82
82
|
if (incoming.platform !== "slack")
|
|
83
83
|
return null;
|
|
84
84
|
const teamId = contextString(incoming.platformContext.teamId);
|
|
85
|
+
const enterpriseId = contextString(incoming.platformContext.enterpriseId);
|
|
85
86
|
const apiAppId = contextString(incoming.platformContext.apiAppId);
|
|
86
|
-
|
|
87
|
+
const isEnterpriseInstall = incoming.platformContext.isEnterpriseInstall === true;
|
|
88
|
+
if ((!teamId && !enterpriseId) || (isEnterpriseInstall && !enterpriseId))
|
|
87
89
|
return null;
|
|
90
|
+
return getActiveIntegrationInstallationByKey("slack", slackInstallationKey({
|
|
91
|
+
teamId,
|
|
92
|
+
enterpriseId,
|
|
93
|
+
apiAppId,
|
|
94
|
+
isEnterpriseInstall,
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
class ManagedSlackInstallationLookupError extends Error {
|
|
98
|
+
constructor(options) {
|
|
99
|
+
super("Managed Slack installation identity is temporarily unavailable", options);
|
|
100
|
+
this.name = "ManagedSlackInstallationLookupError";
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function resolveManagedSlackInstallationOrFail(incoming) {
|
|
88
104
|
try {
|
|
89
|
-
return await
|
|
105
|
+
return await resolveManagedSlackInstallation(incoming);
|
|
90
106
|
}
|
|
91
|
-
catch {
|
|
92
|
-
|
|
107
|
+
catch (cause) {
|
|
108
|
+
throw new ManagedSlackInstallationLookupError({ cause });
|
|
93
109
|
}
|
|
94
110
|
}
|
|
95
111
|
async function resolveManagedSlackToken(incoming) {
|
|
@@ -113,6 +129,12 @@ function formatSlackLinkRequiredMessage() {
|
|
|
113
129
|
: "Open Dispatch while signed in, create a Slack link token, then send `/link <token>` in this DM.";
|
|
114
130
|
return `Agent Native is ready, but this Slack account is not linked to an Agent Native user yet. ${linkStep}`;
|
|
115
131
|
}
|
|
132
|
+
function formatSlackIdentityVerificationFailedMessage() {
|
|
133
|
+
return "I couldn't verify your Slack identity just now, so I can't run this request. Please try again in a moment.";
|
|
134
|
+
}
|
|
135
|
+
function formatSlackIdentityDeniedMessage() {
|
|
136
|
+
return "This assistant is only available to members of this workspace's organization.";
|
|
137
|
+
}
|
|
116
138
|
async function resolveSlackSenderProfile(incoming) {
|
|
117
139
|
if (incoming.platform !== "slack") {
|
|
118
140
|
return { email: null, name: null, trust: "unknown" };
|
|
@@ -147,7 +169,8 @@ async function resolveSlackSenderProfile(incoming) {
|
|
|
147
169
|
data.user?.real_name?.trim() ||
|
|
148
170
|
data.user?.name?.trim() ||
|
|
149
171
|
null,
|
|
150
|
-
trust: data.user?.
|
|
172
|
+
trust: data.user?.is_stranger === true ||
|
|
173
|
+
data.user?.is_ultra_restricted === true
|
|
151
174
|
? "external_shared"
|
|
152
175
|
: data.user?.is_restricted === true
|
|
153
176
|
? "guest"
|
|
@@ -179,6 +202,74 @@ async function resolveSlackOwnerFromVerifiedEmail(incoming) {
|
|
|
179
202
|
const orgId = await resolveOrgIdForEmail(profile.email);
|
|
180
203
|
return orgId ? profile.email : null;
|
|
181
204
|
}
|
|
205
|
+
async function resolveManagedSlackDmExecutionContext(incoming, installation) {
|
|
206
|
+
const profile = await resolveSlackSenderProfile(incoming);
|
|
207
|
+
incoming.actorTrust = {
|
|
208
|
+
memberType: profile.trust === "guest"
|
|
209
|
+
? "guest"
|
|
210
|
+
: profile.trust === "external_shared"
|
|
211
|
+
? "external"
|
|
212
|
+
: profile.trust === "trusted"
|
|
213
|
+
? "member"
|
|
214
|
+
: "unknown",
|
|
215
|
+
verified: profile.trust !== "unknown",
|
|
216
|
+
};
|
|
217
|
+
incoming.senderVerified = profile.email !== null;
|
|
218
|
+
if (profile.email) {
|
|
219
|
+
incoming.senderEmail = profile.email;
|
|
220
|
+
incoming.platformContext.senderEmail = profile.email;
|
|
221
|
+
}
|
|
222
|
+
if (profile.name) {
|
|
223
|
+
incoming.senderName = profile.name;
|
|
224
|
+
incoming.platformContext.senderName = profile.name;
|
|
225
|
+
}
|
|
226
|
+
const deniedContext = () => ({
|
|
227
|
+
ownerEmail: fallbackOwnerForIncoming(incoming),
|
|
228
|
+
orgId: null,
|
|
229
|
+
principalType: "user",
|
|
230
|
+
installationId: installation.id,
|
|
231
|
+
});
|
|
232
|
+
if (profile.trust === "unknown") {
|
|
233
|
+
incoming.platformContext.identityVerificationFailed = true;
|
|
234
|
+
return deniedContext();
|
|
235
|
+
}
|
|
236
|
+
if (profile.trust === "guest" || profile.trust === "external_shared") {
|
|
237
|
+
incoming.platformContext.identityAccessDenied = true;
|
|
238
|
+
return deniedContext();
|
|
239
|
+
}
|
|
240
|
+
if (!installation.orgId) {
|
|
241
|
+
incoming.platformContext.identityLinkRequired = true;
|
|
242
|
+
return deniedContext();
|
|
243
|
+
}
|
|
244
|
+
incoming.platformContext.managedInstallationOrgId = installation.orgId;
|
|
245
|
+
let linkedOwner;
|
|
246
|
+
try {
|
|
247
|
+
linkedOwner = await resolveLinkedOwner("slack", identityKeyForIncoming(incoming), { orgId: installation.orgId });
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
incoming.platformContext.identityVerificationFailed = true;
|
|
251
|
+
return deniedContext();
|
|
252
|
+
}
|
|
253
|
+
const candidates = [profile.email, linkedOwner].filter((email, index, values) => !!email && values.indexOf(email) === index);
|
|
254
|
+
for (const ownerEmail of candidates) {
|
|
255
|
+
try {
|
|
256
|
+
if (await isOrgMember(installation.orgId, ownerEmail)) {
|
|
257
|
+
return {
|
|
258
|
+
ownerEmail,
|
|
259
|
+
orgId: installation.orgId,
|
|
260
|
+
principalType: "user",
|
|
261
|
+
installationId: installation.id,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
incoming.platformContext.identityVerificationFailed = true;
|
|
267
|
+
return deniedContext();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
incoming.platformContext.identityLinkRequired = true;
|
|
271
|
+
return deniedContext();
|
|
272
|
+
}
|
|
182
273
|
async function resolveSlackConversationTrust(incoming, actorTrust) {
|
|
183
274
|
if (incoming.triggerKind === "dm") {
|
|
184
275
|
return { trust: actorTrust, conversationType: "direct_message" };
|
|
@@ -276,6 +367,31 @@ export async function resolveDispatchOwner(incoming) {
|
|
|
276
367
|
* personal credentials or memory.
|
|
277
368
|
*/
|
|
278
369
|
export async function resolveDispatchExecutionContext(incoming) {
|
|
370
|
+
if (incoming.platform === "slack" && incoming.triggerKind === "dm") {
|
|
371
|
+
let installation;
|
|
372
|
+
try {
|
|
373
|
+
installation = await resolveManagedSlackInstallationOrFail(incoming);
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
if (!(error instanceof ManagedSlackInstallationLookupError))
|
|
377
|
+
throw error;
|
|
378
|
+
incoming.platformContext.identityVerificationFailed = true;
|
|
379
|
+
return {
|
|
380
|
+
ownerEmail: fallbackOwnerForIncoming(incoming),
|
|
381
|
+
orgId: null,
|
|
382
|
+
principalType: "user",
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (installation) {
|
|
386
|
+
return resolveManagedSlackDmExecutionContext(incoming, installation);
|
|
387
|
+
}
|
|
388
|
+
incoming.platformContext.identityVerificationFailed = true;
|
|
389
|
+
return {
|
|
390
|
+
ownerEmail: fallbackOwnerForIncoming(incoming),
|
|
391
|
+
orgId: null,
|
|
392
|
+
principalType: "user",
|
|
393
|
+
};
|
|
394
|
+
}
|
|
279
395
|
if (incoming.platform !== "slack" || incoming.triggerKind === "dm") {
|
|
280
396
|
const ownerEmail = await resolveDispatchOwner(incoming);
|
|
281
397
|
if (incoming.platform === "slack" &&
|
|
@@ -291,7 +407,7 @@ export async function resolveDispatchExecutionContext(incoming) {
|
|
|
291
407
|
principalType: "user",
|
|
292
408
|
};
|
|
293
409
|
}
|
|
294
|
-
const installation = await
|
|
410
|
+
const installation = await resolveManagedSlackInstallationOrFail(incoming);
|
|
295
411
|
if (!installation) {
|
|
296
412
|
// Preserve the legacy manually configured app path while managed installs
|
|
297
413
|
// roll out. Its behavior remains explicit and visible in Settings.
|
|
@@ -365,6 +481,30 @@ export async function beforeDispatchProcess(incoming, adapter) {
|
|
|
365
481
|
const trimmed = incoming.text.trim();
|
|
366
482
|
const commandText = contextString(incoming.platformContext.rawText) || trimmed;
|
|
367
483
|
const match = commandText.match(/^\/link(?:@\w+)?\s+([a-zA-Z0-9_-]+)$/);
|
|
484
|
+
if (match &&
|
|
485
|
+
incoming.platform === "slack" &&
|
|
486
|
+
incoming.triggerKind === "dm" &&
|
|
487
|
+
!contextString(incoming.platformContext.managedInstallationOrgId) &&
|
|
488
|
+
incoming.platformContext.identityVerificationFailed !== true &&
|
|
489
|
+
incoming.platformContext.identityAccessDenied !== true) {
|
|
490
|
+
await resolveDispatchExecutionContext(incoming);
|
|
491
|
+
}
|
|
492
|
+
if (incoming.platform === "slack" &&
|
|
493
|
+
incoming.triggerKind === "dm" &&
|
|
494
|
+
incoming.platformContext.identityVerificationFailed === true) {
|
|
495
|
+
return {
|
|
496
|
+
handled: true,
|
|
497
|
+
responseText: formatSlackIdentityVerificationFailedMessage(),
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
if (incoming.platform === "slack" &&
|
|
501
|
+
incoming.triggerKind === "dm" &&
|
|
502
|
+
incoming.platformContext.identityAccessDenied === true) {
|
|
503
|
+
return {
|
|
504
|
+
handled: true,
|
|
505
|
+
responseText: formatSlackIdentityDeniedMessage(),
|
|
506
|
+
};
|
|
507
|
+
}
|
|
368
508
|
if (!match) {
|
|
369
509
|
const routedIncoming = incoming;
|
|
370
510
|
routedIncoming.routingHint ??= dispatchIntegrationRoutingHint(trimmed);
|
|
@@ -390,11 +530,13 @@ export async function beforeDispatchProcess(incoming, adapter) {
|
|
|
390
530
|
});
|
|
391
531
|
}
|
|
392
532
|
try {
|
|
533
|
+
const expectedOrgId = contextString(incoming.platformContext.managedInstallationOrgId);
|
|
393
534
|
const owner = await consumeLinkToken({
|
|
394
535
|
platform: incoming.platform,
|
|
395
536
|
token: match[1],
|
|
396
537
|
externalUserId: identityKeyForIncoming(incoming),
|
|
397
538
|
externalUserName: incoming.senderName || null,
|
|
539
|
+
...(expectedOrgId ? { expectedOrgId } : {}),
|
|
398
540
|
});
|
|
399
541
|
return {
|
|
400
542
|
handled: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatch-integrations.js","sourceRoot":"","sources":["../../../src/server/lib/dispatch-integrations.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EACL,8BAA8B,EAC9B,qCAAqC,EACrC,mBAAmB,EACnB,6BAA6B,EAC7B,+BAA+B,EAC/B,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAOtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACL,8BAA8B,GAE/B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAQ3E,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAG9B,CAAC;AACJ,MAAM,uBAAuB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE/C,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,KAAK,CAAC,IAAI,EAAE,CAAC;I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YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,8BAA8B;SAC1E,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import crypto from \"node:crypto\";\n\nimport {\n evaluateIntegrationScopePolicy,\n getActiveIntegrationInstallationByKey,\n getIntegrationScope,\n resolveIntegrationTokenBundle,\n resolveSlackBotTokenForIncoming,\n saveIntegrationScope,\n slackInstallationKey,\n} from \"@agent-native/core/integrations\";\nimport { resolveOrgIdForEmail } from \"@agent-native/core/org\";\nimport { withConfiguredAppBasePath } from \"@agent-native/core/server\";\nimport type {\n IncomingMessage,\n IntegrationExecutionContext,\n PlatformAdapter,\n} from \"@agent-native/core/server\";\n\nimport { handleRemoteCodeCommand } from \"./dispatch-remote-commands.js\";\nimport {\n dispatchIntegrationRoutingHint,\n type DispatchIntegrationRoutingHint,\n} from \"./dispatch-routing.js\";\nimport { consumeLinkToken, resolveLinkedOwner } from \"./dispatch-store.js\";\n\ntype SlackSenderProfile = {\n email: string | null;\n name: string | null;\n trust: \"trusted\" | \"guest\" | \"external_shared\" | \"unknown\";\n};\n\nconst slackProfileCache = new Map<\n string,\n { profile: SlackSenderProfile; expiresAt: number }\n>();\nconst SLACK_PROFILE_CACHE_TTL = 10 * 60 * 1000;\n\nfunction contextString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim()) return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\nexport function identityKeyForIncoming(\n incoming: IncomingMessage,\n): string | null {\n const senderId = contextString(incoming.senderId);\n if (!senderId) return null;\n\n if (incoming.platform === \"slack\") {\n const teamId = contextString(incoming.platformContext.teamId);\n return teamId ? `${teamId}:${senderId}` : senderId;\n }\n\n if (incoming.platform === \"whatsapp\") {\n const phoneNumberId = contextString(incoming.platformContext.phoneNumberId);\n return phoneNumberId ? `${phoneNumberId}:${senderId}` : senderId;\n }\n\n if (incoming.platform === \"email\") {\n return senderId.toLowerCase();\n }\n\n return senderId;\n}\n\nfunction fallbackOwnerForIncoming(incoming: IncomingMessage): string {\n const tenant =\n contextString(incoming.platformContext.teamId) ||\n contextString(incoming.platformContext.phoneNumberId) ||\n contextString(incoming.platformContext.chatId) ||\n contextString(incoming.platformContext.from) ||\n incoming.externalThreadId;\n const raw = `${incoming.platform}:${tenant}:${incoming.senderId || \"\"}`;\n const hash = crypto\n .createHash(\"sha256\")\n .update(raw)\n .digest(\"hex\")\n .slice(0, 16);\n return `dispatch+${hash}@integration.local`;\n}\n\nfunction configuredDefaultOwnerForIncoming(\n incoming: IncomingMessage,\n): string | null {\n // This is intentionally Slack-only: a deployment-wide default owner grants\n // that Slack workspace access to the owner's connected agents and org\n // credentials, so other platforms should opt in with explicit identity links.\n if (incoming.platform !== \"slack\") return null;\n const email = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (!email) return null;\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : null;\n}\n\nfunction platformRequiresExplicitLink(incoming: IncomingMessage): boolean {\n // Telegram does not provide a verified email address. Require an explicit\n // identity link before it can act as a Builder/Agent-Native user.\n return incoming.platform === \"telegram\";\n}\n\nfunction configuredDispatchIdentitiesUrl(): string | null {\n const raw =\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n \"\";\n if (!raw.trim()) return null;\n const base = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n try {\n return new URL(\n \"identities\",\n `${withConfiguredAppBasePath(base).replace(/\\/+$/, \"\")}/`,\n ).toString();\n } catch {\n return null;\n }\n}\n\nasync function resolveManagedSlackInstallation(incoming: IncomingMessage) {\n if (incoming.platform !== \"slack\") return null;\n const teamId = contextString(incoming.platformContext.teamId);\n const apiAppId = contextString(incoming.platformContext.apiAppId);\n if (!teamId) return null;\n try {\n return await getActiveIntegrationInstallationByKey(\n \"slack\",\n slackInstallationKey({ teamId, apiAppId }),\n );\n } catch {\n return null;\n }\n}\n\nasync function resolveManagedSlackToken(\n incoming: IncomingMessage,\n): Promise<string | null> {\n const installation = await resolveManagedSlackInstallation(incoming);\n if (!installation) return null;\n const bundle = await resolveIntegrationTokenBundle(\n \"slack\",\n installation.installationKey,\n );\n return bundle?.accessToken ?? null;\n}\n\nfunction formatTelegramLinkRequiredMessage(): string {\n const identitiesUrl = configuredDispatchIdentitiesUrl();\n const linkStep = identitiesUrl\n ? `Tap ${identitiesUrl}, create a Telegram link token, then send \\`/link <token>\\` here.`\n : \"Open Dispatch while signed in, create a Telegram link token, then send `/link <token>` here.\";\n return `Telegram is connected, but this Telegram account is not linked to an Agent-Native user yet. ${linkStep} After that I can use your Builder.io org and connected apps.`;\n}\n\nfunction formatSlackLinkRequiredMessage(): string {\n const identitiesUrl = configuredDispatchIdentitiesUrl();\n const linkStep = identitiesUrl\n ? `Open ${identitiesUrl}, create a Slack link token, then send \\`/link <token>\\` in this DM.`\n : \"Open Dispatch while signed in, create a Slack link token, then send `/link <token>` in this DM.\";\n return `Agent Native is ready, but this Slack account is not linked to an Agent Native user yet. ${linkStep}`;\n}\n\nasync function resolveSlackSenderProfile(\n incoming: IncomingMessage,\n): Promise<SlackSenderProfile> {\n if (incoming.platform !== \"slack\") {\n return { email: null, name: null, trust: \"unknown\" };\n }\n const token = await resolveSlackBotTokenForIncoming(incoming);\n const userId = contextString(incoming.senderId);\n const teamId = contextString(incoming.platformContext.teamId);\n if (!token || !userId) {\n return { email: null, name: null, trust: \"unknown\" };\n }\n\n // Slack user IDs are scoped per workspace, so without a teamId we can't\n // safely cache: two installs of the bot in different workspaces could\n // share user-id strings and collide on a single \"default\" key. Skip the\n // cache (and lookup on every request) when teamId is missing.\n const cacheKey = teamId ? `${teamId}:${userId}` : null;\n if (cacheKey) {\n const cached = slackProfileCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) return cached.profile;\n }\n\n try {\n const params = new URLSearchParams({ user: userId });\n const res = await fetch(`https://slack.com/api/users.info?${params}`, {\n headers: { Authorization: `Bearer ${token}` },\n });\n const data = (await res.json()) as {\n ok?: boolean;\n user?: {\n real_name?: string;\n name?: string;\n profile?: {\n email?: string;\n real_name?: string;\n display_name?: string;\n };\n is_restricted?: boolean;\n is_ultra_restricted?: boolean;\n };\n };\n const profile = data.ok\n ? {\n email: data.user?.profile?.email?.trim().toLowerCase() || null,\n name:\n data.user?.profile?.real_name?.trim() ||\n data.user?.profile?.display_name?.trim() ||\n data.user?.real_name?.trim() ||\n data.user?.name?.trim() ||\n null,\n trust:\n data.user?.is_ultra_restricted === true\n ? (\"external_shared\" as const)\n : data.user?.is_restricted === true\n ? (\"guest\" as const)\n : (\"trusted\" as const),\n }\n : { email: null, name: null, trust: \"unknown\" as const };\n if (cacheKey) {\n slackProfileCache.set(cacheKey, {\n profile,\n expiresAt: Date.now() + SLACK_PROFILE_CACHE_TTL,\n });\n }\n return profile;\n } catch {\n return { email: null, name: null, trust: \"unknown\" };\n }\n}\n\nasync function resolveSlackOwnerFromVerifiedEmail(\n incoming: IncomingMessage,\n): Promise<string | null> {\n const profile = await resolveSlackSenderProfile(incoming);\n if (!profile.email) return null;\n\n incoming.senderEmail = profile.email;\n incoming.platformContext.senderEmail = profile.email;\n if (profile.name) {\n incoming.senderName = profile.name;\n incoming.platformContext.senderName = profile.name;\n }\n\n const orgId = await resolveOrgIdForEmail(profile.email);\n return orgId ? profile.email : null;\n}\n\nasync function resolveSlackConversationTrust(\n incoming: IncomingMessage,\n actorTrust: SlackSenderProfile[\"trust\"],\n): Promise<{\n trust: SlackSenderProfile[\"trust\"];\n conversationType: \"channel\" | \"direct_message\" | \"group_direct_message\";\n}> {\n if (incoming.triggerKind === \"dm\") {\n return { trust: actorTrust, conversationType: \"direct_message\" };\n }\n const token = await resolveManagedSlackToken(incoming);\n const channel = contextString(incoming.platformContext.channelId);\n if (!token || !channel) {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n try {\n const params = new URLSearchParams({ channel });\n const response = await fetch(\n `https://slack.com/api/conversations.info?${params}`,\n { headers: { Authorization: `Bearer ${token}` } },\n );\n const data = (await response.json()) as {\n ok?: boolean;\n channel?: {\n is_ext_shared?: boolean;\n is_im?: boolean;\n is_mpim?: boolean;\n };\n };\n if (!data.ok) {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n return {\n trust: data.channel?.is_ext_shared ? \"external_shared\" : actorTrust,\n conversationType: data.channel?.is_im\n ? \"direct_message\"\n : data.channel?.is_mpim\n ? \"group_direct_message\"\n : \"channel\",\n };\n } catch {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n}\n\nexport async function resolveDispatchOwner(\n incoming: IncomingMessage,\n): Promise<string> {\n try {\n const externalUserId = identityKeyForIncoming(incoming);\n\n // Webhooks do not have the browser request's org context, so allow a safe\n // cross-org fallback when the linked platform identity maps to one owner.\n const owner = await resolveLinkedOwner(incoming.platform, externalUserId, {\n allowAnyOrgFallback: true,\n });\n if (owner) return owner;\n\n // For email, the sender's `From:` address is attacker-settable: SMTP lets\n // anyone claim any From, and our inbound webhook secret only authenticates\n // the provider→app hop, not the original sender. So we must NOT grant a\n // real user's identity (their API keys, org secrets, personal\n // instructions, ownable data) off the bare From. Mirror the Slack gate:\n // only return the sender email as the acting owner when BOTH\n // (a) the message is DKIM/SPF-verified for the From domain, AND\n // (b) that email maps to a real org member.\n // Otherwise fall through to the synthetic, credential-less fallback owner.\n // (A linked identity, handled by resolveLinkedOwner above, remains an\n // always-allowed way to bind an address regardless of verification.)\n //\n // Escape hatch: set DISPATCH_TRUST_UNVERIFIED_EMAIL_SENDER=1 to restore\n // the legacy \"trust the From header\" behavior. OFF by default; only use\n // this if you fully control the inbound mail path and accept that a\n // spoofed From can act as any org member. See FINDING 3 (inbound-email\n // impersonation) in the webhook security audit.\n if (\n incoming.platform === \"email\" &&\n incoming.senderId &&\n incoming.senderId.includes(\"@\")\n ) {\n if (process.env.DISPATCH_TRUST_UNVERIFIED_EMAIL_SENDER === \"1\") {\n return incoming.senderId;\n }\n if (incoming.senderVerified) {\n const orgId = await resolveOrgIdForEmail(incoming.senderId);\n if (orgId) return incoming.senderId;\n }\n // Unverified or not an org member — do not impersonate. Fall through to\n // the synthetic fallback owner below.\n }\n\n // Slack gives us a user id in the event payload. Resolve it to a verified\n // workspace email and use that user's own org context when they are an\n // Agent-Native member, so artifacts created via @agent-native are visible\n // when they open the target app.\n if (incoming.platform === \"slack\") {\n const slackOwner = await resolveSlackOwnerFromVerifiedEmail(incoming);\n if (slackOwner) return slackOwner;\n }\n\n const defaultOwner = configuredDefaultOwnerForIncoming(incoming);\n if (defaultOwner) return defaultOwner;\n\n return fallbackOwnerForIncoming(incoming);\n } catch {\n const defaultOwner = configuredDefaultOwnerForIncoming(incoming);\n if (defaultOwner) return defaultOwner;\n return fallbackOwnerForIncoming(incoming);\n }\n}\n\n/**\n * Resolve a personal DM user or a workspace-qualified channel service\n * principal. Managed Slack channels never silently inherit one requester's\n * personal credentials or memory.\n */\nexport async function resolveDispatchExecutionContext(\n incoming: IncomingMessage,\n): Promise<IntegrationExecutionContext> {\n if (incoming.platform !== \"slack\" || incoming.triggerKind === \"dm\") {\n const ownerEmail = await resolveDispatchOwner(incoming);\n if (\n incoming.platform === \"slack\" &&\n ownerEmail.endsWith(\"@integration.local\")\n ) {\n // Preserve a credential-less principal long enough for beforeProcess to\n // deliver linking guidance or consume `/link <token>`. Never run the\n // agent under this synthetic owner.\n incoming.platformContext.identityLinkRequired = true;\n }\n return {\n ownerEmail,\n orgId: (await resolveOrgIdForEmail(ownerEmail)) ?? null,\n principalType: \"user\",\n };\n }\n\n const installation = await resolveManagedSlackInstallation(incoming);\n if (!installation) {\n // Preserve the legacy manually configured app path while managed installs\n // roll out. Its behavior remains explicit and visible in Settings.\n const ownerEmail = await resolveDispatchOwner(incoming);\n return {\n ownerEmail,\n orgId: (await resolveOrgIdForEmail(ownerEmail)) ?? null,\n principalType: \"user\",\n };\n }\n\n const teamId = contextString(incoming.platformContext.teamId);\n const channelId = contextString(incoming.platformContext.channelId);\n if (!teamId || !channelId) {\n throw new Error(\"Slack channel identity is incomplete\");\n }\n const profile = await resolveSlackSenderProfile(incoming);\n const conversation = await resolveSlackConversationTrust(\n incoming,\n profile.trust,\n );\n const access = {\n ownerEmail: installation.ownerEmail,\n orgId: installation.orgId,\n };\n const key = {\n platform: \"slack\",\n tenantId: teamId,\n conversationId: channelId,\n };\n let scope = await getIntegrationScope(key, access);\n if (!scope && incoming.triggerKind === \"mention\") {\n scope = await saveIntegrationScope(\n {\n ...key,\n conversationType: conversation.conversationType,\n trust: conversation.trust,\n orgId: installation.orgId,\n installationId: installation.id,\n },\n access,\n );\n }\n if (!scope) throw new Error(\"Slack channel is not enabled for Agent Native\");\n const decision = evaluateIntegrationScopePolicy(scope, {\n // Slack channel turns only arrive here after an explicit current-message\n // mention; keep the generic thread_reply trigger for other adapters.\n mentioned:\n incoming.triggerKind === \"mention\" ||\n incoming.triggerKind === \"thread_reply\",\n });\n if (!decision.allowed) {\n throw new Error(`Slack channel policy denied: ${decision.reason}`);\n }\n incoming.integrationScopeId = scope.id;\n if (scope.defaultModel) {\n incoming.platformContext.defaultModel = scope.defaultModel;\n }\n incoming.actorTrust = {\n memberType:\n conversation.trust === \"guest\"\n ? \"guest\"\n : conversation.trust === \"external_shared\"\n ? \"external\"\n : conversation.trust === \"trusted\"\n ? \"member\"\n : \"unknown\",\n verified: conversation.trust !== \"unknown\",\n };\n return {\n ownerEmail: scope.serviceOwnerEmail,\n orgId: scope.orgId,\n principalType: \"service\",\n installationId: installation.id,\n scopeId: scope.id,\n };\n}\n\nexport async function beforeDispatchProcess(\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n): Promise<{ handled: true; responseText?: string } | { handled: false }> {\n const trimmed = incoming.text.trim();\n const commandText =\n contextString(incoming.platformContext.rawText) || trimmed;\n const match = commandText.match(/^\\/link(?:@\\w+)?\\s+([a-zA-Z0-9_-]+)$/);\n if (!match) {\n const routedIncoming = incoming as IncomingMessage & {\n routingHint?: DispatchIntegrationRoutingHint;\n };\n routedIncoming.routingHint ??= dispatchIntegrationRoutingHint(trimmed);\n if (\n incoming.platform === \"slack\" &&\n incoming.triggerKind === \"dm\" &&\n incoming.platformContext.identityLinkRequired === true\n ) {\n return {\n handled: true,\n responseText: formatSlackLinkRequiredMessage(),\n };\n }\n if (platformRequiresExplicitLink(incoming)) {\n const owner = await resolveLinkedOwner(\n incoming.platform,\n identityKeyForIncoming(incoming),\n { allowAnyOrgFallback: true },\n );\n if (!owner) {\n return {\n handled: true,\n responseText: formatTelegramLinkRequiredMessage(),\n };\n }\n }\n return handleRemoteCodeCommand(incoming, adapter, {\n resolveOwner: () => resolveDispatchOwner(incoming),\n });\n }\n\n try {\n const owner = await consumeLinkToken({\n platform: incoming.platform,\n token: match[1],\n externalUserId: identityKeyForIncoming(incoming),\n externalUserName: incoming.senderName || null,\n });\n return {\n handled: true,\n responseText: `Linked successfully. Future ${incoming.platform} messages will use ${owner}'s personal dispatch context.`,\n };\n } catch (error) {\n return {\n handled: true,\n responseText:\n error instanceof Error ? error.message : \"Failed to link this account.\",\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dispatch-integrations.js","sourceRoot":"","sources":["../../../src/server/lib/dispatch-integrations.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EACL,8BAA8B,EAC9B,qCAAqC,EACrC,mBAAmB,EACnB,6BAA6B,EAC7B,+BAA+B,EAC/B,oBAAoB,EACpB,oBAAoB,GACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAOtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACL,8BAA8B,GAE/B,MAAM,uBAAuB,CAAC;AAC/B,O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eAAe,CAAC,wBAAwB,CAClD,CAAC;QACF,MAAM,KAAK,GAAG,MAAM,gBAAgB,CAAC;YACnC,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;YACf,cAAc,EAAE,sBAAsB,CAAC,QAAQ,CAAC;YAChD,gBAAgB,EAAE,QAAQ,CAAC,UAAU,IAAI,IAAI;YAC7C,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC5C,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,IAAI;YACb,YAAY,EAAE,+BAA+B,QAAQ,CAAC,QAAQ,sBAAsB,KAAK,+BAA+B;SACzH,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO;YACL,OAAO,EAAE,IAAI;YACb,YAAY,EACV,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,8BAA8B;SAC1E,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import crypto from \"node:crypto\";\n\nimport {\n evaluateIntegrationScopePolicy,\n getActiveIntegrationInstallationByKey,\n getIntegrationScope,\n resolveIntegrationTokenBundle,\n resolveSlackBotTokenForIncoming,\n saveIntegrationScope,\n slackInstallationKey,\n} from \"@agent-native/core/integrations\";\nimport { isOrgMember, resolveOrgIdForEmail } from \"@agent-native/core/org\";\nimport { withConfiguredAppBasePath } from \"@agent-native/core/server\";\nimport type {\n IncomingMessage,\n IntegrationExecutionContext,\n PlatformAdapter,\n} from \"@agent-native/core/server\";\n\nimport { handleRemoteCodeCommand } from \"./dispatch-remote-commands.js\";\nimport {\n dispatchIntegrationRoutingHint,\n type DispatchIntegrationRoutingHint,\n} from \"./dispatch-routing.js\";\nimport { consumeLinkToken, resolveLinkedOwner } from \"./dispatch-store.js\";\n\ntype SlackSenderProfile = {\n email: string | null;\n name: string | null;\n trust: \"trusted\" | \"guest\" | \"external_shared\" | \"unknown\";\n};\n\nconst slackProfileCache = new Map<\n string,\n { profile: SlackSenderProfile; expiresAt: number }\n>();\nconst SLACK_PROFILE_CACHE_TTL = 10 * 60 * 1000;\n\nfunction contextString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim()) return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\nexport function identityKeyForIncoming(\n incoming: IncomingMessage,\n): string | null {\n const senderId = contextString(incoming.senderId);\n if (!senderId) return null;\n\n if (incoming.platform === \"slack\") {\n const teamId = contextString(incoming.platformContext.teamId);\n return teamId ? `${teamId}:${senderId}` : senderId;\n }\n\n if (incoming.platform === \"whatsapp\") {\n const phoneNumberId = contextString(incoming.platformContext.phoneNumberId);\n return phoneNumberId ? `${phoneNumberId}:${senderId}` : senderId;\n }\n\n if (incoming.platform === \"email\") {\n return senderId.toLowerCase();\n }\n\n return senderId;\n}\n\nfunction fallbackOwnerForIncoming(incoming: IncomingMessage): string {\n const tenant =\n contextString(incoming.platformContext.teamId) ||\n contextString(incoming.platformContext.phoneNumberId) ||\n contextString(incoming.platformContext.chatId) ||\n contextString(incoming.platformContext.from) ||\n incoming.externalThreadId;\n const raw = `${incoming.platform}:${tenant}:${incoming.senderId || \"\"}`;\n const hash = crypto\n .createHash(\"sha256\")\n .update(raw)\n .digest(\"hex\")\n .slice(0, 16);\n return `dispatch+${hash}@integration.local`;\n}\n\nfunction configuredDefaultOwnerForIncoming(\n incoming: IncomingMessage,\n): string | null {\n // This is intentionally Slack-only: a deployment-wide default owner grants\n // that Slack workspace access to the owner's connected agents and org\n // credentials, so other platforms should opt in with explicit identity links.\n if (incoming.platform !== \"slack\") return null;\n const email = process.env.DISPATCH_DEFAULT_OWNER_EMAIL?.trim();\n if (!email) return null;\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : null;\n}\n\nfunction platformRequiresExplicitLink(incoming: IncomingMessage): boolean {\n // Telegram does not provide a verified email address. Require an explicit\n // identity link before it can act as a Builder/Agent-Native user.\n return incoming.platform === \"telegram\";\n}\n\nfunction configuredDispatchIdentitiesUrl(): string | null {\n const raw =\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n \"\";\n if (!raw.trim()) return null;\n const base = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n try {\n return new URL(\n \"identities\",\n `${withConfiguredAppBasePath(base).replace(/\\/+$/, \"\")}/`,\n ).toString();\n } catch {\n return null;\n }\n}\n\nasync function resolveManagedSlackInstallation(incoming: IncomingMessage) {\n if (incoming.platform !== \"slack\") return null;\n const teamId = contextString(incoming.platformContext.teamId);\n const enterpriseId = contextString(incoming.platformContext.enterpriseId);\n const apiAppId = contextString(incoming.platformContext.apiAppId);\n const isEnterpriseInstall =\n incoming.platformContext.isEnterpriseInstall === true;\n if ((!teamId && !enterpriseId) || (isEnterpriseInstall && !enterpriseId))\n return null;\n return getActiveIntegrationInstallationByKey(\n \"slack\",\n slackInstallationKey({\n teamId,\n enterpriseId,\n apiAppId,\n isEnterpriseInstall,\n }),\n );\n}\n\nclass ManagedSlackInstallationLookupError extends Error {\n constructor(options?: ErrorOptions) {\n super(\n \"Managed Slack installation identity is temporarily unavailable\",\n options,\n );\n this.name = \"ManagedSlackInstallationLookupError\";\n }\n}\n\nasync function resolveManagedSlackInstallationOrFail(\n incoming: IncomingMessage,\n) {\n try {\n return await resolveManagedSlackInstallation(incoming);\n } catch (cause) {\n throw new ManagedSlackInstallationLookupError({ cause });\n }\n}\n\nasync function resolveManagedSlackToken(\n incoming: IncomingMessage,\n): Promise<string | null> {\n const installation = await resolveManagedSlackInstallation(incoming);\n if (!installation) return null;\n const bundle = await resolveIntegrationTokenBundle(\n \"slack\",\n installation.installationKey,\n );\n return bundle?.accessToken ?? null;\n}\n\nfunction formatTelegramLinkRequiredMessage(): string {\n const identitiesUrl = configuredDispatchIdentitiesUrl();\n const linkStep = identitiesUrl\n ? `Tap ${identitiesUrl}, create a Telegram link token, then send \\`/link <token>\\` here.`\n : \"Open Dispatch while signed in, create a Telegram link token, then send `/link <token>` here.\";\n return `Telegram is connected, but this Telegram account is not linked to an Agent-Native user yet. ${linkStep} After that I can use your Builder.io org and connected apps.`;\n}\n\nfunction formatSlackLinkRequiredMessage(): string {\n const identitiesUrl = configuredDispatchIdentitiesUrl();\n const linkStep = identitiesUrl\n ? `Open ${identitiesUrl}, create a Slack link token, then send \\`/link <token>\\` in this DM.`\n : \"Open Dispatch while signed in, create a Slack link token, then send `/link <token>` in this DM.\";\n return `Agent Native is ready, but this Slack account is not linked to an Agent Native user yet. ${linkStep}`;\n}\n\nfunction formatSlackIdentityVerificationFailedMessage(): string {\n return \"I couldn't verify your Slack identity just now, so I can't run this request. Please try again in a moment.\";\n}\n\nfunction formatSlackIdentityDeniedMessage(): string {\n return \"This assistant is only available to members of this workspace's organization.\";\n}\n\nasync function resolveSlackSenderProfile(\n incoming: IncomingMessage,\n): Promise<SlackSenderProfile> {\n if (incoming.platform !== \"slack\") {\n return { email: null, name: null, trust: \"unknown\" };\n }\n const token = await resolveSlackBotTokenForIncoming(incoming);\n const userId = contextString(incoming.senderId);\n const teamId = contextString(incoming.platformContext.teamId);\n if (!token || !userId) {\n return { email: null, name: null, trust: \"unknown\" };\n }\n\n // Slack user IDs are scoped per workspace, so without a teamId we can't\n // safely cache: two installs of the bot in different workspaces could\n // share user-id strings and collide on a single \"default\" key. Skip the\n // cache (and lookup on every request) when teamId is missing.\n const cacheKey = teamId ? `${teamId}:${userId}` : null;\n if (cacheKey) {\n const cached = slackProfileCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) return cached.profile;\n }\n\n try {\n const params = new URLSearchParams({ user: userId });\n const res = await fetch(`https://slack.com/api/users.info?${params}`, {\n headers: { Authorization: `Bearer ${token}` },\n });\n const data = (await res.json()) as {\n ok?: boolean;\n user?: {\n real_name?: string;\n name?: string;\n profile?: {\n email?: string;\n real_name?: string;\n display_name?: string;\n };\n is_restricted?: boolean;\n is_ultra_restricted?: boolean;\n is_stranger?: boolean;\n };\n };\n const profile = data.ok\n ? {\n email: data.user?.profile?.email?.trim().toLowerCase() || null,\n name:\n data.user?.profile?.real_name?.trim() ||\n data.user?.profile?.display_name?.trim() ||\n data.user?.real_name?.trim() ||\n data.user?.name?.trim() ||\n null,\n trust:\n data.user?.is_stranger === true ||\n data.user?.is_ultra_restricted === true\n ? (\"external_shared\" as const)\n : data.user?.is_restricted === true\n ? (\"guest\" as const)\n : (\"trusted\" as const),\n }\n : { email: null, name: null, trust: \"unknown\" as const };\n if (cacheKey) {\n slackProfileCache.set(cacheKey, {\n profile,\n expiresAt: Date.now() + SLACK_PROFILE_CACHE_TTL,\n });\n }\n return profile;\n } catch {\n return { email: null, name: null, trust: \"unknown\" };\n }\n}\n\nasync function resolveSlackOwnerFromVerifiedEmail(\n incoming: IncomingMessage,\n): Promise<string | null> {\n const profile = await resolveSlackSenderProfile(incoming);\n if (!profile.email) return null;\n\n incoming.senderEmail = profile.email;\n incoming.platformContext.senderEmail = profile.email;\n if (profile.name) {\n incoming.senderName = profile.name;\n incoming.platformContext.senderName = profile.name;\n }\n\n const orgId = await resolveOrgIdForEmail(profile.email);\n return orgId ? profile.email : null;\n}\n\nasync function resolveManagedSlackDmExecutionContext(\n incoming: IncomingMessage,\n installation: NonNullable<\n Awaited<ReturnType<typeof resolveManagedSlackInstallation>>\n >,\n): Promise<IntegrationExecutionContext> {\n const profile = await resolveSlackSenderProfile(incoming);\n incoming.actorTrust = {\n memberType:\n profile.trust === \"guest\"\n ? \"guest\"\n : profile.trust === \"external_shared\"\n ? \"external\"\n : profile.trust === \"trusted\"\n ? \"member\"\n : \"unknown\",\n verified: profile.trust !== \"unknown\",\n };\n incoming.senderVerified = profile.email !== null;\n if (profile.email) {\n incoming.senderEmail = profile.email;\n incoming.platformContext.senderEmail = profile.email;\n }\n if (profile.name) {\n incoming.senderName = profile.name;\n incoming.platformContext.senderName = profile.name;\n }\n\n const deniedContext = (): IntegrationExecutionContext => ({\n ownerEmail: fallbackOwnerForIncoming(incoming),\n orgId: null,\n principalType: \"user\",\n installationId: installation.id,\n });\n\n if (profile.trust === \"unknown\") {\n incoming.platformContext.identityVerificationFailed = true;\n return deniedContext();\n }\n if (profile.trust === \"guest\" || profile.trust === \"external_shared\") {\n incoming.platformContext.identityAccessDenied = true;\n return deniedContext();\n }\n if (!installation.orgId) {\n incoming.platformContext.identityLinkRequired = true;\n return deniedContext();\n }\n incoming.platformContext.managedInstallationOrgId = installation.orgId;\n\n let linkedOwner: string | null;\n try {\n linkedOwner = await resolveLinkedOwner(\n \"slack\",\n identityKeyForIncoming(incoming),\n { orgId: installation.orgId },\n );\n } catch {\n incoming.platformContext.identityVerificationFailed = true;\n return deniedContext();\n }\n const candidates = [profile.email, linkedOwner].filter(\n (email, index, values): email is string =>\n !!email && values.indexOf(email) === index,\n );\n for (const ownerEmail of candidates) {\n try {\n if (await isOrgMember(installation.orgId, ownerEmail)) {\n return {\n ownerEmail,\n orgId: installation.orgId,\n principalType: \"user\",\n installationId: installation.id,\n };\n }\n } catch {\n incoming.platformContext.identityVerificationFailed = true;\n return deniedContext();\n }\n }\n\n incoming.platformContext.identityLinkRequired = true;\n return deniedContext();\n}\n\nasync function resolveSlackConversationTrust(\n incoming: IncomingMessage,\n actorTrust: SlackSenderProfile[\"trust\"],\n): Promise<{\n trust: SlackSenderProfile[\"trust\"];\n conversationType: \"channel\" | \"direct_message\" | \"group_direct_message\";\n}> {\n if (incoming.triggerKind === \"dm\") {\n return { trust: actorTrust, conversationType: \"direct_message\" };\n }\n const token = await resolveManagedSlackToken(incoming);\n const channel = contextString(incoming.platformContext.channelId);\n if (!token || !channel) {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n try {\n const params = new URLSearchParams({ channel });\n const response = await fetch(\n `https://slack.com/api/conversations.info?${params}`,\n { headers: { Authorization: `Bearer ${token}` } },\n );\n const data = (await response.json()) as {\n ok?: boolean;\n channel?: {\n is_ext_shared?: boolean;\n is_im?: boolean;\n is_mpim?: boolean;\n };\n };\n if (!data.ok) {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n return {\n trust: data.channel?.is_ext_shared ? \"external_shared\" : actorTrust,\n conversationType: data.channel?.is_im\n ? \"direct_message\"\n : data.channel?.is_mpim\n ? \"group_direct_message\"\n : \"channel\",\n };\n } catch {\n return { trust: \"unknown\", conversationType: \"channel\" };\n }\n}\n\nexport async function resolveDispatchOwner(\n incoming: IncomingMessage,\n): Promise<string> {\n try {\n const externalUserId = identityKeyForIncoming(incoming);\n\n // Webhooks do not have the browser request's org context, so allow a safe\n // cross-org fallback when the linked platform identity maps to one owner.\n const owner = await resolveLinkedOwner(incoming.platform, externalUserId, {\n allowAnyOrgFallback: true,\n });\n if (owner) return owner;\n\n // For email, the sender's `From:` address is attacker-settable: SMTP lets\n // anyone claim any From, and our inbound webhook secret only authenticates\n // the provider→app hop, not the original sender. So we must NOT grant a\n // real user's identity (their API keys, org secrets, personal\n // instructions, ownable data) off the bare From. Mirror the Slack gate:\n // only return the sender email as the acting owner when BOTH\n // (a) the message is DKIM/SPF-verified for the From domain, AND\n // (b) that email maps to a real org member.\n // Otherwise fall through to the synthetic, credential-less fallback owner.\n // (A linked identity, handled by resolveLinkedOwner above, remains an\n // always-allowed way to bind an address regardless of verification.)\n //\n // Escape hatch: set DISPATCH_TRUST_UNVERIFIED_EMAIL_SENDER=1 to restore\n // the legacy \"trust the From header\" behavior. OFF by default; only use\n // this if you fully control the inbound mail path and accept that a\n // spoofed From can act as any org member. See FINDING 3 (inbound-email\n // impersonation) in the webhook security audit.\n if (\n incoming.platform === \"email\" &&\n incoming.senderId &&\n incoming.senderId.includes(\"@\")\n ) {\n if (process.env.DISPATCH_TRUST_UNVERIFIED_EMAIL_SENDER === \"1\") {\n return incoming.senderId;\n }\n if (incoming.senderVerified) {\n const orgId = await resolveOrgIdForEmail(incoming.senderId);\n if (orgId) return incoming.senderId;\n }\n // Unverified or not an org member — do not impersonate. Fall through to\n // the synthetic fallback owner below.\n }\n\n // Slack gives us a user id in the event payload. Resolve it to a verified\n // workspace email and use that user's own org context when they are an\n // Agent-Native member, so artifacts created via @agent-native are visible\n // when they open the target app.\n if (incoming.platform === \"slack\") {\n const slackOwner = await resolveSlackOwnerFromVerifiedEmail(incoming);\n if (slackOwner) return slackOwner;\n }\n\n const defaultOwner = configuredDefaultOwnerForIncoming(incoming);\n if (defaultOwner) return defaultOwner;\n\n return fallbackOwnerForIncoming(incoming);\n } catch {\n const defaultOwner = configuredDefaultOwnerForIncoming(incoming);\n if (defaultOwner) return defaultOwner;\n return fallbackOwnerForIncoming(incoming);\n }\n}\n\n/**\n * Resolve a personal DM user or a workspace-qualified channel service\n * principal. Managed Slack channels never silently inherit one requester's\n * personal credentials or memory.\n */\nexport async function resolveDispatchExecutionContext(\n incoming: IncomingMessage,\n): Promise<IntegrationExecutionContext> {\n if (incoming.platform === \"slack\" && incoming.triggerKind === \"dm\") {\n let installation;\n try {\n installation = await resolveManagedSlackInstallationOrFail(incoming);\n } catch (error) {\n if (!(error instanceof ManagedSlackInstallationLookupError)) throw error;\n incoming.platformContext.identityVerificationFailed = true;\n return {\n ownerEmail: fallbackOwnerForIncoming(incoming),\n orgId: null,\n principalType: \"user\",\n };\n }\n if (installation) {\n return resolveManagedSlackDmExecutionContext(incoming, installation);\n }\n incoming.platformContext.identityVerificationFailed = true;\n return {\n ownerEmail: fallbackOwnerForIncoming(incoming),\n orgId: null,\n principalType: \"user\",\n };\n }\n\n if (incoming.platform !== \"slack\" || incoming.triggerKind === \"dm\") {\n const ownerEmail = await resolveDispatchOwner(incoming);\n if (\n incoming.platform === \"slack\" &&\n ownerEmail.endsWith(\"@integration.local\")\n ) {\n // Preserve a credential-less principal long enough for beforeProcess to\n // deliver linking guidance or consume `/link <token>`. Never run the\n // agent under this synthetic owner.\n incoming.platformContext.identityLinkRequired = true;\n }\n return {\n ownerEmail,\n orgId: (await resolveOrgIdForEmail(ownerEmail)) ?? null,\n principalType: \"user\",\n };\n }\n\n const installation = await resolveManagedSlackInstallationOrFail(incoming);\n if (!installation) {\n // Preserve the legacy manually configured app path while managed installs\n // roll out. Its behavior remains explicit and visible in Settings.\n const ownerEmail = await resolveDispatchOwner(incoming);\n return {\n ownerEmail,\n orgId: (await resolveOrgIdForEmail(ownerEmail)) ?? null,\n principalType: \"user\",\n };\n }\n\n const teamId = contextString(incoming.platformContext.teamId);\n const channelId = contextString(incoming.platformContext.channelId);\n if (!teamId || !channelId) {\n throw new Error(\"Slack channel identity is incomplete\");\n }\n const profile = await resolveSlackSenderProfile(incoming);\n const conversation = await resolveSlackConversationTrust(\n incoming,\n profile.trust,\n );\n const access = {\n ownerEmail: installation.ownerEmail,\n orgId: installation.orgId,\n };\n const key = {\n platform: \"slack\",\n tenantId: teamId,\n conversationId: channelId,\n };\n let scope = await getIntegrationScope(key, access);\n if (!scope && incoming.triggerKind === \"mention\") {\n scope = await saveIntegrationScope(\n {\n ...key,\n conversationType: conversation.conversationType,\n trust: conversation.trust,\n orgId: installation.orgId,\n installationId: installation.id,\n },\n access,\n );\n }\n if (!scope) throw new Error(\"Slack channel is not enabled for Agent Native\");\n const decision = evaluateIntegrationScopePolicy(scope, {\n // Slack channel turns only arrive here after an explicit current-message\n // mention; keep the generic thread_reply trigger for other adapters.\n mentioned:\n incoming.triggerKind === \"mention\" ||\n incoming.triggerKind === \"thread_reply\",\n });\n if (!decision.allowed) {\n throw new Error(`Slack channel policy denied: ${decision.reason}`);\n }\n incoming.integrationScopeId = scope.id;\n if (scope.defaultModel) {\n incoming.platformContext.defaultModel = scope.defaultModel;\n }\n incoming.actorTrust = {\n memberType:\n conversation.trust === \"guest\"\n ? \"guest\"\n : conversation.trust === \"external_shared\"\n ? \"external\"\n : conversation.trust === \"trusted\"\n ? \"member\"\n : \"unknown\",\n verified: conversation.trust !== \"unknown\",\n };\n return {\n ownerEmail: scope.serviceOwnerEmail,\n orgId: scope.orgId,\n principalType: \"service\",\n installationId: installation.id,\n scopeId: scope.id,\n };\n}\n\nexport async function beforeDispatchProcess(\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n): Promise<{ handled: true; responseText?: string } | { handled: false }> {\n const trimmed = incoming.text.trim();\n const commandText =\n contextString(incoming.platformContext.rawText) || trimmed;\n const match = commandText.match(/^\\/link(?:@\\w+)?\\s+([a-zA-Z0-9_-]+)$/);\n if (\n match &&\n incoming.platform === \"slack\" &&\n incoming.triggerKind === \"dm\" &&\n !contextString(incoming.platformContext.managedInstallationOrgId) &&\n incoming.platformContext.identityVerificationFailed !== true &&\n incoming.platformContext.identityAccessDenied !== true\n ) {\n await resolveDispatchExecutionContext(incoming);\n }\n if (\n incoming.platform === \"slack\" &&\n incoming.triggerKind === \"dm\" &&\n incoming.platformContext.identityVerificationFailed === true\n ) {\n return {\n handled: true,\n responseText: formatSlackIdentityVerificationFailedMessage(),\n };\n }\n if (\n incoming.platform === \"slack\" &&\n incoming.triggerKind === \"dm\" &&\n incoming.platformContext.identityAccessDenied === true\n ) {\n return {\n handled: true,\n responseText: formatSlackIdentityDeniedMessage(),\n };\n }\n if (!match) {\n const routedIncoming = incoming as IncomingMessage & {\n routingHint?: DispatchIntegrationRoutingHint;\n };\n routedIncoming.routingHint ??= dispatchIntegrationRoutingHint(trimmed);\n if (\n incoming.platform === \"slack\" &&\n incoming.triggerKind === \"dm\" &&\n incoming.platformContext.identityLinkRequired === true\n ) {\n return {\n handled: true,\n responseText: formatSlackLinkRequiredMessage(),\n };\n }\n if (platformRequiresExplicitLink(incoming)) {\n const owner = await resolveLinkedOwner(\n incoming.platform,\n identityKeyForIncoming(incoming),\n { allowAnyOrgFallback: true },\n );\n if (!owner) {\n return {\n handled: true,\n responseText: formatTelegramLinkRequiredMessage(),\n };\n }\n }\n return handleRemoteCodeCommand(incoming, adapter, {\n resolveOwner: () => resolveDispatchOwner(incoming),\n });\n }\n\n try {\n const expectedOrgId = contextString(\n incoming.platformContext.managedInstallationOrgId,\n );\n const owner = await consumeLinkToken({\n platform: incoming.platform,\n token: match[1],\n externalUserId: identityKeyForIncoming(incoming),\n externalUserName: incoming.senderName || null,\n ...(expectedOrgId ? { expectedOrgId } : {}),\n });\n return {\n handled: true,\n responseText: `Linked successfully. Future ${incoming.platform} messages will use ${owner}'s personal dispatch context.`,\n };\n } catch (error) {\n return {\n handled: true,\n responseText:\n error instanceof Error ? error.message : \"Failed to link this account.\",\n };\n }\n}\n"]}
|
|
@@ -286,6 +286,7 @@ export declare function consumeLinkToken(input: {
|
|
|
286
286
|
token: string;
|
|
287
287
|
externalUserId?: string | null;
|
|
288
288
|
externalUserName?: string | null;
|
|
289
|
+
expectedOrgId?: string;
|
|
289
290
|
}): Promise<string>;
|
|
290
291
|
export declare function listOverview(): Promise<{
|
|
291
292
|
counts: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatch-store.d.ts","sourceRoot":"","sources":["../../../src/server/lib/dispatch-store.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,qBAAqB,oBAAoB,CAAC;AAqFvD;;;;GAIG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;aAEf,YAAY,EAAE,MAAM;IADhD,QAAQ,CAAC,IAAI,uBAAuB;IACpC,YAA4B,YAAY,EAAE,MAAM,EAI/C;CACF;AAED,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,cAAc,EAAE,MAAM,EAAE,CAAC;CAC1B;AAED,MAAM,WAAW,wBAAwB;IACvC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAKD,wBAAg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AM,GAAG,IAAI,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,mBAoHA;AAED,wBAAsB,YAAY;;QAY5B,YAAY;QACZ,gBAAgB;QAEhB,gBAAgB;QAChB,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GASjB"}
|
|
@@ -643,6 +643,10 @@ export async function consumeLinkToken(input) {
|
|
|
643
643
|
recordLinkFailure(input.platform, input.externalUserId);
|
|
644
644
|
throw new Error("Link token has expired");
|
|
645
645
|
}
|
|
646
|
+
if (input.expectedOrgId && tokenRow.orgId !== input.expectedOrgId) {
|
|
647
|
+
recordLinkFailure(input.platform, input.externalUserId);
|
|
648
|
+
throw new Error("This link token belongs to a different organization. Create a token from this workspace and try again.");
|
|
649
|
+
}
|
|
646
650
|
const timestamp = now();
|
|
647
651
|
const [existing] = await db
|
|
648
652
|
.select()
|