Multiplayer agent harness for work.
Support provider-managed Slack installation and delivery (#1198)
Regan Bell98ffa809381d
diff --git a/README.md b/README.mdindex 0a4d8c517..f35fc680c 100644--- a/README.md+++ b/README.md@@ -246,3 +246,29 @@ upstream source history to merge.## LicenseExcept where otherwise noted, QM is available under the [MIT License](./LICENSE).++### Managed Slack installation++A hosting provider can set `QM_SLACK_SERVICE_URL` (HTTPS),+`QM_SLACK_SERVICE_TOKEN` (unique per deployment), and `QM_SLACK_APP_ID` on core.+Set `QM_SLACK_SERVICE_URL` on the admin/web service as well so its browser policy allows the installation form.+The admin Slack card then offers **Add to Slack** through that service. Core calls+`POST /install/start` with the deployment bearer credential and expects `{ "url":+"https://<service>/..." }`. The browser submits a POST form to that URL; the service must validate its Origin against the company URL. The service owns browser-bound OAuth state, Slack+signature verification, workspace ownership, and app credentials.++The portal forwards only `POST /v1/slack/managed/installation`, `DELETE` on that+same path, and `POST /v1/slack/managed/events` without a browser session. Core+requires the deployment bearer credential on each request. Installation takes+`botToken`, `appId`, `teamId`, `installId`, `installedAt` (epoch milliseconds), and+optional `teamName`. Repeat the same installation request until it returns 200+with `ready: true`; 202 means the encrypted token is saved but the runtime has+not started. Older installation generations and conflicting workspaces fail+closed. Deletion takes `installId` and only disables that generation.++Delivery takes `{ installId, body, retryNum?, retryReason? }`, where `body` is the+verified Slack event or decoded interaction payload. Core checks its workspace+and app before passing it to the existing Slack runtime and acknowledgment+machinery. There is no shared queue: unavailable core instances return failures,+and the hosting service must relay those failures to Slack. The service must+process lifecycle events and ignore revocations older than the installation.diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex efd85826c..c20d045f8 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -6147,6 +6147,7 @@>Create Slack app from manifest ↗</a></p>+ <button class="primary hidden" id="slack-installation-start">Add to Slack</button><p class="hint" id="slack-installation-state">Not configured.</p><div class="hidden" id="slack-token-editor"><label style="display: block; margin-bottom: 8px"@@ -10232,6 +10233,9 @@setStatus("st-slack-installation", r.data?.message || "Failed to load Slack status.", "err");return;}+ $("slack-installation-start").classList.toggle("hidden", !r.data.installAvailable);+ $("slack-installation-create").classList.toggle("hidden", !!r.data.installAvailable);+ $("slack-rotate").classList.toggle("hidden", !!r.data.installAvailable);if (r.data.createUrl) $("slack-installation-create").href = r.data.createUrl;$("slack-installation-state").textContent =r.data.source === "environment"@@ -10247,6 +10251,18 @@: "Not configured.";$("slack-installation-delete").disabled = !r.data.configured;}+ $("slack-installation-start").onclick = async () => {+ $("slack-installation-start").disabled = true;+ const r = await api("POST", "/api/slack-installation/start", {});+ $("slack-installation-start").disabled = false;+ if (r.ok && r.data.url) {+ const form = document.createElement("form");+ form.method = "POST";+ form.action = r.data.url;+ document.body.appendChild(form);+ form.submit();+ } else setStatus("st-slack-installation", "Could not start Slack installation. Please try again.", "err");+ };$("slack-installation-save").onclick = async () => {const botToken = $("slack-bot-token").value.trim();const appToken = $("slack-app-token").value.trim();diff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.tsindex 00528d796..446a42879 100644--- a/plugins/admin/src/index.ts+++ b/plugins/admin/src/index.ts@@ -42,7 +42,7 @@ const ADMIN_CSP = ["connect-src 'self'","frame-ancestors 'none'","base-uri 'none'",- "form-action 'self'",+ `form-action 'self'${process.env.QM_SLACK_SERVICE_URL ? ` ${new URL(process.env.QM_SLACK_SERVICE_URL).origin} https://slack.com` : ""}`,"object-src 'none'",].join("; ");@@ -288,7 +288,7 @@ const WRITES = new Map<string, string[]>([["skills", ["DELETE"]],["skill-packs", ["POST", "PATCH", "DELETE"]],["users", ["PUT", "POST"]],- ["slack-installation", ["PUT", "DELETE"]],+ ["slack-installation", ["POST", "PUT", "DELETE"]],["model-providers", ["PUT", "DELETE"]],["model-registry", ["POST", "PUT", "DELETE"]],["custom-providers", ["PUT", "DELETE"]],diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex bd515d9e0..b289cd237 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -1036,6 +1036,17 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return json(res, 400, { error: "bad_request", message: "illegal path" });}+ if (+ (pathname === "/v1/slack/managed/installation" && (method === "POST" || method === "DELETE")) ||+ (pathname === "/v1/slack/managed/events" && method === "POST")+ ) {+ return proxyToUpstream(req, res, { baseUrl: CORE, path: pathname, search: "" }, [+ "authorization",+ "content-type",+ "content-length",+ ]);+ }+if (method === "POST" && /^\/v1\/webhooks\/incoming\/[^/]+$/.test(pathname)) {return proxyToUpstream(req, res, { baseUrl: CORE, path: pathname, search: url.search }, FORWARD_WEBHOOK_HEADERS);}diff --git a/plugins/portal/test/slack-managed.test.ts b/plugins/portal/test/slack-managed.test.tsnew file mode 100644index 000000000..ec901059e--- /dev/null+++ b/plugins/portal/test/slack-managed.test.ts@@ -0,0 +1,69 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import test from "node:test";++const seen: Array<{+ path: string | undefined;+ authorization: string | undefined;+ cookie: string | undefined;+ body: string;+}> = [];+const core = createServer(async (req, res) => {+ let body = "";+ for await (const chunk of req) body += String(chunk);+ seen.push({ path: req.url, authorization: req.headers.authorization, cookie: req.headers.cookie, body });+ res.writeHead(202, { "content-type": "application/json" });+ res.end('{"ready":false}');+});+await new Promise<void>((resolve) => core.listen(0, "127.0.0.1", resolve));+process.env.PORTAL_PUBLIC_URL = "http://portal.test";+process.env.PORTAL_SESSION_SECRET = "managed-test-session-secret";+process.env.PORTAL_IDENTITY_SECRET = "managed-test-identity-secret";+process.env.CORE_SIGNING_SECRET = "managed-test-core-secret";+process.env.CORE_ORG_ID = "test";+process.env.CORE_API_URL = `http://127.0.0.1:${(core.address() as AddressInfo).port}`;+process.env.WEB_UI_UPSTREAM = process.env.CORE_API_URL;+process.env.ADMIN_UPSTREAM = process.env.CORE_API_URL;+const { server } = await import("../src/index.ts");+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+test.after(() => {+ server.close();+ core.close();+});++test("managed Slack forwards exact methods and paths with service auth but no browser identity", async () => {+ for (const [method, path] of [+ ["POST", "installation"],+ ["DELETE", "installation"],+ ["POST", "events"],+ ]) {+ const result = await fetch(`${base}/v1/slack/managed/${path}`, {+ method,+ headers: {+ authorization: "Bearer deployment-token",+ "content-type": "application/json",+ cookie: "portal_session=forged",+ },+ body: '{"installId":"one"}',+ });+ assert.equal(result.status, 202, `${method} ${path}`);+ assert.deepEqual(await result.json(), { ready: false });+ assert.deepEqual(seen.at(-1), {+ path: `/v1/slack/managed/${path}`,+ authorization: "Bearer deployment-token",+ cookie: undefined,+ body: '{"installId":"one"}',+ });+ }+ const count = seen.length;+ for (const [method, path] of [+ ["GET", "installation"],+ ["DELETE", "events"],+ ["POST", "events/extra"],+ ]) {+ assert.equal((await fetch(`${base}/v1/slack/managed/${path}`, { method })).status, 404);+ }+ assert.equal(seen.length, count);+});diff --git a/src/api/deps.ts b/src/api/deps.tsindex cb8e6d90d..cf5a50573 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -1,4 +1,5 @@import type { createSuggestedActivityService } from "../suggestions/activities.ts";+import type { ManagedSlack } from "../surfaces/slack-managed.ts";import type { BrokerSessionStore } from "../auth/broker-sessions.ts";import type { DirectFileUploads } from "../files/direct-file-upload.ts";import type { SandboxResources } from "../sandbox/sandbox-resources.ts";@@ -81,6 +82,7 @@ export interface ServerDeps {replayDedupe?: ReplayDedupe;brokerSessions?: BrokerSessionStore;connectorTokens?: ConnectorTokenStore;+ managedSlack?: ManagedSlack;slackInstallation?: SlackInstallationStore;slackInstallationFetch?: typeof fetch;slackInstallationSocketAppId?: SlackSocketAppIdReader;diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.tsindex 992f68efa..dcc64a3c8 100644--- a/src/api/routes/admin.ts+++ b/src/api/routes/admin.ts@@ -40,6 +40,8 @@ import {getSlackEmojiList,getSlackInstallation,putSlackInstallation,+ startSlackInstallation,+ managedSlackRequest,} from "./admin/slack-installation.ts";import { deleteModelProvider, getModelProviders, putModelProvider } from "./admin/model-providers.ts";import { deleteCustomProvider, getCustomProviders, putCustomProvider } from "./admin/custom-providers.ts";@@ -64,6 +66,10 @@ const timed =};const routes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "POST", path: "/v1/admin/slack-installation/start", auth: "either", handle: startSlackInstallation },+ { method: "POST", path: "/v1/slack/managed/installation", auth: "public", handle: managedSlackRequest },+ { method: "DELETE", path: "/v1/slack/managed/installation", auth: "public", handle: managedSlackRequest },+ { method: "POST", path: "/v1/slack/managed/events", auth: "public", handle: managedSlackRequest },{ method: "GET", path: "/v1/admin/slack-installation", auth: "either", handle: getSlackInstallation },{ method: "GET", path: "/v1/admin/slack-emoji", auth: "either", handle: getSlackEmojiList },{ method: "PUT", path: "/v1/admin/slack-installation", auth: "either", handle: putSlackInstallation },diff --git a/src/api/routes/admin/slack-installation.ts b/src/api/routes/admin/slack-installation.tsindex 97f26caa6..6271eb704 100644--- a/src/api/routes/admin/slack-installation.ts+++ b/src/api/routes/admin/slack-installation.ts@@ -36,6 +36,10 @@ export async function getSlackInstallation(ctx: ApiCtx): Promise<void> {});const branding = await resolveBranding(ctx.deps.config, scope, ctx.deps.brandingDefault);const createUrl = slackBotManifestCreationUrl(branding.selfLabel);+ if (ctx.deps.managedSlack) {+ const status = await ctx.deps.slackInstallation.status();+ return sendJson(ctx.res, 200, { ...status, source: "service", installAvailable: true });+ }const stored = await ctx.deps.slackInstallation.status();if (stored.managed) return sendJson(ctx.res, 200, { ...stored, source: "admin", createUrl });if (ctx.deps.slackEnvironmentState === "configured") {@@ -54,6 +58,7 @@ export async function putSlackInstallation(ctx: ApiCtx): Promise<void> {const actor = await authorizeAdmin(ctx, scope);if (!actor) return;if (!ctx.deps.slackInstallation) return sendJson(ctx.res, 404, { error: "not_configured" });+ if (ctx.deps.managedSlack) return sendJson(ctx.res, 409, { error: "use_managed_installation" });const body = ctx.body as { botToken?: unknown; appToken?: unknown };const botToken = typeof body.botToken === "string" ? body.botToken.trim() : "";const appToken = typeof body.appToken === "string" ? body.appToken.trim() : "";@@ -123,3 +128,20 @@ export async function getSlackEmojiList(ctx: ApiCtx): Promise<void> {return sendJson(ctx.res, 502, { error: "slack_unreachable", message: errMessage(error) });}}++export async function startSlackInstallation(ctx: ApiCtx): Promise<void> {+ const actor = await authorizeAdmin(ctx, orgScope(ctx.deps));+ if (!actor) return;+ if (!ctx.deps.managedSlack) return sendJson(ctx.res, 404, { error: "not_configured" });+ try {+ const result = await ctx.deps.managedSlack.start();+ return sendJson(ctx.res, 200, result);+ } catch {+ return sendJson(ctx.res, 502, { error: "slack_installation_unavailable" });+ }+}++export async function managedSlackRequest(ctx: ApiCtx): Promise<void> {+ if (!ctx.deps.managedSlack) return sendJson(ctx.res, 404, { error: "not_configured" });+ await ctx.deps.managedSlack.handle(ctx.req, ctx.res, ctx.body);+}diff --git a/src/index.ts b/src/index.tsindex fc55470cb..1890d8e4b 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,3 +1,4 @@+import { createManagedSlack } from "./surfaces/slack-managed.ts";import { randomBytes } from "node:crypto";import { lookup } from "node:dns/promises";import { loadConfig } from "./config.ts";@@ -22,7 +23,19 @@ const envSlackAttempted = Boolean(process.env.SLACK_BOT_TOKEN || process.env.SLAlet slackEnvironmentState: "absent" | "configured" | "partial" = "absent";if (slackConfig) slackEnvironmentState = "configured";else if (envSlackAttempted) slackEnvironmentState = "partial";-const server = createServer(built.app, serverDeps(config, built, slackEnvironmentState, envSlackConfig?.botToken));+const managedSlack = process.env.QM_SLACK_SERVICE_URL+ ? createManagedSlack({+ serviceUrl: process.env.QM_SLACK_SERVICE_URL,+ token: process.env.QM_SLACK_SERVICE_TOKEN ?? "",+ appId: process.env.QM_SLACK_APP_ID ?? "",+ store: built.slackInstallation,+ reconcile: config.backgroundWorkEnabled ? () => slackRuntime.reconcile() : undefined,+ })+ : undefined;+const server = createServer(built.app, {+ ...serverDeps(config, built, slackEnvironmentState, envSlackConfig?.botToken),+ managedSlack,+});await built.config.hydrate?.();await built.refreshCustomProviders();@@ -76,11 +89,16 @@ const slackRuntime = createSlackRuntimeReconciler({const status = await built.slackInstallation.status();const stored = await built.slackInstallation.get();if (stored) {- const dynamic = slackPluginConfigFromEnv({- ...process.env,- SLACK_BOT_TOKEN: stored.botToken,- SLACK_APP_TOKEN: stored.appToken,- });+ if (stored.installId && !managedSlack) return null;+ const dynamic = slackPluginConfigFromEnv(+ {+ ...process.env,+ SLACK_BOT_TOKEN: stored.botToken,+ SLACK_APP_TOKEN: stored.appToken,+ },+ stored.installId && managedSlack ? (staging) => managedSlack.receiver(stored.installId!, staging) : undefined,+ );+ if (dynamic && stored.installId) dynamic.installationId = stored.installId;return dynamic ? { version: stored.version, config: dynamic } : null;}if (status.managed) return null;diff --git a/src/slack/config.ts b/src/slack/config.tsindex 53deb6a13..0aea51432 100644--- a/src/slack/config.ts+++ b/src/slack/config.ts@@ -1,9 +1,13 @@+import type { Receiver } from "@slack/bolt";+import type { EnvelopeStaging } from "./envelope-staging.ts";import { botIdentityFromEnv } from "./delivery.ts";import { normalizeAllowFrom, parseAllowFrom } from "./allow-from.ts";export const NO_RETRY = { retryConfig: { retries: 0 } } as const;export interface SlackPluginConfig {+ installationId?: string;+ receiverFactory?: (staging?: EnvelopeStaging) => Receiver;botToken: string;accountId?: string;allowFrom?: string[];@@ -41,11 +45,14 @@ export function parseAckEmoji(raw: string | undefined): string[] {return out;}-export function slackPluginConfigFromEnv(env: Record<string, string | undefined>): SlackPluginConfig | null {+export function slackPluginConfigFromEnv(+ env: Record<string, string | undefined>,+ receiverFactory?: SlackPluginConfig["receiverFactory"],+): SlackPluginConfig | null {const eventsMode = env.SLACK_EVENTS_MODE?.trim() === "http" ? "http" : "socket";if (!env.SLACK_BOT_TOKEN) return null;- if (eventsMode === "socket" && !env.SLACK_APP_TOKEN) return null;- if (eventsMode === "http" && !env.SLACK_SIGNING_SECRET) return null;+ if (!receiverFactory && eventsMode === "socket" && !env.SLACK_APP_TOKEN) return null;+ if (!receiverFactory && eventsMode === "http" && !env.SLACK_SIGNING_SECRET) return null;const num = (v: string | undefined): number | undefined => {const n = Number(v);return Number.isFinite(n) && n > 0 ? n : undefined;@@ -56,6 +63,7 @@ export function slackPluginConfigFromEnv(env: Record<string, string | undefined>): Partial<SlackPluginConfig> => (value === undefined ? {} : ({ [key]: value } as Partial<SlackPluginConfig>));return {botToken: env.SLACK_BOT_TOKEN,+ ...(receiverFactory ? { receiverFactory } : {}),...opt("appToken", env.SLACK_APP_TOKEN),...opt("apiUrl", env.SLACK_API_URL),...(eventsMode === "http" ? { eventsMode } : {}),diff --git a/src/slack/index.ts b/src/slack/index.tsindex f9225c782..85f0e6d1f 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -43,10 +43,10 @@ export async function startSlackPlugin(if (!cfg.botToken) {throw new Error("Slack plugin needs botToken (SLACK_BOT_TOKEN, xoxb-…)");}- if (EVENTS_MODE === "socket" && !cfg.appToken) {+ if (!cfg.receiverFactory && EVENTS_MODE === "socket" && !cfg.appToken) {throw new Error("Slack plugin needs appToken (SLACK_APP_TOKEN, xapp-…) in socket events mode");}- if (EVENTS_MODE === "http" && (!cfg.signingSecret || !cfg.eventsPort)) {+ if (!cfg.receiverFactory && EVENTS_MODE === "http" && (!cfg.signingSecret || !cfg.eventsPort)) {throw new Error("Slack plugin needs signingSecret (SLACK_SIGNING_SECRET) and eventsPort (SLACK_EVENTS_PORT) in http events mode",);@@ -140,33 +140,37 @@ export async function startSlackPlugin(}}+ const stagingAccount = cfg.installationId ? `${ACCOUNT_LABEL}:${cfg.installationId}` : ACCOUNT_LABEL;const staging = core.stagedEnvelopes- ? createEnvelopeStaging(core.stagedEnvelopes, { account: ACCOUNT_LABEL })+ ? createEnvelopeStaging(core.stagedEnvelopes, { account: stagingAccount }): undefined;+ const receiver = () => {+ if (cfg.receiverFactory) return cfg.receiverFactory(staging);+ return EVENTS_MODE === "http"+ ? createHttpEventsReceiver({+ signingSecret: cfg.signingSecret!,+ port: cfg.eventsPort!,+ ...(cfg.ackCapMs !== undefined ? { capMs: cfg.ackCapMs } : {}),+ ...(staging ? { staging } : {}),+ })+ : createDeferredAckReceiver({+ appToken: APP_TOKEN!,+ ...(cfg.logLevel ? { logLevel: cfg.logLevel } : {}),+ ...(SLACK_API_URL ? { slackApiUrl: SLACK_API_URL } : {}),+ ...(cfg.ackCapMs !== undefined ? { capMs: cfg.ackCapMs } : {}),+ ...(staging ? { staging } : {}),+ });+ };const app = new App({token: BOT_TOKEN,- receiver:- EVENTS_MODE === "http"- ? createHttpEventsReceiver({- signingSecret: cfg.signingSecret!,- port: cfg.eventsPort!,- ...(cfg.ackCapMs !== undefined ? { capMs: cfg.ackCapMs } : {}),- ...(staging ? { staging } : {}),- })- : createDeferredAckReceiver({- appToken: APP_TOKEN!,- ...(cfg.logLevel ? { logLevel: cfg.logLevel } : {}),- ...(SLACK_API_URL ? { slackApiUrl: SLACK_API_URL } : {}),- ...(cfg.ackCapMs !== undefined ? { capMs: cfg.ackCapMs } : {}),- ...(staging ? { staging } : {}),- }),+ receiver: receiver(),logLevel: parseLogLevel(cfg.logLevel),clientOptions: { ...CLIENT_OPTIONS },});const replaySweeper = staging? createSweeper(() =>- core.holdEnvelopeReplay(ACCOUNT_LABEL, () =>+ core.holdEnvelopeReplay(stagingAccount, () =>staging.sweep((body, ackGate) =>app.processEvent({body,diff --git a/src/surfaces/slack-installation.ts b/src/surfaces/slack-installation.tsindex 70f21e769..fd6b11ca9 100644--- a/src/surfaces/slack-installation.ts+++ b/src/surfaces/slack-installation.ts@@ -5,7 +5,10 @@ interface ActiveSlackInstallation {orgId: string;disabled: false;botTokenEnc: string;- appTokenEnc: string;+ appTokenEnc?: string;+ appId?: string;+ installId?: string;+ installedAt?: number;teamId?: string;teamName?: string;updatedAt: number;@@ -14,6 +17,7 @@ interface ActiveSlackInstallation {}interface DisabledSlackInstallation {+ installedAt?: number;orgId: string;disabled: true;updatedAt: number;@@ -25,7 +29,10 @@ type StoredSlackInstallation = ActiveSlackInstallation | DisabledSlackInstallatiinterface SlackInstallation {botToken: string;- appToken: string;+ appToken?: string;+ appId?: string;+ installId?: string;+ installedAt?: number;teamId?: string;teamName?: string;updatedAt: number;@@ -48,12 +55,24 @@ export interface SlackInstallationStore {status(): Promise<SlackInstallationStatus>;set(input: {botToken: string;- appToken: string;+ appToken?: string;+ appId?: string;+ installId?: string;+ installedAt?: number;teamId?: string;teamName?: string;updatedBy: string;}): Promise<SlackInstallationStatus>;delete(updatedBy: string): Promise<void>;+ setManaged(input: {+ botToken: string;+ appId: string;+ installId: string;+ installedAt: number;+ teamId: string;+ teamName?: string;+ }): Promise<boolean>;+ disableManaged(installId: string): Promise<boolean>;}export function createSlackInstallationStore(@@ -80,7 +99,10 @@ export function createSlackInstallationStore(if (!record || record.disabled) return null;return {botToken: decryptSecret(record.botTokenEnc, key),- appToken: decryptSecret(record.appTokenEnc, key),+ ...(record.appTokenEnc ? { appToken: decryptSecret(record.appTokenEnc, key) } : {}),+ ...(record.appId ? { appId: record.appId } : {}),+ ...(record.installId ? { installId: record.installId } : {}),+ ...(record.installedAt ? { installedAt: record.installedAt } : {}),...(record.teamId ? { teamId: record.teamId } : {}),...(record.teamName ? { teamName: record.teamName } : {}),updatedAt: record.updatedAt,@@ -97,7 +119,9 @@ export function createSlackInstallationStore(orgId,disabled: false,botTokenEnc: encryptSecret(input.botToken, key),- appTokenEnc: encryptSecret(input.appToken, key),+ ...(input.appToken ? { appTokenEnc: encryptSecret(input.appToken, key) } : {}),+ ...(input.appId ? { appId: input.appId } : {}),+ ...(input.installId ? { installId: input.installId } : {}),...(input.teamId ? { teamId: input.teamId } : {}),...(input.teamName ? { teamName: input.teamName } : {}),updatedAt,@@ -107,7 +131,70 @@ export function createSlackInstallationStore(await map.put(orgId, record);return publicStatus(record);},+ async setManaged(input) {+ if (!map.update) throw new Error("Atomic installation updates are required");+ await map.putIfAbsent(orgId, {+ orgId,+ disabled: true,+ updatedAt: 0,+ updatedBy: "slack-service",+ version: "initial",+ });+ let accepted = false;+ await map.update(orgId, (record) => {+ if (!record.disabled && record.installId === input.installId) {+ accepted =+ record.teamId === input.teamId && record.appId === input.appId && record.installedAt === input.installedAt;+ return record;+ }+ if ((record.installedAt ?? 0) >= input.installedAt || (!record.disabled && record.teamId !== input.teamId))+ return record;+ accepted = true;+ return {+ orgId,+ disabled: false,+ botTokenEnc: encryptSecret(input.botToken, key),+ appId: input.appId,+ installId: input.installId,+ installedAt: input.installedAt,+ teamId: input.teamId,+ ...(input.teamName ? { teamName: input.teamName } : {}),+ updatedAt: Date.now(),+ updatedBy: "slack-service",+ version: crypto.randomUUID(),+ };+ });+ return accepted;+ },+ async disableManaged(installId) {+ if (!map.update) throw new Error("Atomic installation updates are required");+ let disabled = false;+ await map.update(orgId, (record) => {+ if (record.disabled || record.installId !== installId) return record;+ disabled = true;+ return {+ orgId,+ disabled: true,+ installedAt: record.installedAt,+ updatedAt: Date.now(),+ updatedBy: "slack-service",+ version: crypto.randomUUID(),+ };+ });+ return disabled;+ },async delete(updatedBy) {+ if (map.update) {+ const record = await map.update(orgId, (current) => ({+ orgId,+ disabled: true,+ ...(current.installedAt ? { installedAt: current.installedAt } : {}),+ updatedAt: Date.now(),+ updatedBy,+ version: crypto.randomUUID(),+ }));+ if (record) return;+ }const updatedAt = Date.now();await map.put(orgId, {orgId,diff --git a/src/surfaces/slack-managed.ts b/src/surfaces/slack-managed.tsnew file mode 100644index 000000000..0c2723e99--- /dev/null+++ b/src/surfaces/slack-managed.ts@@ -0,0 +1,146 @@+import { timingSafeEqual } from "node:crypto";+import type { IncomingMessage, ServerResponse } from "node:http";+import type { App as BoltApp, Receiver } from "@slack/bolt";+import type { SlackInstallationStore } from "./slack-installation.ts";+import type { EnvelopeStaging } from "../slack/envelope-staging.ts";+import {+ createDeferredEnvelopeAck,+ describeEnvelope,+ envelopeStageFor,+ isGatedEnvelope,+} from "../slack/deferred-ack.ts";+import { sendJson } from "../api/http.ts";++export function createManagedSlack(opts: {+ serviceUrl: string;+ token: string;+ appId: string;+ store: SlackInstallationStore;+ fetchImpl?: typeof fetch;+ reconcile?: () => Promise<void>;+}) {+ const serviceUrl = new URL(opts.serviceUrl);+ if (serviceUrl.protocol !== "https:" || serviceUrl.username || serviceUrl.password || !opts.token || !opts.appId) {+ throw new Error("Managed Slack requires an HTTPS service URL, credential, and app ID");+ }+ let active: { app: BoltApp; installId: string; staging?: EnvelopeStaging } | undefined;+ const authenticated = (req: IncomingMessage): boolean => {+ const actual = Buffer.from(req.headers.authorization ?? "");+ const expected = Buffer.from(`Bearer ${opts.token}`);+ return actual.length === expected.length && timingSafeEqual(actual, expected);+ };+ return {+ async start(): Promise<{ url: string }> {+ const response = await (opts.fetchImpl ?? fetch)(new URL("/install/start", serviceUrl), {+ method: "POST",+ headers: { authorization: `Bearer ${opts.token}`, "content-type": "application/json" },+ body: "{}",+ signal: AbortSignal.timeout(10_000),+ redirect: "error",+ });+ if (!response.ok) throw new Error("Slack installation service is unavailable");+ const data = (await response.json()) as { url?: unknown };+ if (typeof data.url !== "string" || new URL(data.url).origin !== serviceUrl.origin) {+ throw new Error("Slack installation service returned an invalid URL");+ }+ return { url: data.url };+ },+ receiver(installId: string, staging?: EnvelopeStaging): Receiver {+ let instance: typeof active;+ return {+ init(app) {+ instance = { app, installId, staging };+ },+ async start() {+ active = instance;+ },+ async stop() {+ if (active === instance) active = undefined;+ },+ } as Receiver;+ },+ async handle(req: IncomingMessage, res: ServerResponse, value: unknown): Promise<void> {+ if (!authenticated(req)) return sendJson(res, 401, { error: "unauthorized" });+ if (!value || typeof value !== "object" || Array.isArray(value))+ return sendJson(res, 400, { error: "invalid_body" });+ const input = value as Record<string, unknown>;+ if (typeof input.installId !== "string" || !input.installId || input.installId.length > 200) {+ return sendJson(res, 400, { error: "invalid_installation" });+ }+ const stored = await opts.store.get();+ if ((req.url ?? "").split("?")[0] === "/v1/slack/managed/installation") {+ if (req.method === "DELETE") {+ await opts.store.disableManaged(input.installId);+ void opts.reconcile?.().catch(() => undefined);+ return sendJson(res, 200, { ok: true });+ }+ if (+ typeof input.installedAt !== "number" ||+ !Number.isSafeInteger(input.installedAt) ||+ input.installedAt <= 0 ||+ input.appId !== opts.appId ||+ typeof input.teamId !== "string" ||+ !/^T[A-Z0-9]+$/.test(input.teamId) ||+ typeof input.botToken !== "string" ||+ !input.botToken.startsWith("xoxb-") ||+ (input.teamName !== undefined && typeof input.teamName !== "string")+ ) {+ return sendJson(res, 400, { error: "invalid_installation" });+ }+ const accepted = await opts.store.setManaged({+ botToken: input.botToken,+ appId: opts.appId,+ installId: input.installId,+ installedAt: input.installedAt,+ teamId: input.teamId,+ ...(typeof input.teamName === "string" ? { teamName: input.teamName } : {}),+ });+ if (!accepted) return sendJson(res, 409, { error: "installation_conflict" });+ void opts.reconcile?.().catch(() => undefined);+ const ready = active?.installId === input.installId;+ return sendJson(res, ready ? 200 : 202, { ok: true, ready });+ }+ if (!stored || stored.installId !== input.installId || stored.appId !== opts.appId) {+ return sendJson(res, 409, { error: "installation_mismatch" });+ }+ const body = input.body as Record<string, unknown> | undefined;+ if (+ !body ||+ typeof body !== "object" ||+ Array.isArray(body) ||+ body.api_app_id !== opts.appId ||+ (body.team_id ?? (body.team as { id?: unknown } | undefined)?.id) !== stored.teamId+ ) {+ return sendJson(res, 400, { error: "workspace_mismatch" });+ }+ const runtime = active;+ if (!runtime || runtime.installId !== input.installId) return sendJson(res, 503, { error: "slack_not_ready" });+ await new Promise<void>((resolve) => {+ const respond = (status: number, payload: unknown) => {+ sendJson(res, status, payload);+ resolve();+ };+ const { ack, gate } = createDeferredEnvelopeAck(async (payload) => respond(200, payload ?? {}), {+ gated: isGatedEnvelope(body),+ label: describeEnvelope(body),+ onWithhold: () => respond(503, { error: "not_persisted" }),+ ...envelopeStageFor(runtime.staging, body),+ });+ void runtime.app+ .processEvent({+ body,+ ack,+ ...(typeof input.retryNum === "number" ? { retryNum: input.retryNum } : {}),+ ...(typeof input.retryReason === "string" ? { retryReason: input.retryReason } : {}),+ customProperties: { ackGate: gate },+ })+ .then(+ () => gate.persisted(),+ () => gate.failed("delivery failed"),+ );+ });+ },+ };+}++export type ManagedSlack = ReturnType<typeof createManagedSlack>;diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.tsindex b5ddfb553..c23a3a9be 100644--- a/test/route-auth-conformance.test.ts+++ b/test/route-auth-conformance.test.ts@@ -5,7 +5,11 @@ import { findRoute, type RouteAuth } from "../src/api/routes/route.ts";import { agentApiMatches } from "../src/api/agent-api-catalog.ts";import { OAUTH_CONSENT_AUD, CREDENTIAL_BROKER_AUD } from "../src/auth/capability-token.ts";-const PUBLIC_ROUTES = new Set<string>([]);+const PUBLIC_ROUTES = new Set<string>([+ "POST /v1/slack/managed/installation",+ "DELETE /v1/slack/managed/installation",+ "POST /v1/slack/managed/events",+]);const AUD_ROUTES = new Map<string, string>([["POST /v1/connectors/oauth/consent/mint", OAUTH_CONSENT_AUD],["POST /v1/credentials/broker", CREDENTIAL_BROKER_AUD],diff --git a/test/slack-managed.test.ts b/test/slack-managed.test.tsnew file mode 100644index 000000000..9b1b50227--- /dev/null+++ b/test/slack-managed.test.ts@@ -0,0 +1,173 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import test from "node:test";+import type { App as BoltApp, ReceiverEvent } from "@slack/bolt";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { createSlackInstallationStore } from "../src/surfaces/slack-installation.ts";+import { createManagedSlack } from "../src/surfaces/slack-managed.ts";++const installation = {+ botToken: "xoxb-test",+ appId: "A123",+ teamId: "T123",+ installId: "install-1",+ installedAt: 1000,+};+const event = {+ type: "event_callback",+ api_app_id: "A123",+ team_id: "T123",+ event_id: "Ev123",+ event: { type: "message", channel: "C123", user: "U123", ts: "1.0", text: "hello" },+};++async function fixture(t: test.TestContext) {+ const map = createMemoryMap();+ const store = createSlackInstallationStore(+ "company",+ map as Parameters<typeof createSlackInstallationStore>[1],+ "test-encryption-key",+ );+ const bridge = createManagedSlack({+ serviceUrl: "https://slack.example.com",+ token: "company-token",+ appId: "A123",+ store,+ });+ const server = createServer(async (req, res) => {+ let raw = "";+ for await (const chunk of req) raw += String(chunk);+ await bridge.handle(req, res, JSON.parse(raw));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));+ const address = server.address();+ assert(address && typeof address === "object");+ return {+ map,+ store,+ bridge,+ request: (+ path: "installation" | "events",+ body: unknown,+ method: "POST" | "DELETE" = "POST",+ token = "company-token",+ ) =>+ fetch(`http://127.0.0.1:${address.port}/v1/slack/managed/${path}`, {+ method,+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },+ body: JSON.stringify(body),+ }),+ };+}++test("managed installation encrypts bot-only credentials and waits for its receiver", async (t) => {+ const { request, map, store, bridge } = await fixture(t);+ assert.equal((await request("installation", installation, "POST", "wrong-company")).status, 401);+ assert.equal(await store.get(), null);+ assert.equal((await request("installation", installation)).status, 202);+ assert.equal((await store.get())?.appToken, undefined);+ assert.equal(JSON.stringify(await map.all()).includes("xoxb-test"), false);+ const receiver = bridge.receiver(installation.installId);+ receiver.init?.({ processEvent: async () => {} } as unknown as BoltApp);+ await receiver.start(0 as never);+ assert.equal((await request("installation", installation)).status, 200);+ await receiver.stop(0 as never);+ assert.equal((await request("installation", installation)).status, 202);+});++test("managed generations cannot overwrite newer installs or revive removed credentials", async (t) => {+ const { request, store } = await fixture(t);+ await request("installation", installation);+ const replacement = { ...installation, installId: "install-2", installedAt: 2000 };+ assert.equal((await request("installation", replacement)).status, 202);+ assert.equal((await request("installation", installation)).status, 409);+ await request("installation", { installId: "install-1" }, "DELETE");+ assert.equal((await store.get())?.installId, "install-2");+ assert.equal(+ (await request("installation", { ...replacement, installId: "install-3", installedAt: 3000, teamId: "TOTHER" }))+ .status,+ 409,+ );+ await request("installation", { installId: "install-2" }, "DELETE");+ assert.equal(await store.get(), null);+ assert.equal((await request("installation", replacement)).status, 409);+ assert.equal(+ (await request("installation", { ...replacement, installId: "install-3", installedAt: 3000 })).status,+ 202,+ );+ await store.delete("admin");+ assert.equal(+ (await request("installation", { ...replacement, installId: "install-3", installedAt: 3000 })).status,+ 409,+ );+});++test("managed delivery isolates workspace, app, generation, and credentials and preserves button responses", async (t) => {+ const { request, bridge } = await fixture(t);+ await request("installation", installation);+ const body = { installId: installation.installId, body: event, retryNum: 1, retryReason: "timeout" };+ assert.equal((await request("events", body)).status, 503);+ const received: ReceiverEvent[] = [];+ const receiver = bridge.receiver(installation.installId);+ receiver.init?.({+ processEvent: async (incoming: ReceiverEvent) => {+ received.push(incoming);+ await incoming.ack({ text: "Accepted" });+ },+ } as unknown as BoltApp);+ await receiver.start(0 as never);+ assert.equal((await request("events", body, "POST", "wrong-company")).status, 401);+ assert.equal((await request("events", { ...body, installId: "old" })).status, 409);+ assert.equal((await request("events", { ...body, body: { ...event, team_id: "TOTHER" } })).status, 400);+ assert.equal((await request("events", { ...body, body: { ...event, api_app_id: "AOTHER" } })).status, 400);+ assert.equal(received.length, 0);+ assert.equal((await request("events", body)).status, 200);+ assert.equal(received[0]?.retryNum, 1);+ const button = {+ type: "block_actions",+ api_app_id: "A123",+ team: { id: "T123" },+ actions: [{ action_id: "approve" }],+ };+ const response = await request("events", { installId: installation.installId, body: button });+ assert.deepEqual(await response.json(), { text: "Accepted" });+ await request("installation", { installId: installation.installId }, "DELETE");+ assert.equal((await request("events", body)).status, 409);+});++test("failed delivery withholds acknowledgment", async (t) => {+ const { request, bridge } = await fixture(t);+ await request("installation", installation);+ const receiver = bridge.receiver(installation.installId);+ receiver.init?.({+ processEvent: async () => {+ throw new Error("database unavailable");+ },+ } as unknown as BoltApp);+ await receiver.start(0 as never);+ assert.equal((await request("events", { installId: installation.installId, body: event })).status, 503);+});++test("installation launch restricts redirect origin and hides service credentials", async () => {+ const store = createSlackInstallationStore("company", createMemoryMap(), "test-key");+ const bridge = createManagedSlack({+ serviceUrl: "https://slack.example.com",+ token: "company-token",+ appId: "A123",+ store,+ fetchImpl: (async (_url: unknown, init?: RequestInit) => {+ assert.equal(new Headers(init?.headers).get("authorization"), "Bearer company-token");+ return Response.json({ url: "https://slack.example.com/install/launch?id=opaque" });+ }) as typeof fetch,+ });+ assert.deepEqual(await bridge.start(), { url: "https://slack.example.com/install/launch?id=opaque" });+ const bad = createManagedSlack({+ serviceUrl: "https://slack.example.com",+ token: "company-token",+ appId: "A123",+ store,+ fetchImpl: (async () => Response.json({ url: "https://evil.example" })) as typeof fetch,+ });+ await assert.rejects(bad.start(), /invalid URL/);+});